code_generator.cc revision 442b46a087c389a91a0b51547ac9205058432364
1/*
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
19#include "code_generator_arm.h"
20#include "code_generator_arm64.h"
21#include "code_generator_x86.h"
22#include "code_generator_x86_64.h"
23#include "compiled_method.h"
24#include "dex/verified_method.h"
25#include "driver/dex_compilation_unit.h"
26#include "gc_map_builder.h"
27#include "leb128.h"
28#include "mapping_table.h"
29#include "mirror/array-inl.h"
30#include "mirror/object_array-inl.h"
31#include "mirror/object_reference.h"
32#include "ssa_liveness_analysis.h"
33#include "utils/assembler.h"
34#include "verifier/dex_gc_map.h"
35#include "vmap_table.h"
36
37namespace art {
38
39size_t CodeGenerator::GetCacheOffset(uint32_t index) {
40  return mirror::ObjectArray<mirror::Object>::OffsetOfElement(index).SizeValue();
41}
42
43static bool IsSingleGoto(HBasicBlock* block) {
44  HLoopInformation* loop_info = block->GetLoopInformation();
45  // TODO: Remove the null check b/19084197.
46  return (block->GetFirstInstruction() != nullptr)
47      && (block->GetFirstInstruction() == block->GetLastInstruction())
48      && block->GetLastInstruction()->IsGoto()
49      // Back edges generate the suspend check.
50      && (loop_info == nullptr || !loop_info->IsBackEdge(block));
51}
52
53void CodeGenerator::CompileBaseline(CodeAllocator* allocator, bool is_leaf) {
54  Initialize();
55  if (!is_leaf) {
56    MarkNotLeaf();
57  }
58  InitializeCodeGeneration(GetGraph()->GetNumberOfLocalVRegs()
59                             + GetGraph()->GetTemporariesVRegSlots()
60                             + 1 /* filler */,
61                           0, /* the baseline compiler does not have live registers at slow path */
62                           0, /* the baseline compiler does not have live registers at slow path */
63                           GetGraph()->GetMaximumNumberOfOutVRegs()
64                             + 1 /* current method */,
65                           GetGraph()->GetBlocks());
66  CompileInternal(allocator, /* is_baseline */ true);
67}
68
69bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
70  DCHECK_EQ(block_order_->Get(current_block_index_), current);
71  return GetNextBlockToEmit() == FirstNonEmptyBlock(next);
72}
73
74HBasicBlock* CodeGenerator::GetNextBlockToEmit() const {
75  for (size_t i = current_block_index_ + 1; i < block_order_->Size(); ++i) {
76    HBasicBlock* block = block_order_->Get(i);
77    if (!IsSingleGoto(block)) {
78      return block;
79    }
80  }
81  return nullptr;
82}
83
84HBasicBlock* CodeGenerator::FirstNonEmptyBlock(HBasicBlock* block) const {
85  while (IsSingleGoto(block)) {
86    block = block->GetSuccessors().Get(0);
87  }
88  return block;
89}
90
91void CodeGenerator::CompileInternal(CodeAllocator* allocator, bool is_baseline) {
92  HGraphVisitor* instruction_visitor = GetInstructionVisitor();
93  DCHECK_EQ(current_block_index_, 0u);
94  GenerateFrameEntry();
95  for (size_t e = block_order_->Size(); current_block_index_ < e; ++current_block_index_) {
96    HBasicBlock* block = block_order_->Get(current_block_index_);
97    // Don't generate code for an empty block. Its predecessors will branch to its successor
98    // directly. Also, the label of that block will not be emitted, so this helps catch
99    // errors where we reference that label.
100    if (IsSingleGoto(block)) continue;
101    Bind(block);
102    for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
103      HInstruction* current = it.Current();
104      if (is_baseline) {
105        InitLocationsBaseline(current);
106      }
107      current->Accept(instruction_visitor);
108    }
109  }
110
111  // Generate the slow paths.
112  for (size_t i = 0, e = slow_paths_.Size(); i < e; ++i) {
113    slow_paths_.Get(i)->EmitNativeCode(this);
114  }
115
116  // Finalize instructions in assember;
117  Finalize(allocator);
118}
119
120void CodeGenerator::CompileOptimized(CodeAllocator* allocator) {
121  // The register allocator already called `InitializeCodeGeneration`,
122  // where the frame size has been computed.
123  DCHECK(block_order_ != nullptr);
124  Initialize();
125  CompileInternal(allocator, /* is_baseline */ false);
126}
127
128void CodeGenerator::Finalize(CodeAllocator* allocator) {
129  size_t code_size = GetAssembler()->CodeSize();
130  uint8_t* buffer = allocator->Allocate(code_size);
131
132  MemoryRegion code(buffer, code_size);
133  GetAssembler()->FinalizeInstructions(code);
134}
135
136size_t CodeGenerator::FindFreeEntry(bool* array, size_t length) {
137  for (size_t i = 0; i < length; ++i) {
138    if (!array[i]) {
139      array[i] = true;
140      return i;
141    }
142  }
143  LOG(FATAL) << "Could not find a register in baseline register allocator";
144  UNREACHABLE();
145  return -1;
146}
147
148size_t CodeGenerator::FindTwoFreeConsecutiveAlignedEntries(bool* array, size_t length) {
149  for (size_t i = 0; i < length - 1; i += 2) {
150    if (!array[i] && !array[i + 1]) {
151      array[i] = true;
152      array[i + 1] = true;
153      return i;
154    }
155  }
156  LOG(FATAL) << "Could not find a register in baseline register allocator";
157  UNREACHABLE();
158  return -1;
159}
160
161void CodeGenerator::InitializeCodeGeneration(size_t number_of_spill_slots,
162                                             size_t maximum_number_of_live_core_registers,
163                                             size_t maximum_number_of_live_fp_registers,
164                                             size_t number_of_out_slots,
165                                             const GrowableArray<HBasicBlock*>& block_order) {
166  block_order_ = &block_order;
167  DCHECK(block_order_->Get(0) == GetGraph()->GetEntryBlock());
168  DCHECK(GoesToNextBlock(GetGraph()->GetEntryBlock(), block_order_->Get(1)));
169  ComputeSpillMask();
170  first_register_slot_in_slow_path_ = (number_of_out_slots + number_of_spill_slots) * kVRegSize;
171
172  if (number_of_spill_slots == 0
173      && !HasAllocatedCalleeSaveRegisters()
174      && IsLeafMethod()
175      && !RequiresCurrentMethod()) {
176    DCHECK_EQ(maximum_number_of_live_core_registers, 0u);
177    DCHECK_EQ(maximum_number_of_live_fp_registers, 0u);
178    SetFrameSize(CallPushesPC() ? GetWordSize() : 0);
179  } else {
180    SetFrameSize(RoundUp(
181        number_of_spill_slots * kVRegSize
182        + number_of_out_slots * kVRegSize
183        + maximum_number_of_live_core_registers * GetWordSize()
184        + maximum_number_of_live_fp_registers * GetFloatingPointSpillSlotSize()
185        + FrameEntrySpillSize(),
186        kStackAlignment));
187  }
188}
189
190Location CodeGenerator::GetTemporaryLocation(HTemporary* temp) const {
191  uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs();
192  // The type of the previous instruction tells us if we need a single or double stack slot.
193  Primitive::Type type = temp->GetType();
194  int32_t temp_size = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble) ? 2 : 1;
195  // Use the temporary region (right below the dex registers).
196  int32_t slot = GetFrameSize() - FrameEntrySpillSize()
197                                - kVRegSize  // filler
198                                - (number_of_locals * kVRegSize)
199                                - ((temp_size + temp->GetIndex()) * kVRegSize);
200  return temp_size == 2 ? Location::DoubleStackSlot(slot) : Location::StackSlot(slot);
201}
202
203int32_t CodeGenerator::GetStackSlot(HLocal* local) const {
204  uint16_t reg_number = local->GetRegNumber();
205  uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs();
206  if (reg_number >= number_of_locals) {
207    // Local is a parameter of the method. It is stored in the caller's frame.
208    return GetFrameSize() + kVRegSize  // ART method
209                          + (reg_number - number_of_locals) * kVRegSize;
210  } else {
211    // Local is a temporary in this method. It is stored in this method's frame.
212    return GetFrameSize() - FrameEntrySpillSize()
213                          - kVRegSize  // filler.
214                          - (number_of_locals * kVRegSize)
215                          + (reg_number * kVRegSize);
216  }
217}
218
219void CodeGenerator::AllocateRegistersLocally(HInstruction* instruction) const {
220  LocationSummary* locations = instruction->GetLocations();
221  if (locations == nullptr) return;
222
223  for (size_t i = 0, e = GetNumberOfCoreRegisters(); i < e; ++i) {
224    blocked_core_registers_[i] = false;
225  }
226
227  for (size_t i = 0, e = GetNumberOfFloatingPointRegisters(); i < e; ++i) {
228    blocked_fpu_registers_[i] = false;
229  }
230
231  for (size_t i = 0, e = number_of_register_pairs_; i < e; ++i) {
232    blocked_register_pairs_[i] = false;
233  }
234
235  // Mark all fixed input, temp and output registers as used.
236  for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
237    Location loc = locations->InAt(i);
238    // The DCHECKS below check that a register is not specified twice in
239    // the summary.
240    if (loc.IsRegister()) {
241      DCHECK(!blocked_core_registers_[loc.reg()]);
242      blocked_core_registers_[loc.reg()] = true;
243    } else if (loc.IsFpuRegister()) {
244      DCHECK(!blocked_fpu_registers_[loc.reg()]);
245      blocked_fpu_registers_[loc.reg()] = true;
246    } else if (loc.IsFpuRegisterPair()) {
247      DCHECK(!blocked_fpu_registers_[loc.AsFpuRegisterPairLow<int>()]);
248      blocked_fpu_registers_[loc.AsFpuRegisterPairLow<int>()] = true;
249      DCHECK(!blocked_fpu_registers_[loc.AsFpuRegisterPairHigh<int>()]);
250      blocked_fpu_registers_[loc.AsFpuRegisterPairHigh<int>()] = true;
251    } else if (loc.IsRegisterPair()) {
252      DCHECK(!blocked_core_registers_[loc.AsRegisterPairLow<int>()]);
253      blocked_core_registers_[loc.AsRegisterPairLow<int>()] = true;
254      DCHECK(!blocked_core_registers_[loc.AsRegisterPairHigh<int>()]);
255      blocked_core_registers_[loc.AsRegisterPairHigh<int>()] = true;
256    }
257  }
258
259  for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
260    Location loc = locations->GetTemp(i);
261    // The DCHECKS below check that a register is not specified twice in
262    // the summary.
263    if (loc.IsRegister()) {
264      DCHECK(!blocked_core_registers_[loc.reg()]);
265      blocked_core_registers_[loc.reg()] = true;
266    } else if (loc.IsFpuRegister()) {
267      DCHECK(!blocked_fpu_registers_[loc.reg()]);
268      blocked_fpu_registers_[loc.reg()] = true;
269    } else {
270      DCHECK(loc.GetPolicy() == Location::kRequiresRegister
271             || loc.GetPolicy() == Location::kRequiresFpuRegister);
272    }
273  }
274
275  static constexpr bool kBaseline = true;
276  SetupBlockedRegisters(kBaseline);
277
278  // Allocate all unallocated input locations.
279  for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
280    Location loc = locations->InAt(i);
281    HInstruction* input = instruction->InputAt(i);
282    if (loc.IsUnallocated()) {
283      if ((loc.GetPolicy() == Location::kRequiresRegister)
284          || (loc.GetPolicy() == Location::kRequiresFpuRegister)) {
285        loc = AllocateFreeRegister(input->GetType());
286      } else {
287        DCHECK_EQ(loc.GetPolicy(), Location::kAny);
288        HLoadLocal* load = input->AsLoadLocal();
289        if (load != nullptr) {
290          loc = GetStackLocation(load);
291        } else {
292          loc = AllocateFreeRegister(input->GetType());
293        }
294      }
295      locations->SetInAt(i, loc);
296    }
297  }
298
299  // Allocate all unallocated temp locations.
300  for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
301    Location loc = locations->GetTemp(i);
302    if (loc.IsUnallocated()) {
303      switch (loc.GetPolicy()) {
304        case Location::kRequiresRegister:
305          // Allocate a core register (large enough to fit a 32-bit integer).
306          loc = AllocateFreeRegister(Primitive::kPrimInt);
307          break;
308
309        case Location::kRequiresFpuRegister:
310          // Allocate a core register (large enough to fit a 64-bit double).
311          loc = AllocateFreeRegister(Primitive::kPrimDouble);
312          break;
313
314        default:
315          LOG(FATAL) << "Unexpected policy for temporary location "
316                     << loc.GetPolicy();
317      }
318      locations->SetTempAt(i, loc);
319    }
320  }
321  Location result_location = locations->Out();
322  if (result_location.IsUnallocated()) {
323    switch (result_location.GetPolicy()) {
324      case Location::kAny:
325      case Location::kRequiresRegister:
326      case Location::kRequiresFpuRegister:
327        result_location = AllocateFreeRegister(instruction->GetType());
328        break;
329      case Location::kSameAsFirstInput:
330        result_location = locations->InAt(0);
331        break;
332    }
333    locations->UpdateOut(result_location);
334  }
335}
336
337void CodeGenerator::InitLocationsBaseline(HInstruction* instruction) {
338  AllocateLocations(instruction);
339  if (instruction->GetLocations() == nullptr) {
340    if (instruction->IsTemporary()) {
341      HInstruction* previous = instruction->GetPrevious();
342      Location temp_location = GetTemporaryLocation(instruction->AsTemporary());
343      Move(previous, temp_location, instruction);
344    }
345    return;
346  }
347  AllocateRegistersLocally(instruction);
348  for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
349    Location location = instruction->GetLocations()->InAt(i);
350    HInstruction* input = instruction->InputAt(i);
351    if (location.IsValid()) {
352      // Move the input to the desired location.
353      if (input->GetNext()->IsTemporary()) {
354        // If the input was stored in a temporary, use that temporary to
355        // perform the move.
356        Move(input->GetNext(), location, instruction);
357      } else {
358        Move(input, location, instruction);
359      }
360    }
361  }
362}
363
364void CodeGenerator::AllocateLocations(HInstruction* instruction) {
365  instruction->Accept(GetLocationBuilder());
366  LocationSummary* locations = instruction->GetLocations();
367  if (!instruction->IsSuspendCheckEntry()) {
368    if (locations != nullptr && locations->CanCall()) {
369      MarkNotLeaf();
370    }
371    if (instruction->NeedsCurrentMethod()) {
372      SetRequiresCurrentMethod();
373    }
374  }
375}
376
377CodeGenerator* CodeGenerator::Create(HGraph* graph,
378                                     InstructionSet instruction_set,
379                                     const InstructionSetFeatures& isa_features,
380                                     const CompilerOptions& compiler_options) {
381  switch (instruction_set) {
382    case kArm:
383    case kThumb2: {
384      return new arm::CodeGeneratorARM(graph,
385          *isa_features.AsArmInstructionSetFeatures(),
386          compiler_options);
387    }
388    case kArm64: {
389      return new arm64::CodeGeneratorARM64(graph, compiler_options);
390    }
391    case kMips:
392      return nullptr;
393    case kX86: {
394      return new x86::CodeGeneratorX86(graph, compiler_options);
395    }
396    case kX86_64: {
397      return new x86_64::CodeGeneratorX86_64(graph, compiler_options);
398    }
399    default:
400      return nullptr;
401  }
402}
403
404void CodeGenerator::BuildNativeGCMap(
405    std::vector<uint8_t>* data, const DexCompilationUnit& dex_compilation_unit) const {
406  const std::vector<uint8_t>& gc_map_raw =
407      dex_compilation_unit.GetVerifiedMethod()->GetDexGcMap();
408  verifier::DexPcToReferenceMap dex_gc_map(&(gc_map_raw)[0]);
409
410  uint32_t max_native_offset = 0;
411  for (size_t i = 0; i < pc_infos_.Size(); i++) {
412    uint32_t native_offset = pc_infos_.Get(i).native_pc;
413    if (native_offset > max_native_offset) {
414      max_native_offset = native_offset;
415    }
416  }
417
418  GcMapBuilder builder(data, pc_infos_.Size(), max_native_offset, dex_gc_map.RegWidth());
419  for (size_t i = 0; i < pc_infos_.Size(); i++) {
420    struct PcInfo pc_info = pc_infos_.Get(i);
421    uint32_t native_offset = pc_info.native_pc;
422    uint32_t dex_pc = pc_info.dex_pc;
423    const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
424    CHECK(references != nullptr) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
425    builder.AddEntry(native_offset, references);
426  }
427}
428
429void CodeGenerator::BuildMappingTable(std::vector<uint8_t>* data, DefaultSrcMap* src_map) const {
430  uint32_t pc2dex_data_size = 0u;
431  uint32_t pc2dex_entries = pc_infos_.Size();
432  uint32_t pc2dex_offset = 0u;
433  int32_t pc2dex_dalvik_offset = 0;
434  uint32_t dex2pc_data_size = 0u;
435  uint32_t dex2pc_entries = 0u;
436  uint32_t dex2pc_offset = 0u;
437  int32_t dex2pc_dalvik_offset = 0;
438
439  if (src_map != nullptr) {
440    src_map->reserve(pc2dex_entries);
441  }
442
443  for (size_t i = 0; i < pc2dex_entries; i++) {
444    struct PcInfo pc_info = pc_infos_.Get(i);
445    pc2dex_data_size += UnsignedLeb128Size(pc_info.native_pc - pc2dex_offset);
446    pc2dex_data_size += SignedLeb128Size(pc_info.dex_pc - pc2dex_dalvik_offset);
447    pc2dex_offset = pc_info.native_pc;
448    pc2dex_dalvik_offset = pc_info.dex_pc;
449    if (src_map != nullptr) {
450      src_map->push_back(SrcMapElem({pc2dex_offset, pc2dex_dalvik_offset}));
451    }
452  }
453
454  // Walk over the blocks and find which ones correspond to catch block entries.
455  for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) {
456    HBasicBlock* block = graph_->GetBlocks().Get(i);
457    if (block->IsCatchBlock()) {
458      intptr_t native_pc = GetAddressOf(block);
459      ++dex2pc_entries;
460      dex2pc_data_size += UnsignedLeb128Size(native_pc - dex2pc_offset);
461      dex2pc_data_size += SignedLeb128Size(block->GetDexPc() - dex2pc_dalvik_offset);
462      dex2pc_offset = native_pc;
463      dex2pc_dalvik_offset = block->GetDexPc();
464    }
465  }
466
467  uint32_t total_entries = pc2dex_entries + dex2pc_entries;
468  uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
469  uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
470  data->resize(data_size);
471
472  uint8_t* data_ptr = &(*data)[0];
473  uint8_t* write_pos = data_ptr;
474
475  write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
476  write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
477  DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size);
478  uint8_t* write_pos2 = write_pos + pc2dex_data_size;
479
480  pc2dex_offset = 0u;
481  pc2dex_dalvik_offset = 0u;
482  dex2pc_offset = 0u;
483  dex2pc_dalvik_offset = 0u;
484
485  for (size_t i = 0; i < pc2dex_entries; i++) {
486    struct PcInfo pc_info = pc_infos_.Get(i);
487    DCHECK(pc2dex_offset <= pc_info.native_pc);
488    write_pos = EncodeUnsignedLeb128(write_pos, pc_info.native_pc - pc2dex_offset);
489    write_pos = EncodeSignedLeb128(write_pos, pc_info.dex_pc - pc2dex_dalvik_offset);
490    pc2dex_offset = pc_info.native_pc;
491    pc2dex_dalvik_offset = pc_info.dex_pc;
492  }
493
494  for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) {
495    HBasicBlock* block = graph_->GetBlocks().Get(i);
496    if (block->IsCatchBlock()) {
497      intptr_t native_pc = GetAddressOf(block);
498      write_pos2 = EncodeUnsignedLeb128(write_pos2, native_pc - dex2pc_offset);
499      write_pos2 = EncodeSignedLeb128(write_pos2, block->GetDexPc() - dex2pc_dalvik_offset);
500      dex2pc_offset = native_pc;
501      dex2pc_dalvik_offset = block->GetDexPc();
502    }
503  }
504
505
506  DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size + pc2dex_data_size);
507  DCHECK_EQ(static_cast<size_t>(write_pos2 - data_ptr), data_size);
508
509  if (kIsDebugBuild) {
510    // Verify the encoded table holds the expected data.
511    MappingTable table(data_ptr);
512    CHECK_EQ(table.TotalSize(), total_entries);
513    CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
514    auto it = table.PcToDexBegin();
515    auto it2 = table.DexToPcBegin();
516    for (size_t i = 0; i < pc2dex_entries; i++) {
517      struct PcInfo pc_info = pc_infos_.Get(i);
518      CHECK_EQ(pc_info.native_pc, it.NativePcOffset());
519      CHECK_EQ(pc_info.dex_pc, it.DexPc());
520      ++it;
521    }
522    for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) {
523      HBasicBlock* block = graph_->GetBlocks().Get(i);
524      if (block->IsCatchBlock()) {
525        CHECK_EQ(GetAddressOf(block), it2.NativePcOffset());
526        CHECK_EQ(block->GetDexPc(), it2.DexPc());
527        ++it2;
528      }
529    }
530    CHECK(it == table.PcToDexEnd());
531    CHECK(it2 == table.DexToPcEnd());
532  }
533}
534
535void CodeGenerator::BuildVMapTable(std::vector<uint8_t>* data) const {
536  Leb128EncodingVector vmap_encoder;
537  // We currently don't use callee-saved registers.
538  size_t size = 0 + 1 /* marker */ + 0;
539  vmap_encoder.Reserve(size + 1u);  // All values are likely to be one byte in ULEB128 (<128).
540  vmap_encoder.PushBackUnsigned(size);
541  vmap_encoder.PushBackUnsigned(VmapTable::kAdjustedFpMarker);
542
543  *data = vmap_encoder.GetData();
544}
545
546void CodeGenerator::BuildStackMaps(std::vector<uint8_t>* data) {
547  uint32_t size = stack_map_stream_.ComputeNeededSize();
548  data->resize(size);
549  MemoryRegion region(data->data(), size);
550  stack_map_stream_.FillIn(region);
551}
552
553void CodeGenerator::RecordPcInfo(HInstruction* instruction, uint32_t dex_pc) {
554  if (instruction != nullptr) {
555    // The code generated for some type conversions may call the
556    // runtime, thus normally requiring a subsequent call to this
557    // method.  However, the method verifier does not produce PC
558    // information for certain instructions, which are considered "atomic"
559    // (they cannot join a GC).
560    // Therefore we do not currently record PC information for such
561    // instructions.  As this may change later, we added this special
562    // case so that code generators may nevertheless call
563    // CodeGenerator::RecordPcInfo without triggering an error in
564    // CodeGenerator::BuildNativeGCMap ("Missing ref for dex pc 0x")
565    // thereafter.
566    if (instruction->IsTypeConversion()) {
567      return;
568    }
569    if (instruction->IsRem()) {
570      Primitive::Type type = instruction->AsRem()->GetResultType();
571      if ((type == Primitive::kPrimFloat) || (type == Primitive::kPrimDouble)) {
572        return;
573      }
574    }
575  }
576
577  // Collect PC infos for the mapping table.
578  struct PcInfo pc_info;
579  pc_info.dex_pc = dex_pc;
580  pc_info.native_pc = GetAssembler()->CodeSize();
581  pc_infos_.Add(pc_info);
582
583  // Populate stack map information.
584
585  if (instruction == nullptr) {
586    // For stack overflow checks.
587    stack_map_stream_.AddStackMapEntry(dex_pc, pc_info.native_pc, 0, 0, 0, 0);
588    return;
589  }
590
591  LocationSummary* locations = instruction->GetLocations();
592  HEnvironment* environment = instruction->GetEnvironment();
593
594  size_t environment_size = instruction->EnvironmentSize();
595
596  size_t inlining_depth = 0;
597  uint32_t register_mask = locations->GetRegisterMask();
598  if (locations->OnlyCallsOnSlowPath()) {
599    // In case of slow path, we currently set the location of caller-save registers
600    // to register (instead of their stack location when pushed before the slow-path
601    // call). Therefore register_mask contains both callee-save and caller-save
602    // registers that hold objects. We must remove the caller-save from the mask, since
603    // they will be overwritten by the callee.
604    register_mask &= core_callee_save_mask_;
605  }
606  // The register mask must be a subset of callee-save registers.
607  DCHECK_EQ(register_mask & core_callee_save_mask_, register_mask);
608  stack_map_stream_.AddStackMapEntry(
609      dex_pc, pc_info.native_pc, register_mask,
610      locations->GetStackMask(), environment_size, inlining_depth);
611
612  // Walk over the environment, and record the location of dex registers.
613  for (size_t i = 0; i < environment_size; ++i) {
614    HInstruction* current = environment->GetInstructionAt(i);
615    if (current == nullptr) {
616      stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kNone, 0);
617      continue;
618    }
619
620    Location location = locations->GetEnvironmentAt(i);
621    switch (location.GetKind()) {
622      case Location::kConstant: {
623        DCHECK_EQ(current, location.GetConstant());
624        if (current->IsLongConstant()) {
625          int64_t value = current->AsLongConstant()->GetValue();
626          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, Low32Bits(value));
627          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, High32Bits(value));
628          ++i;
629          DCHECK_LT(i, environment_size);
630        } else if (current->IsDoubleConstant()) {
631          int64_t value = bit_cast<double, int64_t>(current->AsDoubleConstant()->GetValue());
632          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, Low32Bits(value));
633          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, High32Bits(value));
634          ++i;
635          DCHECK_LT(i, environment_size);
636        } else if (current->IsIntConstant()) {
637          int32_t value = current->AsIntConstant()->GetValue();
638          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, value);
639        } else {
640          DCHECK(current->IsFloatConstant());
641          int32_t value = bit_cast<float, int32_t>(current->AsFloatConstant()->GetValue());
642          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kConstant, value);
643        }
644        break;
645      }
646
647      case Location::kStackSlot: {
648        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInStack, location.GetStackIndex());
649        break;
650      }
651
652      case Location::kDoubleStackSlot: {
653        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInStack, location.GetStackIndex());
654        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInStack,
655                                              location.GetHighStackIndex(kVRegSize));
656        ++i;
657        DCHECK_LT(i, environment_size);
658        break;
659      }
660
661      case Location::kRegister : {
662        int id = location.reg();
663        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInRegister, id);
664        if (current->GetType() == Primitive::kPrimLong) {
665          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInRegister, id);
666          ++i;
667          DCHECK_LT(i, environment_size);
668        }
669        break;
670      }
671
672      case Location::kFpuRegister : {
673        int id = location.reg();
674        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInFpuRegister, id);
675        if (current->GetType() == Primitive::kPrimDouble) {
676          stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInFpuRegister, id);
677          ++i;
678          DCHECK_LT(i, environment_size);
679        }
680        break;
681      }
682
683      case Location::kFpuRegisterPair : {
684        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInFpuRegister, location.low());
685        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInFpuRegister, location.high());
686        ++i;
687        DCHECK_LT(i, environment_size);
688        break;
689      }
690
691      case Location::kRegisterPair : {
692        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInRegister, location.low());
693        stack_map_stream_.AddDexRegisterEntry(DexRegisterMap::kInRegister, location.high());
694        ++i;
695        DCHECK_LT(i, environment_size);
696        break;
697      }
698
699      default:
700        LOG(FATAL) << "Unexpected kind " << location.GetKind();
701    }
702  }
703}
704
705bool CodeGenerator::CanMoveNullCheckToUser(HNullCheck* null_check) {
706  HInstruction* first_next_not_move = null_check->GetNextDisregardingMoves();
707  return (first_next_not_move != nullptr) && first_next_not_move->CanDoImplicitNullCheck();
708}
709
710void CodeGenerator::MaybeRecordImplicitNullCheck(HInstruction* instr) {
711  // If we are from a static path don't record the pc as we can't throw NPE.
712  // NB: having the checks here makes the code much less verbose in the arch
713  // specific code generators.
714  if (instr->IsStaticFieldSet() || instr->IsStaticFieldGet()) {
715    return;
716  }
717
718  if (!compiler_options_.GetImplicitNullChecks()) {
719    return;
720  }
721
722  if (!instr->CanDoImplicitNullCheck()) {
723    return;
724  }
725
726  // Find the first previous instruction which is not a move.
727  HInstruction* first_prev_not_move = instr->GetPreviousDisregardingMoves();
728
729  // If the instruction is a null check it means that `instr` is the first user
730  // and needs to record the pc.
731  if (first_prev_not_move != nullptr && first_prev_not_move->IsNullCheck()) {
732    HNullCheck* null_check = first_prev_not_move->AsNullCheck();
733    // TODO: The parallel moves modify the environment. Their changes need to be reverted
734    // otherwise the stack maps at the throw point will not be correct.
735    RecordPcInfo(null_check, null_check->GetDexPc());
736  }
737}
738
739void CodeGenerator::SaveLiveRegisters(LocationSummary* locations) {
740  RegisterSet* register_set = locations->GetLiveRegisters();
741  size_t stack_offset = first_register_slot_in_slow_path_;
742  for (size_t i = 0, e = GetNumberOfCoreRegisters(); i < e; ++i) {
743    if (!IsCoreCalleeSaveRegister(i)) {
744      if (register_set->ContainsCoreRegister(i)) {
745        // If the register holds an object, update the stack mask.
746        if (locations->RegisterContainsObject(i)) {
747          locations->SetStackBit(stack_offset / kVRegSize);
748        }
749        DCHECK_LT(stack_offset, GetFrameSize() - FrameEntrySpillSize());
750        stack_offset += SaveCoreRegister(stack_offset, i);
751      }
752    }
753  }
754
755  for (size_t i = 0, e = GetNumberOfFloatingPointRegisters(); i < e; ++i) {
756    if (!IsFloatingPointCalleeSaveRegister(i)) {
757      if (register_set->ContainsFloatingPointRegister(i)) {
758        DCHECK_LT(stack_offset, GetFrameSize() - FrameEntrySpillSize());
759        stack_offset += SaveFloatingPointRegister(stack_offset, i);
760      }
761    }
762  }
763}
764
765void CodeGenerator::RestoreLiveRegisters(LocationSummary* locations) {
766  RegisterSet* register_set = locations->GetLiveRegisters();
767  size_t stack_offset = first_register_slot_in_slow_path_;
768  for (size_t i = 0, e = GetNumberOfCoreRegisters(); i < e; ++i) {
769    if (!IsCoreCalleeSaveRegister(i)) {
770      if (register_set->ContainsCoreRegister(i)) {
771        DCHECK_LT(stack_offset, GetFrameSize() - FrameEntrySpillSize());
772        stack_offset += RestoreCoreRegister(stack_offset, i);
773      }
774    }
775  }
776
777  for (size_t i = 0, e = GetNumberOfFloatingPointRegisters(); i < e; ++i) {
778    if (!IsFloatingPointCalleeSaveRegister(i)) {
779      if (register_set->ContainsFloatingPointRegister(i)) {
780        DCHECK_LT(stack_offset, GetFrameSize() - FrameEntrySpillSize());
781        stack_offset += RestoreFloatingPointRegister(stack_offset, i);
782      }
783    }
784  }
785}
786
787void CodeGenerator::ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check) const {
788  LocationSummary* locations = suspend_check->GetLocations();
789  HBasicBlock* block = suspend_check->GetBlock();
790  DCHECK(block->GetLoopInformation()->GetSuspendCheck() == suspend_check);
791  DCHECK(block->IsLoopHeader());
792
793  for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
794    HInstruction* current = it.Current();
795    LiveInterval* interval = current->GetLiveInterval();
796    // We only need to clear bits of loop phis containing objects and allocated in register.
797    // Loop phis allocated on stack already have the object in the stack.
798    if (current->GetType() == Primitive::kPrimNot
799        && interval->HasRegister()
800        && interval->HasSpillSlot()) {
801      locations->ClearStackBit(interval->GetSpillSlot() / kVRegSize);
802    }
803  }
804}
805
806void CodeGenerator::EmitParallelMoves(Location from1, Location to1, Location from2, Location to2) {
807  HParallelMove parallel_move(GetGraph()->GetArena());
808  parallel_move.AddMove(from1, to1, nullptr);
809  parallel_move.AddMove(from2, to2, nullptr);
810  GetMoveResolver()->EmitNativeCode(&parallel_move);
811}
812
813}  // namespace art
814