codegen_util.cc revision 8171fc34bf74ed0df02385787d916bc13eb7f160
1/*
2 * Copyright (C) 2011 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 "dex/compiler_internals.h"
18#include "dex_file-inl.h"
19#include "gc_map.h"
20#include "mapping_table.h"
21#include "mir_to_lir-inl.h"
22#include "verifier/dex_gc_map.h"
23#include "verifier/method_verifier.h"
24
25namespace art {
26
27namespace {
28
29/* Dump a mapping table */
30template <typename It>
31void DumpMappingTable(const char* table_name, const char* descriptor, const char* name,
32                      const Signature& signature, uint32_t size, It first) {
33  if (size != 0) {
34    std::string line(StringPrintf("\n  %s %s%s_%s_table[%zu] = {", table_name,
35                     descriptor, name, signature.ToString().c_str(), size));
36    std::replace(line.begin(), line.end(), ';', '_');
37    LOG(INFO) << line;
38    for (uint32_t i = 0; i != size; ++i) {
39      line = StringPrintf("    {0x%05x, 0x%04x},", first.NativePcOffset(), first.DexPc());
40      ++first;
41      LOG(INFO) << line;
42    }
43    LOG(INFO) <<"  };\n\n";
44  }
45}
46
47}  // anonymous namespace
48
49bool Mir2Lir::IsInexpensiveConstant(RegLocation rl_src) {
50  bool res = false;
51  if (rl_src.is_const) {
52    if (rl_src.wide) {
53      if (rl_src.fp) {
54         res = InexpensiveConstantDouble(mir_graph_->ConstantValueWide(rl_src));
55      } else {
56         res = InexpensiveConstantLong(mir_graph_->ConstantValueWide(rl_src));
57      }
58    } else {
59      if (rl_src.fp) {
60         res = InexpensiveConstantFloat(mir_graph_->ConstantValue(rl_src));
61      } else {
62         res = InexpensiveConstantInt(mir_graph_->ConstantValue(rl_src));
63      }
64    }
65  }
66  return res;
67}
68
69void Mir2Lir::MarkSafepointPC(LIR* inst) {
70  DCHECK(!inst->flags.use_def_invalid);
71  inst->u.m.def_mask = ENCODE_ALL;
72  LIR* safepoint_pc = NewLIR0(kPseudoSafepointPC);
73  DCHECK_EQ(safepoint_pc->u.m.def_mask, ENCODE_ALL);
74}
75
76bool Mir2Lir::FastInstance(uint32_t field_idx, bool is_put, int* field_offset, bool* is_volatile) {
77  return cu_->compiler_driver->ComputeInstanceFieldInfo(
78      field_idx, mir_graph_->GetCurrentDexCompilationUnit(), is_put, field_offset, is_volatile);
79}
80
81/* Remove a LIR from the list. */
82void Mir2Lir::UnlinkLIR(LIR* lir) {
83  if (UNLIKELY(lir == first_lir_insn_)) {
84    first_lir_insn_ = lir->next;
85    if (lir->next != NULL) {
86      lir->next->prev = NULL;
87    } else {
88      DCHECK(lir->next == NULL);
89      DCHECK(lir == last_lir_insn_);
90      last_lir_insn_ = NULL;
91    }
92  } else if (lir == last_lir_insn_) {
93    last_lir_insn_ = lir->prev;
94    lir->prev->next = NULL;
95  } else if ((lir->prev != NULL) && (lir->next != NULL)) {
96    lir->prev->next = lir->next;
97    lir->next->prev = lir->prev;
98  }
99}
100
101/* Convert an instruction to a NOP */
102void Mir2Lir::NopLIR(LIR* lir) {
103  lir->flags.is_nop = true;
104  if (!cu_->verbose) {
105    UnlinkLIR(lir);
106  }
107}
108
109void Mir2Lir::SetMemRefType(LIR* lir, bool is_load, int mem_type) {
110  uint64_t *mask_ptr;
111  uint64_t mask = ENCODE_MEM;
112  DCHECK(GetTargetInstFlags(lir->opcode) & (IS_LOAD | IS_STORE));
113  DCHECK(!lir->flags.use_def_invalid);
114  if (is_load) {
115    mask_ptr = &lir->u.m.use_mask;
116  } else {
117    mask_ptr = &lir->u.m.def_mask;
118  }
119  /* Clear out the memref flags */
120  *mask_ptr &= ~mask;
121  /* ..and then add back the one we need */
122  switch (mem_type) {
123    case kLiteral:
124      DCHECK(is_load);
125      *mask_ptr |= ENCODE_LITERAL;
126      break;
127    case kDalvikReg:
128      *mask_ptr |= ENCODE_DALVIK_REG;
129      break;
130    case kHeapRef:
131      *mask_ptr |= ENCODE_HEAP_REF;
132      break;
133    case kMustNotAlias:
134      /* Currently only loads can be marked as kMustNotAlias */
135      DCHECK(!(GetTargetInstFlags(lir->opcode) & IS_STORE));
136      *mask_ptr |= ENCODE_MUST_NOT_ALIAS;
137      break;
138    default:
139      LOG(FATAL) << "Oat: invalid memref kind - " << mem_type;
140  }
141}
142
143/*
144 * Mark load/store instructions that access Dalvik registers through the stack.
145 */
146void Mir2Lir::AnnotateDalvikRegAccess(LIR* lir, int reg_id, bool is_load,
147                                      bool is64bit) {
148  SetMemRefType(lir, is_load, kDalvikReg);
149
150  /*
151   * Store the Dalvik register id in alias_info. Mark the MSB if it is a 64-bit
152   * access.
153   */
154  lir->flags.alias_info = ENCODE_ALIAS_INFO(reg_id, is64bit);
155}
156
157/*
158 * Debugging macros
159 */
160#define DUMP_RESOURCE_MASK(X)
161
162/* Pretty-print a LIR instruction */
163void Mir2Lir::DumpLIRInsn(LIR* lir, unsigned char* base_addr) {
164  int offset = lir->offset;
165  int dest = lir->operands[0];
166  const bool dump_nop = (cu_->enable_debug & (1 << kDebugShowNops));
167
168  /* Handle pseudo-ops individually, and all regular insns as a group */
169  switch (lir->opcode) {
170    case kPseudoMethodEntry:
171      LOG(INFO) << "-------- method entry "
172                << PrettyMethod(cu_->method_idx, *cu_->dex_file);
173      break;
174    case kPseudoMethodExit:
175      LOG(INFO) << "-------- Method_Exit";
176      break;
177    case kPseudoBarrier:
178      LOG(INFO) << "-------- BARRIER";
179      break;
180    case kPseudoEntryBlock:
181      LOG(INFO) << "-------- entry offset: 0x" << std::hex << dest;
182      break;
183    case kPseudoDalvikByteCodeBoundary:
184      if (lir->operands[0] == 0) {
185         // NOTE: only used for debug listings.
186         lir->operands[0] = WrapPointer(ArenaStrdup("No instruction string"));
187      }
188      LOG(INFO) << "-------- dalvik offset: 0x" << std::hex
189                << lir->dalvik_offset << " @ "
190                << reinterpret_cast<char*>(UnwrapPointer(lir->operands[0]));
191      break;
192    case kPseudoExitBlock:
193      LOG(INFO) << "-------- exit offset: 0x" << std::hex << dest;
194      break;
195    case kPseudoPseudoAlign4:
196      LOG(INFO) << reinterpret_cast<uintptr_t>(base_addr) + offset << " (0x" << std::hex
197                << offset << "): .align4";
198      break;
199    case kPseudoEHBlockLabel:
200      LOG(INFO) << "Exception_Handling:";
201      break;
202    case kPseudoTargetLabel:
203    case kPseudoNormalBlockLabel:
204      LOG(INFO) << "L" << reinterpret_cast<void*>(lir) << ":";
205      break;
206    case kPseudoThrowTarget:
207      LOG(INFO) << "LT" << reinterpret_cast<void*>(lir) << ":";
208      break;
209    case kPseudoIntrinsicRetry:
210      LOG(INFO) << "IR" << reinterpret_cast<void*>(lir) << ":";
211      break;
212    case kPseudoSuspendTarget:
213      LOG(INFO) << "LS" << reinterpret_cast<void*>(lir) << ":";
214      break;
215    case kPseudoSafepointPC:
216      LOG(INFO) << "LsafepointPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
217      break;
218    case kPseudoExportedPC:
219      LOG(INFO) << "LexportedPC_0x" << std::hex << lir->offset << "_" << lir->dalvik_offset << ":";
220      break;
221    case kPseudoCaseLabel:
222      LOG(INFO) << "LC" << reinterpret_cast<void*>(lir) << ": Case target 0x"
223                << std::hex << lir->operands[0] << "|" << std::dec <<
224        lir->operands[0];
225      break;
226    default:
227      if (lir->flags.is_nop && !dump_nop) {
228        break;
229      } else {
230        std::string op_name(BuildInsnString(GetTargetInstName(lir->opcode),
231                                               lir, base_addr));
232        std::string op_operands(BuildInsnString(GetTargetInstFmt(lir->opcode),
233                                                    lir, base_addr));
234        LOG(INFO) << StringPrintf("%05x: %-9s%s%s",
235                                  reinterpret_cast<unsigned int>(base_addr + offset),
236                                  op_name.c_str(), op_operands.c_str(),
237                                  lir->flags.is_nop ? "(nop)" : "");
238      }
239      break;
240  }
241
242  if (lir->u.m.use_mask && (!lir->flags.is_nop || dump_nop)) {
243    DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.use_mask, "use"));
244  }
245  if (lir->u.m.def_mask && (!lir->flags.is_nop || dump_nop)) {
246    DUMP_RESOURCE_MASK(DumpResourceMask(lir, lir->u.m.def_mask, "def"));
247  }
248}
249
250void Mir2Lir::DumpPromotionMap() {
251  int num_regs = cu_->num_dalvik_registers + cu_->num_compiler_temps + 1;
252  for (int i = 0; i < num_regs; i++) {
253    PromotionMap v_reg_map = promotion_map_[i];
254    std::string buf;
255    if (v_reg_map.fp_location == kLocPhysReg) {
256      StringAppendF(&buf, " : s%d", v_reg_map.FpReg & FpRegMask());
257    }
258
259    std::string buf3;
260    if (i < cu_->num_dalvik_registers) {
261      StringAppendF(&buf3, "%02d", i);
262    } else if (i == mir_graph_->GetMethodSReg()) {
263      buf3 = "Method*";
264    } else {
265      StringAppendF(&buf3, "ct%d", i - cu_->num_dalvik_registers);
266    }
267
268    LOG(INFO) << StringPrintf("V[%s] -> %s%d%s", buf3.c_str(),
269                              v_reg_map.core_location == kLocPhysReg ?
270                              "r" : "SP+", v_reg_map.core_location == kLocPhysReg ?
271                              v_reg_map.core_reg : SRegOffset(i),
272                              buf.c_str());
273  }
274}
275
276/* Dump instructions and constant pool contents */
277void Mir2Lir::CodegenDump() {
278  LOG(INFO) << "Dumping LIR insns for "
279            << PrettyMethod(cu_->method_idx, *cu_->dex_file);
280  LIR* lir_insn;
281  int insns_size = cu_->code_item->insns_size_in_code_units_;
282
283  LOG(INFO) << "Regs (excluding ins) : " << cu_->num_regs;
284  LOG(INFO) << "Ins          : " << cu_->num_ins;
285  LOG(INFO) << "Outs         : " << cu_->num_outs;
286  LOG(INFO) << "CoreSpills       : " << num_core_spills_;
287  LOG(INFO) << "FPSpills       : " << num_fp_spills_;
288  LOG(INFO) << "CompilerTemps    : " << cu_->num_compiler_temps;
289  LOG(INFO) << "Frame size       : " << frame_size_;
290  LOG(INFO) << "code size is " << total_size_ <<
291    " bytes, Dalvik size is " << insns_size * 2;
292  LOG(INFO) << "expansion factor: "
293            << static_cast<float>(total_size_) / static_cast<float>(insns_size * 2);
294  DumpPromotionMap();
295  for (lir_insn = first_lir_insn_; lir_insn != NULL; lir_insn = lir_insn->next) {
296    DumpLIRInsn(lir_insn, 0);
297  }
298  for (lir_insn = literal_list_; lir_insn != NULL; lir_insn = lir_insn->next) {
299    LOG(INFO) << StringPrintf("%x (%04x): .word (%#x)", lir_insn->offset, lir_insn->offset,
300                              lir_insn->operands[0]);
301  }
302
303  const DexFile::MethodId& method_id =
304      cu_->dex_file->GetMethodId(cu_->method_idx);
305  const Signature signature = cu_->dex_file->GetMethodSignature(method_id);
306  const char* name = cu_->dex_file->GetMethodName(method_id);
307  const char* descriptor(cu_->dex_file->GetMethodDeclaringClassDescriptor(method_id));
308
309  // Dump mapping tables
310  if (!encoded_mapping_table_.empty()) {
311    MappingTable table(&encoded_mapping_table_[0]);
312    DumpMappingTable("PC2Dex_MappingTable", descriptor, name, signature,
313                     table.PcToDexSize(), table.PcToDexBegin());
314    DumpMappingTable("Dex2PC_MappingTable", descriptor, name, signature,
315                     table.DexToPcSize(), table.DexToPcBegin());
316  }
317}
318
319/*
320 * Search the existing constants in the literal pool for an exact or close match
321 * within specified delta (greater or equal to 0).
322 */
323LIR* Mir2Lir::ScanLiteralPool(LIR* data_target, int value, unsigned int delta) {
324  while (data_target) {
325    if ((static_cast<unsigned>(value - data_target->operands[0])) <= delta)
326      return data_target;
327    data_target = data_target->next;
328  }
329  return NULL;
330}
331
332/* Search the existing constants in the literal pool for an exact wide match */
333LIR* Mir2Lir::ScanLiteralPoolWide(LIR* data_target, int val_lo, int val_hi) {
334  bool lo_match = false;
335  LIR* lo_target = NULL;
336  while (data_target) {
337    if (lo_match && (data_target->operands[0] == val_hi)) {
338      // Record high word in case we need to expand this later.
339      lo_target->operands[1] = val_hi;
340      return lo_target;
341    }
342    lo_match = false;
343    if (data_target->operands[0] == val_lo) {
344      lo_match = true;
345      lo_target = data_target;
346    }
347    data_target = data_target->next;
348  }
349  return NULL;
350}
351
352/*
353 * The following are building blocks to insert constants into the pool or
354 * instruction streams.
355 */
356
357/* Add a 32-bit constant to the constant pool */
358LIR* Mir2Lir::AddWordData(LIR* *constant_list_p, int value) {
359  /* Add the constant to the literal pool */
360  if (constant_list_p) {
361    LIR* new_value = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocData));
362    new_value->operands[0] = value;
363    new_value->next = *constant_list_p;
364    *constant_list_p = new_value;
365    estimated_native_code_size_ += sizeof(value);
366    return new_value;
367  }
368  return NULL;
369}
370
371/* Add a 64-bit constant to the constant pool or mixed with code */
372LIR* Mir2Lir::AddWideData(LIR* *constant_list_p, int val_lo, int val_hi) {
373  AddWordData(constant_list_p, val_hi);
374  return AddWordData(constant_list_p, val_lo);
375}
376
377static void PushWord(std::vector<uint8_t>&buf, int data) {
378  buf.push_back(data & 0xff);
379  buf.push_back((data >> 8) & 0xff);
380  buf.push_back((data >> 16) & 0xff);
381  buf.push_back((data >> 24) & 0xff);
382}
383
384// Push 8 bytes on 64-bit systems; 4 on 32-bit systems.
385static void PushPointer(std::vector<uint8_t>&buf, void const* pointer) {
386  uintptr_t data = reinterpret_cast<uintptr_t>(pointer);
387  if (sizeof(void*) == sizeof(uint64_t)) {
388    PushWord(buf, (data >> (sizeof(void*) * 4)) & 0xFFFFFFFF);
389    PushWord(buf, data & 0xFFFFFFFF);
390  } else {
391    PushWord(buf, data);
392  }
393}
394
395static void AlignBuffer(std::vector<uint8_t>&buf, size_t offset) {
396  while (buf.size() < offset) {
397    buf.push_back(0);
398  }
399}
400
401/* Write the literal pool to the output stream */
402void Mir2Lir::InstallLiteralPools() {
403  AlignBuffer(code_buffer_, data_offset_);
404  LIR* data_lir = literal_list_;
405  while (data_lir != NULL) {
406    PushWord(code_buffer_, data_lir->operands[0]);
407    data_lir = NEXT_LIR(data_lir);
408  }
409  // Push code and method literals, record offsets for the compiler to patch.
410  data_lir = code_literal_list_;
411  while (data_lir != NULL) {
412    uint32_t target = data_lir->operands[0];
413    cu_->compiler_driver->AddCodePatch(cu_->dex_file,
414                                       cu_->class_def_idx,
415                                       cu_->method_idx,
416                                       cu_->invoke_type,
417                                       target,
418                                       static_cast<InvokeType>(data_lir->operands[1]),
419                                       code_buffer_.size());
420    const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
421    // unique value based on target to ensure code deduplication works
422    PushPointer(code_buffer_, &id);
423    data_lir = NEXT_LIR(data_lir);
424  }
425  data_lir = method_literal_list_;
426  while (data_lir != NULL) {
427    uint32_t target = data_lir->operands[0];
428    cu_->compiler_driver->AddMethodPatch(cu_->dex_file,
429                                         cu_->class_def_idx,
430                                         cu_->method_idx,
431                                         cu_->invoke_type,
432                                         target,
433                                         static_cast<InvokeType>(data_lir->operands[1]),
434                                         code_buffer_.size());
435    const DexFile::MethodId& id = cu_->dex_file->GetMethodId(target);
436    // unique value based on target to ensure code deduplication works
437    PushPointer(code_buffer_, &id);
438    data_lir = NEXT_LIR(data_lir);
439  }
440}
441
442/* Write the switch tables to the output stream */
443void Mir2Lir::InstallSwitchTables() {
444  GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
445  while (true) {
446    Mir2Lir::SwitchTable* tab_rec = iterator.Next();
447    if (tab_rec == NULL) break;
448    AlignBuffer(code_buffer_, tab_rec->offset);
449    /*
450     * For Arm, our reference point is the address of the bx
451     * instruction that does the launch, so we have to subtract
452     * the auto pc-advance.  For other targets the reference point
453     * is a label, so we can use the offset as-is.
454     */
455    int bx_offset = INVALID_OFFSET;
456    switch (cu_->instruction_set) {
457      case kThumb2:
458        DCHECK(tab_rec->anchor->flags.fixup != kFixupNone);
459        bx_offset = tab_rec->anchor->offset + 4;
460        break;
461      case kX86:
462        bx_offset = 0;
463        break;
464      case kMips:
465        bx_offset = tab_rec->anchor->offset;
466        break;
467      default: LOG(FATAL) << "Unexpected instruction set: " << cu_->instruction_set;
468    }
469    if (cu_->verbose) {
470      LOG(INFO) << "Switch table for offset 0x" << std::hex << bx_offset;
471    }
472    if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
473      const int32_t* keys = reinterpret_cast<const int32_t*>(&(tab_rec->table[2]));
474      for (int elems = 0; elems < tab_rec->table[1]; elems++) {
475        int disp = tab_rec->targets[elems]->offset - bx_offset;
476        if (cu_->verbose) {
477          LOG(INFO) << "  Case[" << elems << "] key: 0x"
478                    << std::hex << keys[elems] << ", disp: 0x"
479                    << std::hex << disp;
480        }
481        PushWord(code_buffer_, keys[elems]);
482        PushWord(code_buffer_,
483          tab_rec->targets[elems]->offset - bx_offset);
484      }
485    } else {
486      DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
487                static_cast<int>(Instruction::kPackedSwitchSignature));
488      for (int elems = 0; elems < tab_rec->table[1]; elems++) {
489        int disp = tab_rec->targets[elems]->offset - bx_offset;
490        if (cu_->verbose) {
491          LOG(INFO) << "  Case[" << elems << "] disp: 0x"
492                    << std::hex << disp;
493        }
494        PushWord(code_buffer_, tab_rec->targets[elems]->offset - bx_offset);
495      }
496    }
497  }
498}
499
500/* Write the fill array dta to the output stream */
501void Mir2Lir::InstallFillArrayData() {
502  GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
503  while (true) {
504    Mir2Lir::FillArrayData *tab_rec = iterator.Next();
505    if (tab_rec == NULL) break;
506    AlignBuffer(code_buffer_, tab_rec->offset);
507    for (int i = 0; i < (tab_rec->size + 1) / 2; i++) {
508      code_buffer_.push_back(tab_rec->table[i] & 0xFF);
509      code_buffer_.push_back((tab_rec->table[i] >> 8) & 0xFF);
510    }
511  }
512}
513
514static int AssignLiteralOffsetCommon(LIR* lir, CodeOffset offset) {
515  for (; lir != NULL; lir = lir->next) {
516    lir->offset = offset;
517    offset += 4;
518  }
519  return offset;
520}
521
522static int AssignLiteralPointerOffsetCommon(LIR* lir, CodeOffset offset) {
523  unsigned int element_size = sizeof(void*);
524  // Align to natural pointer size.
525  offset = (offset + (element_size - 1)) & ~(element_size - 1);
526  for (; lir != NULL; lir = lir->next) {
527    lir->offset = offset;
528    offset += element_size;
529  }
530  return offset;
531}
532
533// Make sure we have a code address for every declared catch entry
534bool Mir2Lir::VerifyCatchEntries() {
535  MappingTable table(&encoded_mapping_table_[0]);
536  std::vector<uint32_t> dex_pcs;
537  dex_pcs.reserve(table.DexToPcSize());
538  for (auto it = table.DexToPcBegin(), end = table.DexToPcEnd(); it != end; ++it) {
539    dex_pcs.push_back(it.DexPc());
540  }
541  // Sort dex_pcs, so that we can quickly check it against the ordered mir_graph_->catches_.
542  std::sort(dex_pcs.begin(), dex_pcs.end());
543
544  bool success = true;
545  auto it = dex_pcs.begin(), end = dex_pcs.end();
546  for (uint32_t dex_pc : mir_graph_->catches_) {
547    while (it != end && *it < dex_pc) {
548      LOG(INFO) << "Unexpected catch entry @ dex pc 0x" << std::hex << *it;
549      ++it;
550      success = false;
551    }
552    if (it == end || *it > dex_pc) {
553      LOG(INFO) << "Missing native PC for catch entry @ 0x" << std::hex << dex_pc;
554      success = false;
555    } else {
556      ++it;
557    }
558  }
559  if (!success) {
560    LOG(INFO) << "Bad dex2pcMapping table in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
561    LOG(INFO) << "Entries @ decode: " << mir_graph_->catches_.size() << ", Entries in table: "
562              << table.DexToPcSize();
563  }
564  return success;
565}
566
567
568void Mir2Lir::CreateMappingTables() {
569  uint32_t pc2dex_data_size = 0u;
570  uint32_t pc2dex_entries = 0u;
571  uint32_t pc2dex_offset = 0u;
572  uint32_t pc2dex_dalvik_offset = 0u;
573  uint32_t dex2pc_data_size = 0u;
574  uint32_t dex2pc_entries = 0u;
575  uint32_t dex2pc_offset = 0u;
576  uint32_t dex2pc_dalvik_offset = 0u;
577  for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
578    if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
579      pc2dex_entries += 1;
580      DCHECK(pc2dex_offset <= tgt_lir->offset);
581      pc2dex_data_size += UnsignedLeb128Size(tgt_lir->offset - pc2dex_offset);
582      pc2dex_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
583                                           static_cast<int32_t>(pc2dex_dalvik_offset));
584      pc2dex_offset = tgt_lir->offset;
585      pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
586    }
587    if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
588      dex2pc_entries += 1;
589      DCHECK(dex2pc_offset <= tgt_lir->offset);
590      dex2pc_data_size += UnsignedLeb128Size(tgt_lir->offset - dex2pc_offset);
591      dex2pc_data_size += SignedLeb128Size(static_cast<int32_t>(tgt_lir->dalvik_offset) -
592                                           static_cast<int32_t>(dex2pc_dalvik_offset));
593      dex2pc_offset = tgt_lir->offset;
594      dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
595    }
596  }
597
598  uint32_t total_entries = pc2dex_entries + dex2pc_entries;
599  uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
600  uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
601  encoded_mapping_table_.resize(data_size);
602  uint8_t* write_pos = &encoded_mapping_table_[0];
603  write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
604  write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
605  DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]), hdr_data_size);
606  uint8_t* write_pos2 = write_pos + pc2dex_data_size;
607
608  pc2dex_offset = 0u;
609  pc2dex_dalvik_offset = 0u;
610  dex2pc_offset = 0u;
611  dex2pc_dalvik_offset = 0u;
612  for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
613    if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
614      DCHECK(pc2dex_offset <= tgt_lir->offset);
615      write_pos = EncodeUnsignedLeb128(write_pos, tgt_lir->offset - pc2dex_offset);
616      write_pos = EncodeSignedLeb128(write_pos, static_cast<int32_t>(tgt_lir->dalvik_offset) -
617                                     static_cast<int32_t>(pc2dex_dalvik_offset));
618      pc2dex_offset = tgt_lir->offset;
619      pc2dex_dalvik_offset = tgt_lir->dalvik_offset;
620    }
621    if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
622      DCHECK(dex2pc_offset <= tgt_lir->offset);
623      write_pos2 = EncodeUnsignedLeb128(write_pos2, tgt_lir->offset - dex2pc_offset);
624      write_pos2 = EncodeSignedLeb128(write_pos2, static_cast<int32_t>(tgt_lir->dalvik_offset) -
625                                      static_cast<int32_t>(dex2pc_dalvik_offset));
626      dex2pc_offset = tgt_lir->offset;
627      dex2pc_dalvik_offset = tgt_lir->dalvik_offset;
628    }
629  }
630  DCHECK_EQ(static_cast<size_t>(write_pos - &encoded_mapping_table_[0]),
631            hdr_data_size + pc2dex_data_size);
632  DCHECK_EQ(static_cast<size_t>(write_pos2 - &encoded_mapping_table_[0]), data_size);
633
634  if (kIsDebugBuild) {
635    CHECK(VerifyCatchEntries());
636
637    // Verify the encoded table holds the expected data.
638    MappingTable table(&encoded_mapping_table_[0]);
639    CHECK_EQ(table.TotalSize(), total_entries);
640    CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
641    auto it = table.PcToDexBegin();
642    auto it2 = table.DexToPcBegin();
643    for (LIR* tgt_lir = first_lir_insn_; tgt_lir != NULL; tgt_lir = NEXT_LIR(tgt_lir)) {
644      if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoSafepointPC)) {
645        CHECK_EQ(tgt_lir->offset, it.NativePcOffset());
646        CHECK_EQ(tgt_lir->dalvik_offset, it.DexPc());
647        ++it;
648      }
649      if (!tgt_lir->flags.is_nop && (tgt_lir->opcode == kPseudoExportedPC)) {
650        CHECK_EQ(tgt_lir->offset, it2.NativePcOffset());
651        CHECK_EQ(tgt_lir->dalvik_offset, it2.DexPc());
652        ++it2;
653      }
654    }
655    CHECK(it == table.PcToDexEnd());
656    CHECK(it2 == table.DexToPcEnd());
657  }
658}
659
660class NativePcToReferenceMapBuilder {
661 public:
662  NativePcToReferenceMapBuilder(std::vector<uint8_t>* table,
663                                size_t entries, uint32_t max_native_offset,
664                                size_t references_width) : entries_(entries),
665                                references_width_(references_width), in_use_(entries),
666                                table_(table) {
667    // Compute width in bytes needed to hold max_native_offset.
668    native_offset_width_ = 0;
669    while (max_native_offset != 0) {
670      native_offset_width_++;
671      max_native_offset >>= 8;
672    }
673    // Resize table and set up header.
674    table->resize((EntryWidth() * entries) + sizeof(uint32_t));
675    CHECK_LT(native_offset_width_, 1U << 3);
676    (*table)[0] = native_offset_width_ & 7;
677    CHECK_LT(references_width_, 1U << 13);
678    (*table)[0] |= (references_width_ << 3) & 0xFF;
679    (*table)[1] = (references_width_ >> 5) & 0xFF;
680    CHECK_LT(entries, 1U << 16);
681    (*table)[2] = entries & 0xFF;
682    (*table)[3] = (entries >> 8) & 0xFF;
683  }
684
685  void AddEntry(uint32_t native_offset, const uint8_t* references) {
686    size_t table_index = TableIndex(native_offset);
687    while (in_use_[table_index]) {
688      table_index = (table_index + 1) % entries_;
689    }
690    in_use_[table_index] = true;
691    SetCodeOffset(table_index, native_offset);
692    DCHECK_EQ(native_offset, GetCodeOffset(table_index));
693    SetReferences(table_index, references);
694  }
695
696 private:
697  size_t TableIndex(uint32_t native_offset) {
698    return NativePcOffsetToReferenceMap::Hash(native_offset) % entries_;
699  }
700
701  uint32_t GetCodeOffset(size_t table_index) {
702    uint32_t native_offset = 0;
703    size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
704    for (size_t i = 0; i < native_offset_width_; i++) {
705      native_offset |= (*table_)[table_offset + i] << (i * 8);
706    }
707    return native_offset;
708  }
709
710  void SetCodeOffset(size_t table_index, uint32_t native_offset) {
711    size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
712    for (size_t i = 0; i < native_offset_width_; i++) {
713      (*table_)[table_offset + i] = (native_offset >> (i * 8)) & 0xFF;
714    }
715  }
716
717  void SetReferences(size_t table_index, const uint8_t* references) {
718    size_t table_offset = (table_index * EntryWidth()) + sizeof(uint32_t);
719    memcpy(&(*table_)[table_offset + native_offset_width_], references, references_width_);
720  }
721
722  size_t EntryWidth() const {
723    return native_offset_width_ + references_width_;
724  }
725
726  // Number of entries in the table.
727  const size_t entries_;
728  // Number of bytes used to encode the reference bitmap.
729  const size_t references_width_;
730  // Number of bytes used to encode a native offset.
731  size_t native_offset_width_;
732  // Entries that are in use.
733  std::vector<bool> in_use_;
734  // The table we're building.
735  std::vector<uint8_t>* const table_;
736};
737
738void Mir2Lir::CreateNativeGcMap() {
739  DCHECK(!encoded_mapping_table_.empty());
740  MappingTable mapping_table(&encoded_mapping_table_[0]);
741  uint32_t max_native_offset = 0;
742  for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
743    uint32_t native_offset = it.NativePcOffset();
744    if (native_offset > max_native_offset) {
745      max_native_offset = native_offset;
746    }
747  }
748  MethodReference method_ref(cu_->dex_file, cu_->method_idx);
749  const std::vector<uint8_t>* gc_map_raw = verifier::MethodVerifier::GetDexGcMap(method_ref);
750  verifier::DexPcToReferenceMap dex_gc_map(&(*gc_map_raw)[0]);
751  DCHECK_EQ(gc_map_raw->size(), dex_gc_map.RawSize());
752  // Compute native offset to references size.
753  NativePcToReferenceMapBuilder native_gc_map_builder(&native_gc_map_,
754                                                      mapping_table.PcToDexSize(),
755                                                      max_native_offset, dex_gc_map.RegWidth());
756
757  for (auto it = mapping_table.PcToDexBegin(), end = mapping_table.PcToDexEnd(); it != end; ++it) {
758    uint32_t native_offset = it.NativePcOffset();
759    uint32_t dex_pc = it.DexPc();
760    const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
761    CHECK(references != NULL) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
762    native_gc_map_builder.AddEntry(native_offset, references);
763  }
764}
765
766/* Determine the offset of each literal field */
767int Mir2Lir::AssignLiteralOffset(CodeOffset offset) {
768  offset = AssignLiteralOffsetCommon(literal_list_, offset);
769  offset = AssignLiteralPointerOffsetCommon(code_literal_list_, offset);
770  offset = AssignLiteralPointerOffsetCommon(method_literal_list_, offset);
771  return offset;
772}
773
774int Mir2Lir::AssignSwitchTablesOffset(CodeOffset offset) {
775  GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
776  while (true) {
777    Mir2Lir::SwitchTable* tab_rec = iterator.Next();
778    if (tab_rec == NULL) break;
779    tab_rec->offset = offset;
780    if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
781      offset += tab_rec->table[1] * (sizeof(int) * 2);
782    } else {
783      DCHECK_EQ(static_cast<int>(tab_rec->table[0]),
784                static_cast<int>(Instruction::kPackedSwitchSignature));
785      offset += tab_rec->table[1] * sizeof(int);
786    }
787  }
788  return offset;
789}
790
791int Mir2Lir::AssignFillArrayDataOffset(CodeOffset offset) {
792  GrowableArray<FillArrayData*>::Iterator iterator(&fill_array_data_);
793  while (true) {
794    Mir2Lir::FillArrayData *tab_rec = iterator.Next();
795    if (tab_rec == NULL) break;
796    tab_rec->offset = offset;
797    offset += tab_rec->size;
798    // word align
799    offset = (offset + 3) & ~3;
800    }
801  return offset;
802}
803
804/*
805 * Insert a kPseudoCaseLabel at the beginning of the Dalvik
806 * offset vaddr if pretty-printing, otherise use the standard block
807 * label.  The selected label will be used to fix up the case
808 * branch table during the assembly phase.  All resource flags
809 * are set to prevent code motion.  KeyVal is just there for debugging.
810 */
811LIR* Mir2Lir::InsertCaseLabel(DexOffset vaddr, int keyVal) {
812  LIR* boundary_lir = &block_label_list_[mir_graph_->FindBlock(vaddr)->id];
813  LIR* res = boundary_lir;
814  if (cu_->verbose) {
815    // Only pay the expense if we're pretty-printing.
816    LIR* new_label = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocLIR));
817    new_label->dalvik_offset = vaddr;
818    new_label->opcode = kPseudoCaseLabel;
819    new_label->operands[0] = keyVal;
820    new_label->flags.fixup = kFixupLabel;
821    DCHECK(!new_label->flags.use_def_invalid);
822    new_label->u.m.def_mask = ENCODE_ALL;
823    InsertLIRAfter(boundary_lir, new_label);
824    res = new_label;
825  }
826  return res;
827}
828
829void Mir2Lir::MarkPackedCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
830  const uint16_t* table = tab_rec->table;
831  DexOffset base_vaddr = tab_rec->vaddr;
832  const int32_t *targets = reinterpret_cast<const int32_t*>(&table[4]);
833  int entries = table[1];
834  int low_key = s4FromSwitchData(&table[2]);
835  for (int i = 0; i < entries; i++) {
836    tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], i + low_key);
837  }
838}
839
840void Mir2Lir::MarkSparseCaseLabels(Mir2Lir::SwitchTable* tab_rec) {
841  const uint16_t* table = tab_rec->table;
842  DexOffset base_vaddr = tab_rec->vaddr;
843  int entries = table[1];
844  const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
845  const int32_t* targets = &keys[entries];
846  for (int i = 0; i < entries; i++) {
847    tab_rec->targets[i] = InsertCaseLabel(base_vaddr + targets[i], keys[i]);
848  }
849}
850
851void Mir2Lir::ProcessSwitchTables() {
852  GrowableArray<SwitchTable*>::Iterator iterator(&switch_tables_);
853  while (true) {
854    Mir2Lir::SwitchTable *tab_rec = iterator.Next();
855    if (tab_rec == NULL) break;
856    if (tab_rec->table[0] == Instruction::kPackedSwitchSignature) {
857      MarkPackedCaseLabels(tab_rec);
858    } else if (tab_rec->table[0] == Instruction::kSparseSwitchSignature) {
859      MarkSparseCaseLabels(tab_rec);
860    } else {
861      LOG(FATAL) << "Invalid switch table";
862    }
863  }
864}
865
866void Mir2Lir::DumpSparseSwitchTable(const uint16_t* table) {
867  /*
868   * Sparse switch data format:
869   *  ushort ident = 0x0200   magic value
870   *  ushort size       number of entries in the table; > 0
871   *  int keys[size]      keys, sorted low-to-high; 32-bit aligned
872   *  int targets[size]     branch targets, relative to switch opcode
873   *
874   * Total size is (2+size*4) 16-bit code units.
875   */
876  uint16_t ident = table[0];
877  int entries = table[1];
878  const int32_t* keys = reinterpret_cast<const int32_t*>(&table[2]);
879  const int32_t* targets = &keys[entries];
880  LOG(INFO) <<  "Sparse switch table - ident:0x" << std::hex << ident
881            << ", entries: " << std::dec << entries;
882  for (int i = 0; i < entries; i++) {
883    LOG(INFO) << "  Key[" << keys[i] << "] -> 0x" << std::hex << targets[i];
884  }
885}
886
887void Mir2Lir::DumpPackedSwitchTable(const uint16_t* table) {
888  /*
889   * Packed switch data format:
890   *  ushort ident = 0x0100   magic value
891   *  ushort size       number of entries in the table
892   *  int first_key       first (and lowest) switch case value
893   *  int targets[size]     branch targets, relative to switch opcode
894   *
895   * Total size is (4+size*2) 16-bit code units.
896   */
897  uint16_t ident = table[0];
898  const int32_t* targets = reinterpret_cast<const int32_t*>(&table[4]);
899  int entries = table[1];
900  int low_key = s4FromSwitchData(&table[2]);
901  LOG(INFO) << "Packed switch table - ident:0x" << std::hex << ident
902            << ", entries: " << std::dec << entries << ", low_key: " << low_key;
903  for (int i = 0; i < entries; i++) {
904    LOG(INFO) << "  Key[" << (i + low_key) << "] -> 0x" << std::hex
905              << targets[i];
906  }
907}
908
909/* Set up special LIR to mark a Dalvik byte-code instruction start for pretty printing */
910void Mir2Lir::MarkBoundary(DexOffset offset, const char* inst_str) {
911  // NOTE: only used for debug listings.
912  NewLIR1(kPseudoDalvikByteCodeBoundary, WrapPointer(ArenaStrdup(inst_str)));
913}
914
915bool Mir2Lir::EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
916  bool is_taken;
917  switch (opcode) {
918    case Instruction::IF_EQ: is_taken = (src1 == src2); break;
919    case Instruction::IF_NE: is_taken = (src1 != src2); break;
920    case Instruction::IF_LT: is_taken = (src1 < src2); break;
921    case Instruction::IF_GE: is_taken = (src1 >= src2); break;
922    case Instruction::IF_GT: is_taken = (src1 > src2); break;
923    case Instruction::IF_LE: is_taken = (src1 <= src2); break;
924    case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
925    case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
926    case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
927    case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
928    case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
929    case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
930    default:
931      LOG(FATAL) << "Unexpected opcode " << opcode;
932      is_taken = false;
933  }
934  return is_taken;
935}
936
937// Convert relation of src1/src2 to src2/src1
938ConditionCode Mir2Lir::FlipComparisonOrder(ConditionCode before) {
939  ConditionCode res;
940  switch (before) {
941    case kCondEq: res = kCondEq; break;
942    case kCondNe: res = kCondNe; break;
943    case kCondLt: res = kCondGt; break;
944    case kCondGt: res = kCondLt; break;
945    case kCondLe: res = kCondGe; break;
946    case kCondGe: res = kCondLe; break;
947    default:
948      res = static_cast<ConditionCode>(0);
949      LOG(FATAL) << "Unexpected ccode " << before;
950  }
951  return res;
952}
953
954// TODO: move to mir_to_lir.cc
955Mir2Lir::Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena)
956    : Backend(arena),
957      literal_list_(NULL),
958      method_literal_list_(NULL),
959      code_literal_list_(NULL),
960      first_fixup_(NULL),
961      cu_(cu),
962      mir_graph_(mir_graph),
963      switch_tables_(arena, 4, kGrowableArraySwitchTables),
964      fill_array_data_(arena, 4, kGrowableArrayFillArrayData),
965      throw_launchpads_(arena, 2048, kGrowableArrayThrowLaunchPads),
966      suspend_launchpads_(arena, 4, kGrowableArraySuspendLaunchPads),
967      intrinsic_launchpads_(arena, 2048, kGrowableArrayMisc),
968      tempreg_info_(arena, 20, kGrowableArrayMisc),
969      reginfo_map_(arena, 64, kGrowableArrayMisc),
970      pointer_storage_(arena, 128, kGrowableArrayMisc),
971      data_offset_(0),
972      total_size_(0),
973      block_label_list_(NULL),
974      current_dalvik_offset_(0),
975      estimated_native_code_size_(0),
976      reg_pool_(NULL),
977      live_sreg_(0),
978      num_core_spills_(0),
979      num_fp_spills_(0),
980      frame_size_(0),
981      core_spill_mask_(0),
982      fp_spill_mask_(0),
983      first_lir_insn_(NULL),
984      last_lir_insn_(NULL),
985      inliner_(nullptr) {
986  promotion_map_ = static_cast<PromotionMap*>
987      (arena_->Alloc((cu_->num_dalvik_registers  + cu_->num_compiler_temps + 1) *
988                      sizeof(promotion_map_[0]), ArenaAllocator::kAllocRegAlloc));
989  // Reserve pointer id 0 for NULL.
990  size_t null_idx = WrapPointer(NULL);
991  DCHECK_EQ(null_idx, 0U);
992}
993
994void Mir2Lir::Materialize() {
995  cu_->NewTimingSplit("RegisterAllocation");
996  CompilerInitializeRegAlloc();  // Needs to happen after SSA naming
997
998  /* Allocate Registers using simple local allocation scheme */
999  SimpleRegAlloc();
1000
1001  if (mir_graph_->IsSpecialCase()) {
1002      /*
1003       * Custom codegen for special cases.  If for any reason the
1004       * special codegen doesn't succeed, first_lir_insn_ will
1005       * set to NULL;
1006       */
1007      cu_->NewTimingSplit("SpecialMIR2LIR");
1008      SpecialMIR2LIR(mir_graph_->GetSpecialCase());
1009    }
1010
1011  /* Convert MIR to LIR, etc. */
1012  if (first_lir_insn_ == NULL) {
1013    MethodMIR2LIR();
1014  }
1015
1016  /* Method is not empty */
1017  if (first_lir_insn_) {
1018    // mark the targets of switch statement case labels
1019    ProcessSwitchTables();
1020
1021    /* Convert LIR into machine code. */
1022    AssembleLIR();
1023
1024    if (cu_->verbose) {
1025      CodegenDump();
1026    }
1027  }
1028}
1029
1030CompiledMethod* Mir2Lir::GetCompiledMethod() {
1031  // Combine vmap tables - core regs, then fp regs - into vmap_table
1032  std::vector<uint16_t> raw_vmap_table;
1033  // Core regs may have been inserted out of order - sort first
1034  std::sort(core_vmap_table_.begin(), core_vmap_table_.end());
1035  for (size_t i = 0 ; i < core_vmap_table_.size(); ++i) {
1036    // Copy, stripping out the phys register sort key
1037    raw_vmap_table.push_back(~(-1 << VREG_NUM_WIDTH) & core_vmap_table_[i]);
1038  }
1039  // If we have a frame, push a marker to take place of lr
1040  if (frame_size_ > 0) {
1041    raw_vmap_table.push_back(INVALID_VREG);
1042  } else {
1043    DCHECK_EQ(__builtin_popcount(core_spill_mask_), 0);
1044    DCHECK_EQ(__builtin_popcount(fp_spill_mask_), 0);
1045  }
1046  // Combine vmap tables - core regs, then fp regs. fp regs already sorted
1047  for (uint32_t i = 0; i < fp_vmap_table_.size(); i++) {
1048    raw_vmap_table.push_back(fp_vmap_table_[i]);
1049  }
1050  Leb128EncodingVector vmap_encoder;
1051  // Prefix the encoded data with its size.
1052  vmap_encoder.PushBackUnsigned(raw_vmap_table.size());
1053  for (uint16_t cur : raw_vmap_table) {
1054    vmap_encoder.PushBackUnsigned(cur);
1055  }
1056  CompiledMethod* result =
1057      new CompiledMethod(*cu_->compiler_driver, cu_->instruction_set, code_buffer_, frame_size_,
1058                         core_spill_mask_, fp_spill_mask_, encoded_mapping_table_,
1059                         vmap_encoder.GetData(), native_gc_map_);
1060  return result;
1061}
1062
1063int Mir2Lir::ComputeFrameSize() {
1064  /* Figure out the frame size */
1065  static const uint32_t kAlignMask = kStackAlignment - 1;
1066  uint32_t size = (num_core_spills_ + num_fp_spills_ +
1067                   1 /* filler word */ + cu_->num_regs + cu_->num_outs +
1068                   cu_->num_compiler_temps + 1 /* cur_method* */)
1069                   * sizeof(uint32_t);
1070  /* Align and set */
1071  return (size + kAlignMask) & ~(kAlignMask);
1072}
1073
1074/*
1075 * Append an LIR instruction to the LIR list maintained by a compilation
1076 * unit
1077 */
1078void Mir2Lir::AppendLIR(LIR* lir) {
1079  if (first_lir_insn_ == NULL) {
1080    DCHECK(last_lir_insn_ == NULL);
1081    last_lir_insn_ = first_lir_insn_ = lir;
1082    lir->prev = lir->next = NULL;
1083  } else {
1084    last_lir_insn_->next = lir;
1085    lir->prev = last_lir_insn_;
1086    lir->next = NULL;
1087    last_lir_insn_ = lir;
1088  }
1089}
1090
1091/*
1092 * Insert an LIR instruction before the current instruction, which cannot be the
1093 * first instruction.
1094 *
1095 * prev_lir <-> new_lir <-> current_lir
1096 */
1097void Mir2Lir::InsertLIRBefore(LIR* current_lir, LIR* new_lir) {
1098  DCHECK(current_lir->prev != NULL);
1099  LIR *prev_lir = current_lir->prev;
1100
1101  prev_lir->next = new_lir;
1102  new_lir->prev = prev_lir;
1103  new_lir->next = current_lir;
1104  current_lir->prev = new_lir;
1105}
1106
1107/*
1108 * Insert an LIR instruction after the current instruction, which cannot be the
1109 * first instruction.
1110 *
1111 * current_lir -> new_lir -> old_next
1112 */
1113void Mir2Lir::InsertLIRAfter(LIR* current_lir, LIR* new_lir) {
1114  new_lir->prev = current_lir;
1115  new_lir->next = current_lir->next;
1116  current_lir->next = new_lir;
1117  new_lir->next->prev = new_lir;
1118}
1119
1120}  // namespace art
1121