blob: a1bb5e0838a4bd1b20cc9c86edc83f36128c0da7 [file] [log] [blame]
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "code_generator.h"
18
Alex Light50fa9932015-08-10 15:30:07 -070019#ifdef ART_ENABLE_CODEGEN_arm
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000020#include "code_generator_arm.h"
Alex Light50fa9932015-08-10 15:30:07 -070021#endif
22
23#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames5319def2014-10-23 10:03:10 +010024#include "code_generator_arm64.h"
Alex Light50fa9932015-08-10 15:30:07 -070025#endif
26
27#ifdef ART_ENABLE_CODEGEN_x86
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000028#include "code_generator_x86.h"
Alex Light50fa9932015-08-10 15:30:07 -070029#endif
30
31#ifdef ART_ENABLE_CODEGEN_x86_64
Nicolas Geoffray9cf35522014-06-09 18:40:10 +010032#include "code_generator_x86_64.h"
Alex Light50fa9932015-08-10 15:30:07 -070033#endif
34
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020035#ifdef ART_ENABLE_CODEGEN_mips
36#include "code_generator_mips.h"
37#endif
38
Alex Light50fa9932015-08-10 15:30:07 -070039#ifdef ART_ENABLE_CODEGEN_mips64
Alexey Frunze4dda3372015-06-01 18:31:49 -070040#include "code_generator_mips64.h"
Alex Light50fa9932015-08-10 15:30:07 -070041#endif
42
Yevgeny Roubane3ea8382014-08-08 16:29:38 +070043#include "compiled_method.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000044#include "dex/verified_method.h"
45#include "driver/dex_compilation_unit.h"
46#include "gc_map_builder.h"
Alexandre Rameseb7b7392015-06-19 14:47:01 +010047#include "graph_visualizer.h"
Nicolas Geoffray5bd05a52015-10-13 09:48:30 +010048#include "intrinsics.h"
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +000049#include "leb128.h"
50#include "mapping_table.h"
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +010051#include "mirror/array-inl.h"
52#include "mirror/object_array-inl.h"
53#include "mirror/object_reference.h"
Alex Light50fa9932015-08-10 15:30:07 -070054#include "parallel_move_resolver.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010055#include "ssa_liveness_analysis.h"
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000056#include "utils/assembler.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000057#include "verifier/dex_gc_map.h"
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +000058#include "vmap_table.h"
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000059
60namespace art {
61
Alexandre Rames88c13cd2015-04-14 17:35:39 +010062// Return whether a location is consistent with a type.
63static bool CheckType(Primitive::Type type, Location location) {
64 if (location.IsFpuRegister()
65 || (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresFpuRegister))) {
66 return (type == Primitive::kPrimFloat) || (type == Primitive::kPrimDouble);
67 } else if (location.IsRegister() ||
68 (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresRegister))) {
69 return Primitive::IsIntegralType(type) || (type == Primitive::kPrimNot);
70 } else if (location.IsRegisterPair()) {
71 return type == Primitive::kPrimLong;
72 } else if (location.IsFpuRegisterPair()) {
73 return type == Primitive::kPrimDouble;
74 } else if (location.IsStackSlot()) {
75 return (Primitive::IsIntegralType(type) && type != Primitive::kPrimLong)
76 || (type == Primitive::kPrimFloat)
77 || (type == Primitive::kPrimNot);
78 } else if (location.IsDoubleStackSlot()) {
79 return (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble);
80 } else if (location.IsConstant()) {
81 if (location.GetConstant()->IsIntConstant()) {
82 return Primitive::IsIntegralType(type) && (type != Primitive::kPrimLong);
83 } else if (location.GetConstant()->IsNullConstant()) {
84 return type == Primitive::kPrimNot;
85 } else if (location.GetConstant()->IsLongConstant()) {
86 return type == Primitive::kPrimLong;
87 } else if (location.GetConstant()->IsFloatConstant()) {
88 return type == Primitive::kPrimFloat;
89 } else {
90 return location.GetConstant()->IsDoubleConstant()
91 && (type == Primitive::kPrimDouble);
92 }
93 } else {
94 return location.IsInvalid() || (location.GetPolicy() == Location::kAny);
95 }
96}
97
98// Check that a location summary is consistent with an instruction.
99static bool CheckTypeConsistency(HInstruction* instruction) {
100 LocationSummary* locations = instruction->GetLocations();
101 if (locations == nullptr) {
102 return true;
103 }
104
105 if (locations->Out().IsUnallocated()
106 && (locations->Out().GetPolicy() == Location::kSameAsFirstInput)) {
107 DCHECK(CheckType(instruction->GetType(), locations->InAt(0)))
108 << instruction->GetType()
109 << " " << locations->InAt(0);
110 } else {
111 DCHECK(CheckType(instruction->GetType(), locations->Out()))
112 << instruction->GetType()
113 << " " << locations->Out();
114 }
115
116 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
117 DCHECK(CheckType(instruction->InputAt(i)->GetType(), locations->InAt(i)))
118 << instruction->InputAt(i)->GetType()
119 << " " << locations->InAt(i);
120 }
121
122 HEnvironment* environment = instruction->GetEnvironment();
123 for (size_t i = 0; i < instruction->EnvironmentSize(); ++i) {
124 if (environment->GetInstructionAt(i) != nullptr) {
125 Primitive::Type type = environment->GetInstructionAt(i)->GetType();
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100126 DCHECK(CheckType(type, environment->GetLocationAt(i)))
127 << type << " " << environment->GetLocationAt(i);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100128 } else {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100129 DCHECK(environment->GetLocationAt(i).IsInvalid())
130 << environment->GetLocationAt(i);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100131 }
132 }
133 return true;
134}
135
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +0100136size_t CodeGenerator::GetCacheOffset(uint32_t index) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100137 return sizeof(GcRoot<mirror::Object>) * index;
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +0100138}
139
Mathieu Chartiere401d142015-04-22 13:56:20 -0700140size_t CodeGenerator::GetCachePointerOffset(uint32_t index) {
141 auto pointer_size = InstructionSetPointerSize(GetInstructionSet());
Vladimir Marko05792b92015-08-03 11:56:49 +0100142 return pointer_size * index;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700143}
144
Nicolas Geoffray73e80c32014-07-22 17:47:56 +0100145void CodeGenerator::CompileBaseline(CodeAllocator* allocator, bool is_leaf) {
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000146 Initialize();
Nicolas Geoffray73e80c32014-07-22 17:47:56 +0100147 if (!is_leaf) {
148 MarkNotLeaf();
149 }
Mathieu Chartiere3b034a2015-05-31 14:29:23 -0700150 const bool is_64_bit = Is64BitInstructionSet(GetInstructionSet());
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000151 InitializeCodeGeneration(GetGraph()->GetNumberOfLocalVRegs()
152 + GetGraph()->GetTemporariesVRegSlots()
153 + 1 /* filler */,
154 0, /* the baseline compiler does not have live registers at slow path */
155 0, /* the baseline compiler does not have live registers at slow path */
156 GetGraph()->GetMaximumNumberOfOutVRegs()
Mathieu Chartiere3b034a2015-05-31 14:29:23 -0700157 + (is_64_bit ? 2 : 1) /* current method */,
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000158 GetGraph()->GetBlocks());
159 CompileInternal(allocator, /* is_baseline */ true);
160}
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100161
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000162bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100163 DCHECK_EQ((*block_order_)[current_block_index_], current);
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000164 return GetNextBlockToEmit() == FirstNonEmptyBlock(next);
165}
166
167HBasicBlock* CodeGenerator::GetNextBlockToEmit() const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100168 for (size_t i = current_block_index_ + 1; i < block_order_->size(); ++i) {
169 HBasicBlock* block = (*block_order_)[i];
David Brazdilfc6a86a2015-06-26 10:33:45 +0000170 if (!block->IsSingleJump()) {
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000171 return block;
172 }
173 }
174 return nullptr;
175}
176
177HBasicBlock* CodeGenerator::FirstNonEmptyBlock(HBasicBlock* block) const {
David Brazdilfc6a86a2015-06-26 10:33:45 +0000178 while (block->IsSingleJump()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100179 block = block->GetSuccessors()[0];
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000180 }
181 return block;
182}
183
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100184class DisassemblyScope {
185 public:
186 DisassemblyScope(HInstruction* instruction, const CodeGenerator& codegen)
187 : codegen_(codegen), instruction_(instruction), start_offset_(static_cast<size_t>(-1)) {
188 if (codegen_.GetDisassemblyInformation() != nullptr) {
189 start_offset_ = codegen_.GetAssembler().CodeSize();
190 }
191 }
192
193 ~DisassemblyScope() {
194 // We avoid building this data when we know it will not be used.
195 if (codegen_.GetDisassemblyInformation() != nullptr) {
196 codegen_.GetDisassemblyInformation()->AddInstructionInterval(
197 instruction_, start_offset_, codegen_.GetAssembler().CodeSize());
198 }
199 }
200
201 private:
202 const CodeGenerator& codegen_;
203 HInstruction* instruction_;
204 size_t start_offset_;
205};
206
207
208void CodeGenerator::GenerateSlowPaths() {
209 size_t code_start = 0;
Vladimir Marko225b6462015-09-28 12:17:40 +0100210 for (SlowPathCode* slow_path : slow_paths_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100211 if (disasm_info_ != nullptr) {
212 code_start = GetAssembler()->CodeSize();
213 }
Vladimir Marko225b6462015-09-28 12:17:40 +0100214 slow_path->EmitNativeCode(this);
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100215 if (disasm_info_ != nullptr) {
Vladimir Marko225b6462015-09-28 12:17:40 +0100216 disasm_info_->AddSlowPathInterval(slow_path, code_start, GetAssembler()->CodeSize());
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100217 }
218 }
219}
220
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000221void CodeGenerator::CompileInternal(CodeAllocator* allocator, bool is_baseline) {
Roland Levillain3e3d7332015-04-28 11:00:54 +0100222 is_baseline_ = is_baseline;
Nicolas Geoffray8a16d972014-09-11 10:30:02 +0100223 HGraphVisitor* instruction_visitor = GetInstructionVisitor();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000224 DCHECK_EQ(current_block_index_, 0u);
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100225
226 size_t frame_start = GetAssembler()->CodeSize();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000227 GenerateFrameEntry();
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100228 DCHECK_EQ(GetAssembler()->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size_));
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100229 if (disasm_info_ != nullptr) {
230 disasm_info_->SetFrameEntryInterval(frame_start, GetAssembler()->CodeSize());
231 }
232
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100233 for (size_t e = block_order_->size(); current_block_index_ < e; ++current_block_index_) {
234 HBasicBlock* block = (*block_order_)[current_block_index_];
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000235 // Don't generate code for an empty block. Its predecessors will branch to its successor
236 // directly. Also, the label of that block will not be emitted, so this helps catch
237 // errors where we reference that label.
David Brazdilfc6a86a2015-06-26 10:33:45 +0000238 if (block->IsSingleJump()) continue;
Nicolas Geoffray92a73ae2014-10-16 11:12:52 +0100239 Bind(block);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100240 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
241 HInstruction* current = it.Current();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100242 DisassemblyScope disassembly_scope(current, *this);
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000243 if (is_baseline) {
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000244 InitLocationsBaseline(current);
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000245 }
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100246 DCHECK(CheckTypeConsistency(current));
Yevgeny Rouban2a7c1ef2015-07-22 18:36:24 +0600247 uintptr_t native_pc_begin = GetAssembler()->CodeSize();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100248 current->Accept(instruction_visitor);
Yevgeny Rouban2a7c1ef2015-07-22 18:36:24 +0600249 uintptr_t native_pc_end = GetAssembler()->CodeSize();
250 RecordNativeDebugInfo(current->GetDexPc(), native_pc_begin, native_pc_end);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100251 }
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000252 }
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000253
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100254 GenerateSlowPaths();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000255
David Brazdil77a48ae2015-09-15 12:34:04 +0000256 // Emit catch stack maps at the end of the stack map stream as expected by the
257 // runtime exception handler.
258 if (!is_baseline && graph_->HasTryCatch()) {
259 RecordCatchBlockInfo();
260 }
261
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000262 // Finalize instructions in assember;
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000263 Finalize(allocator);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000264}
265
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100266void CodeGenerator::CompileOptimized(CodeAllocator* allocator) {
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000267 // The register allocator already called `InitializeCodeGeneration`,
268 // where the frame size has been computed.
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000269 DCHECK(block_order_ != nullptr);
Nicolas Geoffray92a73ae2014-10-16 11:12:52 +0100270 Initialize();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000271 CompileInternal(allocator, /* is_baseline */ false);
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000272}
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100273
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000274void CodeGenerator::Finalize(CodeAllocator* allocator) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100275 size_t code_size = GetAssembler()->CodeSize();
276 uint8_t* buffer = allocator->Allocate(code_size);
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000277
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100278 MemoryRegion code(buffer, code_size);
279 GetAssembler()->FinalizeInstructions(code);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000280}
281
Vladimir Marko58155012015-08-19 12:49:41 +0000282void CodeGenerator::EmitLinkerPatches(ArenaVector<LinkerPatch>* linker_patches ATTRIBUTE_UNUSED) {
283 // No linker patches by default.
284}
285
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100286size_t CodeGenerator::FindFreeEntry(bool* array, size_t length) {
287 for (size_t i = 0; i < length; ++i) {
288 if (!array[i]) {
289 array[i] = true;
290 return i;
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100291 }
292 }
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100293 LOG(FATAL) << "Could not find a register in baseline register allocator";
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000294 UNREACHABLE();
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000295}
296
Nicolas Geoffray3c035032014-10-28 10:46:40 +0000297size_t CodeGenerator::FindTwoFreeConsecutiveAlignedEntries(bool* array, size_t length) {
298 for (size_t i = 0; i < length - 1; i += 2) {
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000299 if (!array[i] && !array[i + 1]) {
300 array[i] = true;
301 array[i + 1] = true;
302 return i;
303 }
304 }
305 LOG(FATAL) << "Could not find a register in baseline register allocator";
306 UNREACHABLE();
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100307}
308
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000309void CodeGenerator::InitializeCodeGeneration(size_t number_of_spill_slots,
310 size_t maximum_number_of_live_core_registers,
311 size_t maximum_number_of_live_fp_registers,
312 size_t number_of_out_slots,
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100313 const ArenaVector<HBasicBlock*>& block_order) {
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000314 block_order_ = &block_order;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100315 DCHECK(!block_order.empty());
316 DCHECK(block_order[0] == GetGraph()->GetEntryBlock());
Nicolas Geoffray4dee6362015-01-23 18:23:14 +0000317 ComputeSpillMask();
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100318 first_register_slot_in_slow_path_ = (number_of_out_slots + number_of_spill_slots) * kVRegSize;
319
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000320 if (number_of_spill_slots == 0
321 && !HasAllocatedCalleeSaveRegisters()
322 && IsLeafMethod()
323 && !RequiresCurrentMethod()) {
324 DCHECK_EQ(maximum_number_of_live_core_registers, 0u);
325 DCHECK_EQ(maximum_number_of_live_fp_registers, 0u);
326 SetFrameSize(CallPushesPC() ? GetWordSize() : 0);
327 } else {
328 SetFrameSize(RoundUp(
329 number_of_spill_slots * kVRegSize
330 + number_of_out_slots * kVRegSize
331 + maximum_number_of_live_core_registers * GetWordSize()
332 + maximum_number_of_live_fp_registers * GetFloatingPointSpillSlotSize()
333 + FrameEntrySpillSize(),
334 kStackAlignment));
335 }
Nicolas Geoffrayab032bc2014-07-15 12:55:21 +0100336}
337
338Location CodeGenerator::GetTemporaryLocation(HTemporary* temp) const {
339 uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs();
Calin Juravlef97f9fb2014-11-11 15:38:19 +0000340 // The type of the previous instruction tells us if we need a single or double stack slot.
341 Primitive::Type type = temp->GetType();
342 int32_t temp_size = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble) ? 2 : 1;
Nicolas Geoffrayab032bc2014-07-15 12:55:21 +0100343 // Use the temporary region (right below the dex registers).
344 int32_t slot = GetFrameSize() - FrameEntrySpillSize()
345 - kVRegSize // filler
346 - (number_of_locals * kVRegSize)
Calin Juravlef97f9fb2014-11-11 15:38:19 +0000347 - ((temp_size + temp->GetIndex()) * kVRegSize);
348 return temp_size == 2 ? Location::DoubleStackSlot(slot) : Location::StackSlot(slot);
Nicolas Geoffrayab032bc2014-07-15 12:55:21 +0100349}
350
351int32_t CodeGenerator::GetStackSlot(HLocal* local) const {
352 uint16_t reg_number = local->GetRegNumber();
353 uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs();
354 if (reg_number >= number_of_locals) {
355 // Local is a parameter of the method. It is stored in the caller's frame.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700356 // TODO: Share this logic with StackVisitor::GetVRegOffsetFromQuickCode.
357 return GetFrameSize() + InstructionSetPointerSize(GetInstructionSet()) // ART method
Nicolas Geoffrayab032bc2014-07-15 12:55:21 +0100358 + (reg_number - number_of_locals) * kVRegSize;
359 } else {
360 // Local is a temporary in this method. It is stored in this method's frame.
361 return GetFrameSize() - FrameEntrySpillSize()
362 - kVRegSize // filler.
363 - (number_of_locals * kVRegSize)
364 + (reg_number * kVRegSize);
365 }
366}
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100367
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100368void CodeGenerator::CreateCommonInvokeLocationSummary(
Nicolas Geoffray4e40c262015-06-03 12:02:38 +0100369 HInvoke* invoke, InvokeDexCallingConventionVisitor* visitor) {
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100370 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetArena();
371 LocationSummary* locations = new (allocator) LocationSummary(invoke, LocationSummary::kCall);
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100372
373 for (size_t i = 0; i < invoke->GetNumberOfArguments(); i++) {
374 HInstruction* input = invoke->InputAt(i);
375 locations->SetInAt(i, visitor->GetNextLocation(input->GetType()));
376 }
377
378 locations->SetOut(visitor->GetReturnLocation(invoke->GetType()));
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100379
380 if (invoke->IsInvokeStaticOrDirect()) {
381 HInvokeStaticOrDirect* call = invoke->AsInvokeStaticOrDirect();
Vladimir Markodc151b22015-10-15 18:02:30 +0100382 switch (call->GetMethodLoadKind()) {
383 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
384 locations->SetInAt(call->GetCurrentMethodInputIndex(), visitor->GetMethodLocation());
385 break;
386 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
387 locations->AddTemp(visitor->GetMethodLocation());
388 locations->SetInAt(call->GetCurrentMethodInputIndex(), Location::RequiresRegister());
389 break;
390 default:
391 locations->AddTemp(visitor->GetMethodLocation());
392 break;
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100393 }
394 } else {
395 locations->AddTemp(visitor->GetMethodLocation());
396 }
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100397}
398
Calin Juravle175dc732015-08-25 15:42:32 +0100399void CodeGenerator::GenerateInvokeUnresolvedRuntimeCall(HInvokeUnresolved* invoke) {
400 MoveConstant(invoke->GetLocations()->GetTemp(0), invoke->GetDexMethodIndex());
401
402 // Initialize to anything to silent compiler warnings.
403 QuickEntrypointEnum entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
404 switch (invoke->GetOriginalInvokeType()) {
405 case kStatic:
406 entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
407 break;
408 case kDirect:
409 entrypoint = kQuickInvokeDirectTrampolineWithAccessCheck;
410 break;
411 case kVirtual:
412 entrypoint = kQuickInvokeVirtualTrampolineWithAccessCheck;
413 break;
414 case kSuper:
415 entrypoint = kQuickInvokeSuperTrampolineWithAccessCheck;
416 break;
417 case kInterface:
418 entrypoint = kQuickInvokeInterfaceTrampolineWithAccessCheck;
419 break;
420 }
421 InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), nullptr);
422}
423
Calin Juravlee460d1d2015-09-29 04:52:17 +0100424void CodeGenerator::CreateUnresolvedFieldLocationSummary(
425 HInstruction* field_access,
426 Primitive::Type field_type,
427 const FieldAccessCallingConvention& calling_convention) {
428 bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
429 || field_access->IsUnresolvedInstanceFieldSet();
430 bool is_get = field_access->IsUnresolvedInstanceFieldGet()
431 || field_access->IsUnresolvedStaticFieldGet();
432
433 ArenaAllocator* allocator = field_access->GetBlock()->GetGraph()->GetArena();
434 LocationSummary* locations =
435 new (allocator) LocationSummary(field_access, LocationSummary::kCall);
436
437 locations->AddTemp(calling_convention.GetFieldIndexLocation());
438
439 if (is_instance) {
440 // Add the `this` object for instance field accesses.
441 locations->SetInAt(0, calling_convention.GetObjectLocation());
442 }
443
444 // Note that pSetXXStatic/pGetXXStatic always takes/returns an int or int64
445 // regardless of the the type. Because of that we forced to special case
446 // the access to floating point values.
447 if (is_get) {
448 if (Primitive::IsFloatingPointType(field_type)) {
449 // The return value will be stored in regular registers while register
450 // allocator expects it in a floating point register.
451 // Note We don't need to request additional temps because the return
452 // register(s) are already blocked due the call and they may overlap with
453 // the input or field index.
454 // The transfer between the two will be done at codegen level.
455 locations->SetOut(calling_convention.GetFpuLocation(field_type));
456 } else {
457 locations->SetOut(calling_convention.GetReturnLocation(field_type));
458 }
459 } else {
460 size_t set_index = is_instance ? 1 : 0;
461 if (Primitive::IsFloatingPointType(field_type)) {
462 // The set value comes from a float location while the calling convention
463 // expects it in a regular register location. Allocate a temp for it and
464 // make the transfer at codegen.
465 AddLocationAsTemp(calling_convention.GetSetValueLocation(field_type, is_instance), locations);
466 locations->SetInAt(set_index, calling_convention.GetFpuLocation(field_type));
467 } else {
468 locations->SetInAt(set_index,
469 calling_convention.GetSetValueLocation(field_type, is_instance));
470 }
471 }
472}
473
474void CodeGenerator::GenerateUnresolvedFieldAccess(
475 HInstruction* field_access,
476 Primitive::Type field_type,
477 uint32_t field_index,
478 uint32_t dex_pc,
479 const FieldAccessCallingConvention& calling_convention) {
480 LocationSummary* locations = field_access->GetLocations();
481
482 MoveConstant(locations->GetTemp(0), field_index);
483
484 bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
485 || field_access->IsUnresolvedInstanceFieldSet();
486 bool is_get = field_access->IsUnresolvedInstanceFieldGet()
487 || field_access->IsUnresolvedStaticFieldGet();
488
489 if (!is_get && Primitive::IsFloatingPointType(field_type)) {
490 // Copy the float value to be set into the calling convention register.
491 // Note that using directly the temp location is problematic as we don't
492 // support temp register pairs. To avoid boilerplate conversion code, use
493 // the location from the calling convention.
494 MoveLocation(calling_convention.GetSetValueLocation(field_type, is_instance),
495 locations->InAt(is_instance ? 1 : 0),
496 (Primitive::Is64BitType(field_type) ? Primitive::kPrimLong : Primitive::kPrimInt));
497 }
498
499 QuickEntrypointEnum entrypoint = kQuickSet8Static; // Initialize to anything to avoid warnings.
500 switch (field_type) {
501 case Primitive::kPrimBoolean:
502 entrypoint = is_instance
503 ? (is_get ? kQuickGetBooleanInstance : kQuickSet8Instance)
504 : (is_get ? kQuickGetBooleanStatic : kQuickSet8Static);
505 break;
506 case Primitive::kPrimByte:
507 entrypoint = is_instance
508 ? (is_get ? kQuickGetByteInstance : kQuickSet8Instance)
509 : (is_get ? kQuickGetByteStatic : kQuickSet8Static);
510 break;
511 case Primitive::kPrimShort:
512 entrypoint = is_instance
513 ? (is_get ? kQuickGetShortInstance : kQuickSet16Instance)
514 : (is_get ? kQuickGetShortStatic : kQuickSet16Static);
515 break;
516 case Primitive::kPrimChar:
517 entrypoint = is_instance
518 ? (is_get ? kQuickGetCharInstance : kQuickSet16Instance)
519 : (is_get ? kQuickGetCharStatic : kQuickSet16Static);
520 break;
521 case Primitive::kPrimInt:
522 case Primitive::kPrimFloat:
523 entrypoint = is_instance
524 ? (is_get ? kQuickGet32Instance : kQuickSet32Instance)
525 : (is_get ? kQuickGet32Static : kQuickSet32Static);
526 break;
527 case Primitive::kPrimNot:
528 entrypoint = is_instance
529 ? (is_get ? kQuickGetObjInstance : kQuickSetObjInstance)
530 : (is_get ? kQuickGetObjStatic : kQuickSetObjStatic);
531 break;
532 case Primitive::kPrimLong:
533 case Primitive::kPrimDouble:
534 entrypoint = is_instance
535 ? (is_get ? kQuickGet64Instance : kQuickSet64Instance)
536 : (is_get ? kQuickGet64Static : kQuickSet64Static);
537 break;
538 default:
539 LOG(FATAL) << "Invalid type " << field_type;
540 }
541 InvokeRuntime(entrypoint, field_access, dex_pc, nullptr);
542
543 if (is_get && Primitive::IsFloatingPointType(field_type)) {
544 MoveLocation(locations->Out(), calling_convention.GetReturnLocation(field_type), field_type);
545 }
546}
547
Calin Juravle98893e12015-10-02 21:05:03 +0100548void CodeGenerator::CreateLoadClassLocationSummary(HLoadClass* cls,
549 Location runtime_type_index_location,
550 Location runtime_return_location) {
551 ArenaAllocator* allocator = cls->GetBlock()->GetGraph()->GetArena();
552 LocationSummary::CallKind call_kind = cls->NeedsAccessCheck()
553 ? LocationSummary::kCall
554 : (cls->CanCallRuntime()
555 ? LocationSummary::kCallOnSlowPath
556 : LocationSummary::kNoCall);
557 LocationSummary* locations = new (allocator) LocationSummary(cls, call_kind);
Calin Juravle98893e12015-10-02 21:05:03 +0100558 if (cls->NeedsAccessCheck()) {
Calin Juravle580b6092015-10-06 17:35:58 +0100559 locations->SetInAt(0, Location::NoLocation());
Calin Juravle98893e12015-10-02 21:05:03 +0100560 locations->AddTemp(runtime_type_index_location);
561 locations->SetOut(runtime_return_location);
562 } else {
Calin Juravle580b6092015-10-06 17:35:58 +0100563 locations->SetInAt(0, Location::RequiresRegister());
Calin Juravle98893e12015-10-02 21:05:03 +0100564 locations->SetOut(Location::RequiresRegister());
565 }
566}
567
568
Mark Mendell5f874182015-03-04 15:42:45 -0500569void CodeGenerator::BlockIfInRegister(Location location, bool is_out) const {
570 // The DCHECKS below check that a register is not specified twice in
571 // the summary. The out location can overlap with an input, so we need
572 // to special case it.
573 if (location.IsRegister()) {
574 DCHECK(is_out || !blocked_core_registers_[location.reg()]);
575 blocked_core_registers_[location.reg()] = true;
576 } else if (location.IsFpuRegister()) {
577 DCHECK(is_out || !blocked_fpu_registers_[location.reg()]);
578 blocked_fpu_registers_[location.reg()] = true;
579 } else if (location.IsFpuRegisterPair()) {
580 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()]);
581 blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()] = true;
582 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()]);
583 blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()] = true;
584 } else if (location.IsRegisterPair()) {
585 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairLow<int>()]);
586 blocked_core_registers_[location.AsRegisterPairLow<int>()] = true;
587 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairHigh<int>()]);
588 blocked_core_registers_[location.AsRegisterPairHigh<int>()] = true;
589 }
590}
591
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100592void CodeGenerator::AllocateRegistersLocally(HInstruction* instruction) const {
593 LocationSummary* locations = instruction->GetLocations();
594 if (locations == nullptr) return;
595
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100596 for (size_t i = 0, e = GetNumberOfCoreRegisters(); i < e; ++i) {
597 blocked_core_registers_[i] = false;
598 }
599
600 for (size_t i = 0, e = GetNumberOfFloatingPointRegisters(); i < e; ++i) {
601 blocked_fpu_registers_[i] = false;
602 }
603
604 for (size_t i = 0, e = number_of_register_pairs_; i < e; ++i) {
605 blocked_register_pairs_[i] = false;
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100606 }
607
608 // Mark all fixed input, temp and output registers as used.
609 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
Mark Mendell5f874182015-03-04 15:42:45 -0500610 BlockIfInRegister(locations->InAt(i));
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100611 }
612
613 for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
614 Location loc = locations->GetTemp(i);
Mark Mendell5f874182015-03-04 15:42:45 -0500615 BlockIfInRegister(loc);
616 }
617 Location result_location = locations->Out();
618 if (locations->OutputCanOverlapWithInputs()) {
619 BlockIfInRegister(result_location, /* is_out */ true);
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100620 }
621
Mark Mendell5f874182015-03-04 15:42:45 -0500622 SetupBlockedRegisters(/* is_baseline */ true);
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100623
624 // Allocate all unallocated input locations.
625 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
626 Location loc = locations->InAt(i);
627 HInstruction* input = instruction->InputAt(i);
628 if (loc.IsUnallocated()) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100629 if ((loc.GetPolicy() == Location::kRequiresRegister)
630 || (loc.GetPolicy() == Location::kRequiresFpuRegister)) {
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100631 loc = AllocateFreeRegister(input->GetType());
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100632 } else {
633 DCHECK_EQ(loc.GetPolicy(), Location::kAny);
634 HLoadLocal* load = input->AsLoadLocal();
635 if (load != nullptr) {
636 loc = GetStackLocation(load);
637 } else {
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100638 loc = AllocateFreeRegister(input->GetType());
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100639 }
640 }
641 locations->SetInAt(i, loc);
642 }
643 }
644
645 // Allocate all unallocated temp locations.
646 for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
647 Location loc = locations->GetTemp(i);
648 if (loc.IsUnallocated()) {
Roland Levillain647b9ed2014-11-27 12:06:00 +0000649 switch (loc.GetPolicy()) {
650 case Location::kRequiresRegister:
651 // Allocate a core register (large enough to fit a 32-bit integer).
652 loc = AllocateFreeRegister(Primitive::kPrimInt);
653 break;
654
655 case Location::kRequiresFpuRegister:
656 // Allocate a core register (large enough to fit a 64-bit double).
657 loc = AllocateFreeRegister(Primitive::kPrimDouble);
658 break;
659
660 default:
661 LOG(FATAL) << "Unexpected policy for temporary location "
662 << loc.GetPolicy();
663 }
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100664 locations->SetTempAt(i, loc);
665 }
666 }
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100667 if (result_location.IsUnallocated()) {
668 switch (result_location.GetPolicy()) {
669 case Location::kAny:
670 case Location::kRequiresRegister:
Nicolas Geoffray7fb49da2014-10-06 09:12:41 +0100671 case Location::kRequiresFpuRegister:
Nicolas Geoffray71175b72014-10-09 22:13:55 +0100672 result_location = AllocateFreeRegister(instruction->GetType());
Nicolas Geoffray7fb49da2014-10-06 09:12:41 +0100673 break;
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100674 case Location::kSameAsFirstInput:
675 result_location = locations->InAt(0);
676 break;
677 }
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000678 locations->UpdateOut(result_location);
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100679 }
680}
681
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000682void CodeGenerator::InitLocationsBaseline(HInstruction* instruction) {
683 AllocateLocations(instruction);
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100684 if (instruction->GetLocations() == nullptr) {
Nicolas Geoffraye5038322014-07-04 09:41:32 +0100685 if (instruction->IsTemporary()) {
686 HInstruction* previous = instruction->GetPrevious();
687 Location temp_location = GetTemporaryLocation(instruction->AsTemporary());
688 Move(previous, temp_location, instruction);
Nicolas Geoffraye5038322014-07-04 09:41:32 +0100689 }
Nicolas Geoffraya7aca372014-04-28 17:47:12 +0100690 return;
691 }
692 AllocateRegistersLocally(instruction);
693 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000694 Location location = instruction->GetLocations()->InAt(i);
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +0000695 HInstruction* input = instruction->InputAt(i);
Nicolas Geoffraybab4ed72014-03-11 17:53:17 +0000696 if (location.IsValid()) {
697 // Move the input to the desired location.
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +0000698 if (input->GetNext()->IsTemporary()) {
699 // If the input was stored in a temporary, use that temporary to
700 // perform the move.
701 Move(input->GetNext(), location, instruction);
702 } else {
703 Move(input, location, instruction);
704 }
Nicolas Geoffraybab4ed72014-03-11 17:53:17 +0000705 }
706 }
707}
708
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000709void CodeGenerator::AllocateLocations(HInstruction* instruction) {
710 instruction->Accept(GetLocationBuilder());
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100711 DCHECK(CheckTypeConsistency(instruction));
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000712 LocationSummary* locations = instruction->GetLocations();
713 if (!instruction->IsSuspendCheckEntry()) {
714 if (locations != nullptr && locations->CanCall()) {
715 MarkNotLeaf();
716 }
717 if (instruction->NeedsCurrentMethod()) {
718 SetRequiresCurrentMethod();
719 }
720 }
721}
722
Serban Constantinescuecc43662015-08-13 13:33:12 +0100723void CodeGenerator::MaybeRecordStat(MethodCompilationStat compilation_stat, size_t count) const {
724 if (stats_ != nullptr) {
725 stats_->RecordStat(compilation_stat, count);
726 }
727}
728
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000729CodeGenerator* CodeGenerator::Create(HGraph* graph,
Calin Juravle34166012014-12-19 17:22:29 +0000730 InstructionSet instruction_set,
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000731 const InstructionSetFeatures& isa_features,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100732 const CompilerOptions& compiler_options,
733 OptimizingCompilerStats* stats) {
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000734 switch (instruction_set) {
Alex Light50fa9932015-08-10 15:30:07 -0700735#ifdef ART_ENABLE_CODEGEN_arm
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000736 case kArm:
737 case kThumb2: {
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000738 return new arm::CodeGeneratorARM(graph,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100739 *isa_features.AsArmInstructionSetFeatures(),
740 compiler_options,
741 stats);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000742 }
Alex Light50fa9932015-08-10 15:30:07 -0700743#endif
744#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames5319def2014-10-23 10:03:10 +0100745 case kArm64: {
Serban Constantinescu579885a2015-02-22 20:51:33 +0000746 return new arm64::CodeGeneratorARM64(graph,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100747 *isa_features.AsArm64InstructionSetFeatures(),
748 compiler_options,
749 stats);
Alexandre Rames5319def2014-10-23 10:03:10 +0100750 }
Alex Light50fa9932015-08-10 15:30:07 -0700751#endif
752#ifdef ART_ENABLE_CODEGEN_mips
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200753 case kMips: {
754 return new mips::CodeGeneratorMIPS(graph,
755 *isa_features.AsMipsInstructionSetFeatures(),
756 compiler_options,
757 stats);
758 }
Alex Light50fa9932015-08-10 15:30:07 -0700759#endif
760#ifdef ART_ENABLE_CODEGEN_mips64
Alexey Frunze4dda3372015-06-01 18:31:49 -0700761 case kMips64: {
762 return new mips64::CodeGeneratorMIPS64(graph,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100763 *isa_features.AsMips64InstructionSetFeatures(),
764 compiler_options,
765 stats);
Alexey Frunze4dda3372015-06-01 18:31:49 -0700766 }
Alex Light50fa9932015-08-10 15:30:07 -0700767#endif
768#ifdef ART_ENABLE_CODEGEN_x86
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000769 case kX86: {
Mark Mendellfb8d2792015-03-31 22:16:59 -0400770 return new x86::CodeGeneratorX86(graph,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100771 *isa_features.AsX86InstructionSetFeatures(),
772 compiler_options,
773 stats);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000774 }
Alex Light50fa9932015-08-10 15:30:07 -0700775#endif
776#ifdef ART_ENABLE_CODEGEN_x86_64
Dmitry Petrochenko6a58cb12014-04-02 17:27:59 +0700777 case kX86_64: {
Mark Mendellfb8d2792015-03-31 22:16:59 -0400778 return new x86_64::CodeGeneratorX86_64(graph,
Serban Constantinescuecc43662015-08-13 13:33:12 +0100779 *isa_features.AsX86_64InstructionSetFeatures(),
780 compiler_options,
781 stats);
Dmitry Petrochenko6a58cb12014-04-02 17:27:59 +0700782 }
Alex Light50fa9932015-08-10 15:30:07 -0700783#endif
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000784 default:
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000785 return nullptr;
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000786 }
787}
788
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000789void CodeGenerator::BuildNativeGCMap(
Vladimir Markof9f64412015-09-02 14:05:49 +0100790 ArenaVector<uint8_t>* data, const DexCompilationUnit& dex_compilation_unit) const {
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000791 const std::vector<uint8_t>& gc_map_raw =
792 dex_compilation_unit.GetVerifiedMethod()->GetDexGcMap();
793 verifier::DexPcToReferenceMap dex_gc_map(&(gc_map_raw)[0]);
794
Vladimir Markobd8c7252015-06-12 10:06:32 +0100795 uint32_t max_native_offset = stack_map_stream_.ComputeMaxNativePcOffset();
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000796
Vladimir Markobd8c7252015-06-12 10:06:32 +0100797 size_t num_stack_maps = stack_map_stream_.GetNumberOfStackMaps();
798 GcMapBuilder builder(data, num_stack_maps, max_native_offset, dex_gc_map.RegWidth());
799 for (size_t i = 0; i != num_stack_maps; ++i) {
800 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i);
801 uint32_t native_offset = stack_map_entry.native_pc_offset;
802 uint32_t dex_pc = stack_map_entry.dex_pc;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000803 const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
Jean Christophe Beyler0ada95d2014-12-04 11:20:20 -0800804 CHECK(references != nullptr) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000805 builder.AddEntry(native_offset, references);
806 }
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000807}
808
Vladimir Markof9f64412015-09-02 14:05:49 +0100809void CodeGenerator::BuildMappingTable(ArenaVector<uint8_t>* data) const {
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000810 uint32_t pc2dex_data_size = 0u;
Vladimir Markobd8c7252015-06-12 10:06:32 +0100811 uint32_t pc2dex_entries = stack_map_stream_.GetNumberOfStackMaps();
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000812 uint32_t pc2dex_offset = 0u;
813 int32_t pc2dex_dalvik_offset = 0;
814 uint32_t dex2pc_data_size = 0u;
815 uint32_t dex2pc_entries = 0u;
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000816 uint32_t dex2pc_offset = 0u;
817 int32_t dex2pc_dalvik_offset = 0;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000818
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000819 for (size_t i = 0; i < pc2dex_entries; i++) {
Vladimir Markobd8c7252015-06-12 10:06:32 +0100820 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i);
821 pc2dex_data_size += UnsignedLeb128Size(stack_map_entry.native_pc_offset - pc2dex_offset);
822 pc2dex_data_size += SignedLeb128Size(stack_map_entry.dex_pc - pc2dex_dalvik_offset);
823 pc2dex_offset = stack_map_entry.native_pc_offset;
824 pc2dex_dalvik_offset = stack_map_entry.dex_pc;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000825 }
826
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000827 // Walk over the blocks and find which ones correspond to catch block entries.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100828 for (HBasicBlock* block : graph_->GetBlocks()) {
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000829 if (block->IsCatchBlock()) {
830 intptr_t native_pc = GetAddressOf(block);
831 ++dex2pc_entries;
832 dex2pc_data_size += UnsignedLeb128Size(native_pc - dex2pc_offset);
833 dex2pc_data_size += SignedLeb128Size(block->GetDexPc() - dex2pc_dalvik_offset);
834 dex2pc_offset = native_pc;
835 dex2pc_dalvik_offset = block->GetDexPc();
836 }
837 }
838
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000839 uint32_t total_entries = pc2dex_entries + dex2pc_entries;
840 uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
841 uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
842 data->resize(data_size);
843
844 uint8_t* data_ptr = &(*data)[0];
845 uint8_t* write_pos = data_ptr;
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000846
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000847 write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
848 write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
849 DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size);
850 uint8_t* write_pos2 = write_pos + pc2dex_data_size;
851
852 pc2dex_offset = 0u;
853 pc2dex_dalvik_offset = 0u;
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000854 dex2pc_offset = 0u;
855 dex2pc_dalvik_offset = 0u;
856
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000857 for (size_t i = 0; i < pc2dex_entries; i++) {
Vladimir Markobd8c7252015-06-12 10:06:32 +0100858 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i);
859 DCHECK(pc2dex_offset <= stack_map_entry.native_pc_offset);
860 write_pos = EncodeUnsignedLeb128(write_pos, stack_map_entry.native_pc_offset - pc2dex_offset);
861 write_pos = EncodeSignedLeb128(write_pos, stack_map_entry.dex_pc - pc2dex_dalvik_offset);
862 pc2dex_offset = stack_map_entry.native_pc_offset;
863 pc2dex_dalvik_offset = stack_map_entry.dex_pc;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000864 }
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000865
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100866 for (HBasicBlock* block : graph_->GetBlocks()) {
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000867 if (block->IsCatchBlock()) {
868 intptr_t native_pc = GetAddressOf(block);
869 write_pos2 = EncodeUnsignedLeb128(write_pos2, native_pc - dex2pc_offset);
870 write_pos2 = EncodeSignedLeb128(write_pos2, block->GetDexPc() - dex2pc_dalvik_offset);
871 dex2pc_offset = native_pc;
872 dex2pc_dalvik_offset = block->GetDexPc();
873 }
874 }
875
876
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000877 DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size + pc2dex_data_size);
878 DCHECK_EQ(static_cast<size_t>(write_pos2 - data_ptr), data_size);
879
880 if (kIsDebugBuild) {
881 // Verify the encoded table holds the expected data.
882 MappingTable table(data_ptr);
883 CHECK_EQ(table.TotalSize(), total_entries);
884 CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
885 auto it = table.PcToDexBegin();
886 auto it2 = table.DexToPcBegin();
887 for (size_t i = 0; i < pc2dex_entries; i++) {
Vladimir Markobd8c7252015-06-12 10:06:32 +0100888 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i);
889 CHECK_EQ(stack_map_entry.native_pc_offset, it.NativePcOffset());
890 CHECK_EQ(stack_map_entry.dex_pc, it.DexPc());
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000891 ++it;
892 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100893 for (HBasicBlock* block : graph_->GetBlocks()) {
Nicolas Geoffrayde58ab22014-11-05 12:46:03 +0000894 if (block->IsCatchBlock()) {
895 CHECK_EQ(GetAddressOf(block), it2.NativePcOffset());
896 CHECK_EQ(block->GetDexPc(), it2.DexPc());
897 ++it2;
898 }
899 }
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000900 CHECK(it == table.PcToDexEnd());
901 CHECK(it2 == table.DexToPcEnd());
902 }
903}
904
Vladimir Markof9f64412015-09-02 14:05:49 +0100905void CodeGenerator::BuildVMapTable(ArenaVector<uint8_t>* data) const {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100906 Leb128Encoder<ArenaVector<uint8_t>> vmap_encoder(data);
Nicolas Geoffray4a34a422014-04-03 10:38:37 +0100907 // We currently don't use callee-saved registers.
908 size_t size = 0 + 1 /* marker */ + 0;
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000909 vmap_encoder.Reserve(size + 1u); // All values are likely to be one byte in ULEB128 (<128).
910 vmap_encoder.PushBackUnsigned(size);
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000911 vmap_encoder.PushBackUnsigned(VmapTable::kAdjustedFpMarker);
Nicolas Geoffray8ccc3f52014-03-19 10:34:11 +0000912}
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000913
Vladimir Markof9f64412015-09-02 14:05:49 +0100914void CodeGenerator::BuildStackMaps(ArenaVector<uint8_t>* data) {
Calin Juravle4f46ac52015-04-23 18:47:21 +0100915 uint32_t size = stack_map_stream_.PrepareForFillIn();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100916 data->resize(size);
917 MemoryRegion region(data->data(), size);
918 stack_map_stream_.FillIn(region);
919}
920
Yevgeny Rouban2a7c1ef2015-07-22 18:36:24 +0600921void CodeGenerator::RecordNativeDebugInfo(uint32_t dex_pc,
922 uintptr_t native_pc_begin,
923 uintptr_t native_pc_end) {
924 if (src_map_ != nullptr && dex_pc != kNoDexPc && native_pc_begin != native_pc_end) {
925 src_map_->push_back(SrcMapElem({static_cast<uint32_t>(native_pc_begin),
926 static_cast<int32_t>(dex_pc)}));
927 }
928}
929
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +0000930void CodeGenerator::RecordPcInfo(HInstruction* instruction,
931 uint32_t dex_pc,
932 SlowPathCode* slow_path) {
Calin Juravled2ec87d2014-12-08 14:24:46 +0000933 if (instruction != nullptr) {
Alexey Frunze4dda3372015-06-01 18:31:49 -0700934 // The code generated for some type conversions and comparisons
935 // may call the runtime, thus normally requiring a subsequent
936 // call to this method. However, the method verifier does not
937 // produce PC information for certain instructions, which are
938 // considered "atomic" (they cannot join a GC).
Roland Levillain624279f2014-12-04 11:54:28 +0000939 // Therefore we do not currently record PC information for such
940 // instructions. As this may change later, we added this special
941 // case so that code generators may nevertheless call
942 // CodeGenerator::RecordPcInfo without triggering an error in
943 // CodeGenerator::BuildNativeGCMap ("Missing ref for dex pc 0x")
944 // thereafter.
Alexey Frunze4dda3372015-06-01 18:31:49 -0700945 if (instruction->IsTypeConversion() || instruction->IsCompare()) {
Calin Juravled2ec87d2014-12-08 14:24:46 +0000946 return;
947 }
948 if (instruction->IsRem()) {
949 Primitive::Type type = instruction->AsRem()->GetResultType();
950 if ((type == Primitive::kPrimFloat) || (type == Primitive::kPrimDouble)) {
951 return;
952 }
953 }
Roland Levillain624279f2014-12-04 11:54:28 +0000954 }
955
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +0100956 uint32_t outer_dex_pc = dex_pc;
957 uint32_t outer_environment_size = 0;
958 uint32_t inlining_depth = 0;
959 if (instruction != nullptr) {
960 for (HEnvironment* environment = instruction->GetEnvironment();
961 environment != nullptr;
962 environment = environment->GetParent()) {
963 outer_dex_pc = environment->GetDexPc();
964 outer_environment_size = environment->Size();
965 if (environment != instruction->GetEnvironment()) {
966 inlining_depth++;
967 }
968 }
969 }
970
Nicolas Geoffray39468442014-09-02 15:17:15 +0100971 // Collect PC infos for the mapping table.
Vladimir Markobd8c7252015-06-12 10:06:32 +0100972 uint32_t native_pc = GetAssembler()->CodeSize();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100973
Nicolas Geoffray39468442014-09-02 15:17:15 +0100974 if (instruction == nullptr) {
975 // For stack overflow checks.
Vladimir Markobd8c7252015-06-12 10:06:32 +0100976 stack_map_stream_.BeginStackMapEntry(outer_dex_pc, native_pc, 0, 0, 0, 0);
Calin Juravle4f46ac52015-04-23 18:47:21 +0100977 stack_map_stream_.EndStackMapEntry();
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +0000978 return;
979 }
980 LocationSummary* locations = instruction->GetLocations();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100981
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +0000982 uint32_t register_mask = locations->GetRegisterMask();
983 if (locations->OnlyCallsOnSlowPath()) {
984 // In case of slow path, we currently set the location of caller-save registers
985 // to register (instead of their stack location when pushed before the slow-path
986 // call). Therefore register_mask contains both callee-save and caller-save
987 // registers that hold objects. We must remove the caller-save from the mask, since
988 // they will be overwritten by the callee.
989 register_mask &= core_callee_save_mask_;
990 }
991 // The register mask must be a subset of callee-save registers.
992 DCHECK_EQ(register_mask & core_callee_save_mask_, register_mask);
Vladimir Markobd8c7252015-06-12 10:06:32 +0100993 stack_map_stream_.BeginStackMapEntry(outer_dex_pc,
994 native_pc,
Calin Juravle4f46ac52015-04-23 18:47:21 +0100995 register_mask,
996 locations->GetStackMask(),
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +0100997 outer_environment_size,
Calin Juravle4f46ac52015-04-23 18:47:21 +0100998 inlining_depth);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +0100999
1000 EmitEnvironment(instruction->GetEnvironment(), slow_path);
1001 stack_map_stream_.EndStackMapEntry();
1002}
1003
David Brazdil77a48ae2015-09-15 12:34:04 +00001004void CodeGenerator::RecordCatchBlockInfo() {
1005 ArenaAllocator* arena = graph_->GetArena();
1006
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001007 for (HBasicBlock* block : *block_order_) {
David Brazdil77a48ae2015-09-15 12:34:04 +00001008 if (!block->IsCatchBlock()) {
1009 continue;
1010 }
1011
1012 uint32_t dex_pc = block->GetDexPc();
1013 uint32_t num_vregs = graph_->GetNumberOfVRegs();
1014 uint32_t inlining_depth = 0; // Inlining of catch blocks is not supported at the moment.
1015 uint32_t native_pc = GetAddressOf(block);
1016 uint32_t register_mask = 0; // Not used.
1017
1018 // The stack mask is not used, so we leave it empty.
1019 ArenaBitVector* stack_mask = new (arena) ArenaBitVector(arena, 0, /* expandable */ true);
1020
1021 stack_map_stream_.BeginStackMapEntry(dex_pc,
1022 native_pc,
1023 register_mask,
1024 stack_mask,
1025 num_vregs,
1026 inlining_depth);
1027
1028 HInstruction* current_phi = block->GetFirstPhi();
1029 for (size_t vreg = 0; vreg < num_vregs; ++vreg) {
1030 while (current_phi != nullptr && current_phi->AsPhi()->GetRegNumber() < vreg) {
1031 HInstruction* next_phi = current_phi->GetNext();
1032 DCHECK(next_phi == nullptr ||
1033 current_phi->AsPhi()->GetRegNumber() <= next_phi->AsPhi()->GetRegNumber())
1034 << "Phis need to be sorted by vreg number to keep this a linear-time loop.";
1035 current_phi = next_phi;
1036 }
1037
1038 if (current_phi == nullptr || current_phi->AsPhi()->GetRegNumber() != vreg) {
1039 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
1040 } else {
1041 Location location = current_phi->GetLiveInterval()->ToLocation();
1042 switch (location.GetKind()) {
1043 case Location::kStackSlot: {
1044 stack_map_stream_.AddDexRegisterEntry(
1045 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
1046 break;
1047 }
1048 case Location::kDoubleStackSlot: {
1049 stack_map_stream_.AddDexRegisterEntry(
1050 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
1051 stack_map_stream_.AddDexRegisterEntry(
1052 DexRegisterLocation::Kind::kInStack, location.GetHighStackIndex(kVRegSize));
1053 ++vreg;
1054 DCHECK_LT(vreg, num_vregs);
1055 break;
1056 }
1057 default: {
1058 // All catch phis must be allocated to a stack slot.
1059 LOG(FATAL) << "Unexpected kind " << location.GetKind();
1060 UNREACHABLE();
1061 }
1062 }
1063 }
1064 }
1065
1066 stack_map_stream_.EndStackMapEntry();
1067 }
1068}
1069
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001070void CodeGenerator::EmitEnvironment(HEnvironment* environment, SlowPathCode* slow_path) {
1071 if (environment == nullptr) return;
1072
1073 if (environment->GetParent() != nullptr) {
1074 // We emit the parent environment first.
1075 EmitEnvironment(environment->GetParent(), slow_path);
Nicolas Geoffrayb176d7c2015-05-20 18:48:31 +01001076 stack_map_stream_.BeginInlineInfoEntry(environment->GetMethodIdx(),
1077 environment->GetDexPc(),
1078 environment->GetInvokeType(),
1079 environment->Size());
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001080 }
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001081
1082 // Walk over the environment, and record the location of dex registers.
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001083 for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) {
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001084 HInstruction* current = environment->GetInstructionAt(i);
1085 if (current == nullptr) {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001086 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001087 continue;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001088 }
1089
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001090 Location location = environment->GetLocationAt(i);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001091 switch (location.GetKind()) {
1092 case Location::kConstant: {
1093 DCHECK_EQ(current, location.GetConstant());
1094 if (current->IsLongConstant()) {
1095 int64_t value = current->AsLongConstant()->GetValue();
1096 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001097 DexRegisterLocation::Kind::kConstant, Low32Bits(value));
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001098 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001099 DexRegisterLocation::Kind::kConstant, High32Bits(value));
1100 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001101 DCHECK_LT(i, environment_size);
1102 } else if (current->IsDoubleConstant()) {
Roland Levillainda4d79b2015-03-24 14:36:11 +00001103 int64_t value = bit_cast<int64_t, double>(current->AsDoubleConstant()->GetValue());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001104 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001105 DexRegisterLocation::Kind::kConstant, Low32Bits(value));
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001106 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001107 DexRegisterLocation::Kind::kConstant, High32Bits(value));
1108 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001109 DCHECK_LT(i, environment_size);
1110 } else if (current->IsIntConstant()) {
1111 int32_t value = current->AsIntConstant()->GetValue();
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001112 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, value);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001113 } else if (current->IsNullConstant()) {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001114 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001115 } else {
1116 DCHECK(current->IsFloatConstant()) << current->DebugName();
Roland Levillainda4d79b2015-03-24 14:36:11 +00001117 int32_t value = bit_cast<int32_t, float>(current->AsFloatConstant()->GetValue());
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001118 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, value);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001119 }
1120 break;
1121 }
1122
1123 case Location::kStackSlot: {
1124 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001125 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001126 break;
1127 }
1128
1129 case Location::kDoubleStackSlot: {
1130 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001131 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001132 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001133 DexRegisterLocation::Kind::kInStack, location.GetHighStackIndex(kVRegSize));
1134 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001135 DCHECK_LT(i, environment_size);
1136 break;
1137 }
1138
1139 case Location::kRegister : {
1140 int id = location.reg();
1141 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(id)) {
1142 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001143 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001144 if (current->GetType() == Primitive::kPrimLong) {
1145 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001146 DexRegisterLocation::Kind::kInStack, offset + kVRegSize);
1147 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001148 DCHECK_LT(i, environment_size);
1149 }
1150 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001151 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, id);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001152 if (current->GetType() == Primitive::kPrimLong) {
David Brazdild9cb68e2015-08-25 13:52:43 +01001153 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegisterHigh, id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001154 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001155 DCHECK_LT(i, environment_size);
1156 }
1157 }
1158 break;
1159 }
1160
1161 case Location::kFpuRegister : {
1162 int id = location.reg();
1163 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(id)) {
1164 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001165 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001166 if (current->GetType() == Primitive::kPrimDouble) {
1167 stack_map_stream_.AddDexRegisterEntry(
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001168 DexRegisterLocation::Kind::kInStack, offset + kVRegSize);
1169 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001170 DCHECK_LT(i, environment_size);
1171 }
1172 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001173 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, id);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001174 if (current->GetType() == Primitive::kPrimDouble) {
David Brazdild9cb68e2015-08-25 13:52:43 +01001175 stack_map_stream_.AddDexRegisterEntry(
1176 DexRegisterLocation::Kind::kInFpuRegisterHigh, id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001177 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001178 DCHECK_LT(i, environment_size);
1179 }
1180 }
1181 break;
1182 }
1183
1184 case Location::kFpuRegisterPair : {
1185 int low = location.low();
1186 int high = location.high();
1187 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(low)) {
1188 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(low);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001189 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001190 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001191 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, low);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001192 }
1193 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(high)) {
1194 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(high);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001195 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
1196 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001197 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001198 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, high);
1199 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001200 }
1201 DCHECK_LT(i, environment_size);
1202 break;
1203 }
1204
1205 case Location::kRegisterPair : {
1206 int low = location.low();
1207 int high = location.high();
1208 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(low)) {
1209 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(low);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001210 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001211 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001212 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, low);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001213 }
1214 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(high)) {
1215 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(high);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001216 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001217 } else {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001218 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, high);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001219 }
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001220 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001221 DCHECK_LT(i, environment_size);
1222 break;
1223 }
1224
1225 case Location::kInvalid: {
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001226 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001227 break;
1228 }
1229
1230 default:
1231 LOG(FATAL) << "Unexpected kind " << location.GetKind();
1232 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001233 }
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001234
1235 if (environment->GetParent() != nullptr) {
1236 stack_map_stream_.EndInlineInfoEntry();
1237 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001238}
1239
David Brazdil77a48ae2015-09-15 12:34:04 +00001240bool CodeGenerator::IsImplicitNullCheckAllowed(HNullCheck* null_check) const {
1241 return compiler_options_.GetImplicitNullChecks() &&
1242 // Null checks which might throw into a catch block need to save live
1243 // registers and therefore cannot be done implicitly.
1244 !null_check->CanThrowIntoCatchBlock();
1245}
1246
Calin Juravle77520bc2015-01-12 18:45:46 +00001247bool CodeGenerator::CanMoveNullCheckToUser(HNullCheck* null_check) {
1248 HInstruction* first_next_not_move = null_check->GetNextDisregardingMoves();
Calin Juravle641547a2015-04-21 22:08:51 +01001249
1250 return (first_next_not_move != nullptr)
1251 && first_next_not_move->CanDoImplicitNullCheckOn(null_check->InputAt(0));
Calin Juravle77520bc2015-01-12 18:45:46 +00001252}
1253
1254void CodeGenerator::MaybeRecordImplicitNullCheck(HInstruction* instr) {
1255 // If we are from a static path don't record the pc as we can't throw NPE.
1256 // NB: having the checks here makes the code much less verbose in the arch
1257 // specific code generators.
1258 if (instr->IsStaticFieldSet() || instr->IsStaticFieldGet()) {
1259 return;
1260 }
1261
Calin Juravle641547a2015-04-21 22:08:51 +01001262 if (!instr->CanDoImplicitNullCheckOn(instr->InputAt(0))) {
Calin Juravle77520bc2015-01-12 18:45:46 +00001263 return;
1264 }
1265
1266 // Find the first previous instruction which is not a move.
1267 HInstruction* first_prev_not_move = instr->GetPreviousDisregardingMoves();
1268
1269 // If the instruction is a null check it means that `instr` is the first user
1270 // and needs to record the pc.
1271 if (first_prev_not_move != nullptr && first_prev_not_move->IsNullCheck()) {
1272 HNullCheck* null_check = first_prev_not_move->AsNullCheck();
David Brazdil77a48ae2015-09-15 12:34:04 +00001273 if (IsImplicitNullCheckAllowed(null_check)) {
1274 // TODO: The parallel moves modify the environment. Their changes need to be
1275 // reverted otherwise the stack maps at the throw point will not be correct.
1276 RecordPcInfo(null_check, null_check->GetDexPc());
1277 }
Calin Juravle77520bc2015-01-12 18:45:46 +00001278 }
1279}
1280
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001281void CodeGenerator::ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check) const {
1282 LocationSummary* locations = suspend_check->GetLocations();
1283 HBasicBlock* block = suspend_check->GetBlock();
1284 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == suspend_check);
1285 DCHECK(block->IsLoopHeader());
1286
1287 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1288 HInstruction* current = it.Current();
1289 LiveInterval* interval = current->GetLiveInterval();
1290 // We only need to clear bits of loop phis containing objects and allocated in register.
1291 // Loop phis allocated on stack already have the object in the stack.
1292 if (current->GetType() == Primitive::kPrimNot
1293 && interval->HasRegister()
1294 && interval->HasSpillSlot()) {
1295 locations->ClearStackBit(interval->GetSpillSlot() / kVRegSize);
1296 }
1297 }
1298}
1299
Nicolas Geoffray90218252015-04-15 11:56:51 +01001300void CodeGenerator::EmitParallelMoves(Location from1,
1301 Location to1,
1302 Primitive::Type type1,
1303 Location from2,
1304 Location to2,
1305 Primitive::Type type2) {
Nicolas Geoffrayf0e39372014-11-12 17:50:07 +00001306 HParallelMove parallel_move(GetGraph()->GetArena());
Nicolas Geoffray90218252015-04-15 11:56:51 +01001307 parallel_move.AddMove(from1, to1, type1, nullptr);
1308 parallel_move.AddMove(from2, to2, type2, nullptr);
Nicolas Geoffrayf0e39372014-11-12 17:50:07 +00001309 GetMoveResolver()->EmitNativeCode(&parallel_move);
1310}
1311
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001312void CodeGenerator::ValidateInvokeRuntime(HInstruction* instruction, SlowPathCode* slow_path) {
1313 // Ensure that the call kind indication given to the register allocator is
1314 // coherent with the runtime call generated, and that the GC side effect is
1315 // set when required.
1316 if (slow_path == nullptr) {
Roland Levillaindf3f8222015-08-13 12:31:44 +01001317 DCHECK(instruction->GetLocations()->WillCall()) << instruction->DebugName();
1318 DCHECK(instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()))
1319 << instruction->DebugName() << instruction->GetSideEffects().ToString();
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001320 } else {
Roland Levillaindf3f8222015-08-13 12:31:44 +01001321 DCHECK(instruction->GetLocations()->OnlyCallsOnSlowPath() || slow_path->IsFatal())
1322 << instruction->DebugName() << slow_path->GetDescription();
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001323 DCHECK(instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()) ||
1324 // Control flow would not come back into the code if a fatal slow
1325 // path is taken, so we do not care if it triggers GC.
1326 slow_path->IsFatal() ||
1327 // HDeoptimize is a special case: we know we are not coming back from
1328 // it into the code.
Roland Levillaindf3f8222015-08-13 12:31:44 +01001329 instruction->IsDeoptimize())
1330 << instruction->DebugName() << instruction->GetSideEffects().ToString()
1331 << slow_path->GetDescription();
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001332 }
1333
1334 // Check the coherency of leaf information.
1335 DCHECK(instruction->IsSuspendCheck()
1336 || ((slow_path != nullptr) && slow_path->IsFatal())
1337 || instruction->GetLocations()->CanCall()
Roland Levillaindf3f8222015-08-13 12:31:44 +01001338 || !IsLeafMethod())
1339 << instruction->DebugName() << ((slow_path != nullptr) ? slow_path->GetDescription() : "");
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001340}
1341
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001342void SlowPathCode::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
1343 RegisterSet* register_set = locations->GetLiveRegisters();
1344 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
1345 for (size_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) {
1346 if (!codegen->IsCoreCalleeSaveRegister(i)) {
1347 if (register_set->ContainsCoreRegister(i)) {
1348 // If the register holds an object, update the stack mask.
1349 if (locations->RegisterContainsObject(i)) {
1350 locations->SetStackBit(stack_offset / kVRegSize);
1351 }
1352 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001353 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1354 saved_core_stack_offsets_[i] = stack_offset;
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001355 stack_offset += codegen->SaveCoreRegister(stack_offset, i);
1356 }
1357 }
1358 }
1359
1360 for (size_t i = 0, e = codegen->GetNumberOfFloatingPointRegisters(); i < e; ++i) {
1361 if (!codegen->IsFloatingPointCalleeSaveRegister(i)) {
1362 if (register_set->ContainsFloatingPointRegister(i)) {
1363 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001364 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1365 saved_fpu_stack_offsets_[i] = stack_offset;
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001366 stack_offset += codegen->SaveFloatingPointRegister(stack_offset, i);
1367 }
1368 }
1369 }
1370}
1371
1372void SlowPathCode::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
1373 RegisterSet* register_set = locations->GetLiveRegisters();
1374 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
1375 for (size_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) {
1376 if (!codegen->IsCoreCalleeSaveRegister(i)) {
1377 if (register_set->ContainsCoreRegister(i)) {
1378 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1379 stack_offset += codegen->RestoreCoreRegister(stack_offset, i);
1380 }
1381 }
1382 }
1383
1384 for (size_t i = 0, e = codegen->GetNumberOfFloatingPointRegisters(); i < e; ++i) {
1385 if (!codegen->IsFloatingPointCalleeSaveRegister(i)) {
1386 if (register_set->ContainsFloatingPointRegister(i)) {
1387 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1388 stack_offset += codegen->RestoreFloatingPointRegister(stack_offset, i);
1389 }
1390 }
1391 }
1392}
1393
Nicolas Geoffray5bd05a52015-10-13 09:48:30 +01001394void CodeGenerator::CreateSystemArrayCopyLocationSummary(HInvoke* invoke) {
1395 // Check to see if we have known failures that will cause us to have to bail out
1396 // to the runtime, and just generate the runtime call directly.
1397 HIntConstant* src_pos = invoke->InputAt(1)->AsIntConstant();
1398 HIntConstant* dest_pos = invoke->InputAt(3)->AsIntConstant();
1399
1400 // The positions must be non-negative.
1401 if ((src_pos != nullptr && src_pos->GetValue() < 0) ||
1402 (dest_pos != nullptr && dest_pos->GetValue() < 0)) {
1403 // We will have to fail anyways.
1404 return;
1405 }
1406
1407 // The length must be >= 0.
1408 HIntConstant* length = invoke->InputAt(4)->AsIntConstant();
1409 if (length != nullptr) {
1410 int32_t len = length->GetValue();
1411 if (len < 0) {
1412 // Just call as normal.
1413 return;
1414 }
1415 }
1416
1417 SystemArrayCopyOptimizations optimizations(invoke);
1418
1419 if (optimizations.GetDestinationIsSource()) {
1420 if (src_pos != nullptr && dest_pos != nullptr && src_pos->GetValue() < dest_pos->GetValue()) {
1421 // We only support backward copying if source and destination are the same.
1422 return;
1423 }
1424 }
1425
1426 if (optimizations.GetDestinationIsPrimitiveArray() || optimizations.GetSourceIsPrimitiveArray()) {
1427 // We currently don't intrinsify primitive copying.
1428 return;
1429 }
1430
1431 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetArena();
1432 LocationSummary* locations = new (allocator) LocationSummary(invoke,
1433 LocationSummary::kCallOnSlowPath,
1434 kIntrinsified);
1435 // arraycopy(Object src, int src_pos, Object dest, int dest_pos, int length).
1436 locations->SetInAt(0, Location::RequiresRegister());
1437 locations->SetInAt(1, Location::RegisterOrConstant(invoke->InputAt(1)));
1438 locations->SetInAt(2, Location::RequiresRegister());
1439 locations->SetInAt(3, Location::RegisterOrConstant(invoke->InputAt(3)));
1440 locations->SetInAt(4, Location::RegisterOrConstant(invoke->InputAt(4)));
1441
1442 locations->AddTemp(Location::RequiresRegister());
1443 locations->AddTemp(Location::RequiresRegister());
1444 locations->AddTemp(Location::RequiresRegister());
1445}
1446
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001447} // namespace art