builder.cc revision 317f9cebedc0117ce89931a1f28a82e989057c31
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 "builder.h"
18
19#include "art_field-inl.h"
20#include "base/logging.h"
21#include "class_linker.h"
22#include "dex/verified_method.h"
23#include "dex_file-inl.h"
24#include "dex_instruction-inl.h"
25#include "dex/verified_method.h"
26#include "driver/compiler_driver-inl.h"
27#include "driver/compiler_options.h"
28#include "mirror/class_loader.h"
29#include "mirror/dex_cache.h"
30#include "nodes.h"
31#include "primitive.h"
32#include "scoped_thread_state_change.h"
33#include "thread.h"
34#include "utils/dex_cache_arrays_layout-inl.h"
35
36namespace art {
37
38/**
39 * Helper class to add HTemporary instructions. This class is used when
40 * converting a DEX instruction to multiple HInstruction, and where those
41 * instructions do not die at the following instruction, but instead spans
42 * multiple instructions.
43 */
44class Temporaries : public ValueObject {
45 public:
46  explicit Temporaries(HGraph* graph) : graph_(graph), index_(0) {}
47
48  void Add(HInstruction* instruction) {
49    HInstruction* temp = new (graph_->GetArena()) HTemporary(index_, instruction->GetDexPc());
50    instruction->GetBlock()->AddInstruction(temp);
51
52    DCHECK(temp->GetPrevious() == instruction);
53
54    size_t offset;
55    if (instruction->GetType() == Primitive::kPrimLong
56        || instruction->GetType() == Primitive::kPrimDouble) {
57      offset = 2;
58    } else {
59      offset = 1;
60    }
61    index_ += offset;
62
63    graph_->UpdateTemporariesVRegSlots(index_);
64  }
65
66 private:
67  HGraph* const graph_;
68
69  // Current index in the temporary stack, updated by `Add`.
70  size_t index_;
71};
72
73class SwitchTable : public ValueObject {
74 public:
75  SwitchTable(const Instruction& instruction, uint32_t dex_pc, bool sparse)
76      : instruction_(instruction), dex_pc_(dex_pc), sparse_(sparse) {
77    int32_t table_offset = instruction.VRegB_31t();
78    const uint16_t* table = reinterpret_cast<const uint16_t*>(&instruction) + table_offset;
79    if (sparse) {
80      CHECK_EQ(table[0], static_cast<uint16_t>(Instruction::kSparseSwitchSignature));
81    } else {
82      CHECK_EQ(table[0], static_cast<uint16_t>(Instruction::kPackedSwitchSignature));
83    }
84    num_entries_ = table[1];
85    values_ = reinterpret_cast<const int32_t*>(&table[2]);
86  }
87
88  uint16_t GetNumEntries() const {
89    return num_entries_;
90  }
91
92  void CheckIndex(size_t index) const {
93    if (sparse_) {
94      // In a sparse table, we have num_entries_ keys and num_entries_ values, in that order.
95      DCHECK_LT(index, 2 * static_cast<size_t>(num_entries_));
96    } else {
97      // In a packed table, we have the starting key and num_entries_ values.
98      DCHECK_LT(index, 1 + static_cast<size_t>(num_entries_));
99    }
100  }
101
102  int32_t GetEntryAt(size_t index) const {
103    CheckIndex(index);
104    return values_[index];
105  }
106
107  uint32_t GetDexPcForIndex(size_t index) const {
108    CheckIndex(index);
109    return dex_pc_ +
110        (reinterpret_cast<const int16_t*>(values_ + index) -
111         reinterpret_cast<const int16_t*>(&instruction_));
112  }
113
114  // Index of the first value in the table.
115  size_t GetFirstValueIndex() const {
116    if (sparse_) {
117      // In a sparse table, we have num_entries_ keys and num_entries_ values, in that order.
118      return num_entries_;
119    } else {
120      // In a packed table, we have the starting key and num_entries_ values.
121      return 1;
122    }
123  }
124
125 private:
126  const Instruction& instruction_;
127  const uint32_t dex_pc_;
128
129  // Whether this is a sparse-switch table (or a packed-switch one).
130  const bool sparse_;
131
132  // This can't be const as it needs to be computed off of the given instruction, and complicated
133  // expressions in the initializer list seemed very ugly.
134  uint16_t num_entries_;
135
136  const int32_t* values_;
137
138  DISALLOW_COPY_AND_ASSIGN(SwitchTable);
139};
140
141void HGraphBuilder::InitializeLocals(uint16_t count) {
142  graph_->SetNumberOfVRegs(count);
143  locals_.resize(count);
144  for (int i = 0; i < count; i++) {
145    HLocal* local = new (arena_) HLocal(i);
146    entry_block_->AddInstruction(local);
147    locals_[i] = local;
148  }
149}
150
151void HGraphBuilder::InitializeParameters(uint16_t number_of_parameters) {
152  // dex_compilation_unit_ is null only when unit testing.
153  if (dex_compilation_unit_ == nullptr) {
154    return;
155  }
156
157  graph_->SetNumberOfInVRegs(number_of_parameters);
158  const char* shorty = dex_compilation_unit_->GetShorty();
159  int locals_index = locals_.size() - number_of_parameters;
160  int parameter_index = 0;
161
162  const DexFile::MethodId& referrer_method_id =
163      dex_file_->GetMethodId(dex_compilation_unit_->GetDexMethodIndex());
164  if (!dex_compilation_unit_->IsStatic()) {
165    // Add the implicit 'this' argument, not expressed in the signature.
166    HParameterValue* parameter = new (arena_) HParameterValue(*dex_file_,
167                                                              referrer_method_id.class_idx_,
168                                                              parameter_index++,
169                                                              Primitive::kPrimNot,
170                                                              true);
171    entry_block_->AddInstruction(parameter);
172    HLocal* local = GetLocalAt(locals_index++);
173    entry_block_->AddInstruction(new (arena_) HStoreLocal(local, parameter, local->GetDexPc()));
174    number_of_parameters--;
175  }
176
177  const DexFile::ProtoId& proto = dex_file_->GetMethodPrototype(referrer_method_id);
178  const DexFile::TypeList* arg_types = dex_file_->GetProtoParameters(proto);
179  for (int i = 0, shorty_pos = 1; i < number_of_parameters; i++) {
180    HParameterValue* parameter = new (arena_) HParameterValue(
181        *dex_file_,
182        arg_types->GetTypeItem(shorty_pos - 1).type_idx_,
183        parameter_index++,
184        Primitive::GetType(shorty[shorty_pos]),
185        false);
186    ++shorty_pos;
187    entry_block_->AddInstruction(parameter);
188    HLocal* local = GetLocalAt(locals_index++);
189    // Store the parameter value in the local that the dex code will use
190    // to reference that parameter.
191    entry_block_->AddInstruction(new (arena_) HStoreLocal(local, parameter, local->GetDexPc()));
192    bool is_wide = (parameter->GetType() == Primitive::kPrimLong)
193        || (parameter->GetType() == Primitive::kPrimDouble);
194    if (is_wide) {
195      i++;
196      locals_index++;
197      parameter_index++;
198    }
199  }
200}
201
202template<typename T>
203void HGraphBuilder::If_22t(const Instruction& instruction, uint32_t dex_pc) {
204  int32_t target_offset = instruction.GetTargetOffset();
205  HBasicBlock* branch_target = FindBlockStartingAt(dex_pc + target_offset);
206  HBasicBlock* fallthrough_target = FindBlockStartingAt(dex_pc + instruction.SizeInCodeUnits());
207  DCHECK(branch_target != nullptr);
208  DCHECK(fallthrough_target != nullptr);
209  PotentiallyAddSuspendCheck(branch_target, dex_pc);
210  HInstruction* first = LoadLocal(instruction.VRegA(), Primitive::kPrimInt, dex_pc);
211  HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt, dex_pc);
212  T* comparison = new (arena_) T(first, second, dex_pc);
213  current_block_->AddInstruction(comparison);
214  HInstruction* ifinst = new (arena_) HIf(comparison, dex_pc);
215  current_block_->AddInstruction(ifinst);
216  current_block_->AddSuccessor(branch_target);
217  current_block_->AddSuccessor(fallthrough_target);
218  current_block_ = nullptr;
219}
220
221template<typename T>
222void HGraphBuilder::If_21t(const Instruction& instruction, uint32_t dex_pc) {
223  int32_t target_offset = instruction.GetTargetOffset();
224  HBasicBlock* branch_target = FindBlockStartingAt(dex_pc + target_offset);
225  HBasicBlock* fallthrough_target = FindBlockStartingAt(dex_pc + instruction.SizeInCodeUnits());
226  DCHECK(branch_target != nullptr);
227  DCHECK(fallthrough_target != nullptr);
228  PotentiallyAddSuspendCheck(branch_target, dex_pc);
229  HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt, dex_pc);
230  T* comparison = new (arena_) T(value, graph_->GetIntConstant(0, dex_pc), dex_pc);
231  current_block_->AddInstruction(comparison);
232  HInstruction* ifinst = new (arena_) HIf(comparison, dex_pc);
233  current_block_->AddInstruction(ifinst);
234  current_block_->AddSuccessor(branch_target);
235  current_block_->AddSuccessor(fallthrough_target);
236  current_block_ = nullptr;
237}
238
239void HGraphBuilder::MaybeRecordStat(MethodCompilationStat compilation_stat) {
240  if (compilation_stats_ != nullptr) {
241    compilation_stats_->RecordStat(compilation_stat);
242  }
243}
244
245bool HGraphBuilder::SkipCompilation(const DexFile::CodeItem& code_item,
246                                    size_t number_of_branches) {
247  const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
248  CompilerOptions::CompilerFilter compiler_filter = compiler_options.GetCompilerFilter();
249  if (compiler_filter == CompilerOptions::kEverything) {
250    return false;
251  }
252
253  if (compiler_options.IsHugeMethod(code_item.insns_size_in_code_units_)) {
254    VLOG(compiler) << "Skip compilation of huge method "
255                   << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
256                   << ": " << code_item.insns_size_in_code_units_ << " code units";
257    MaybeRecordStat(MethodCompilationStat::kNotCompiledHugeMethod);
258    return true;
259  }
260
261  // If it's large and contains no branches, it's likely to be machine generated initialization.
262  if (compiler_options.IsLargeMethod(code_item.insns_size_in_code_units_)
263      && (number_of_branches == 0)) {
264    VLOG(compiler) << "Skip compilation of large method with no branch "
265                   << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
266                   << ": " << code_item.insns_size_in_code_units_ << " code units";
267    MaybeRecordStat(MethodCompilationStat::kNotCompiledLargeMethodNoBranches);
268    return true;
269  }
270
271  return false;
272}
273
274void HGraphBuilder::CreateBlocksForTryCatch(const DexFile::CodeItem& code_item) {
275  if (code_item.tries_size_ == 0) {
276    return;
277  }
278
279  // Create branch targets at the start/end of the TryItem range. These are
280  // places where the program might fall through into/out of the a block and
281  // where TryBoundary instructions will be inserted later. Other edges which
282  // enter/exit the try blocks are a result of branches/switches.
283  for (size_t idx = 0; idx < code_item.tries_size_; ++idx) {
284    const DexFile::TryItem* try_item = DexFile::GetTryItems(code_item, idx);
285    uint32_t dex_pc_start = try_item->start_addr_;
286    uint32_t dex_pc_end = dex_pc_start + try_item->insn_count_;
287    FindOrCreateBlockStartingAt(dex_pc_start);
288    if (dex_pc_end < code_item.insns_size_in_code_units_) {
289      // TODO: Do not create block if the last instruction cannot fall through.
290      FindOrCreateBlockStartingAt(dex_pc_end);
291    } else {
292      // The TryItem spans until the very end of the CodeItem (or beyond if
293      // invalid) and therefore cannot have any code afterwards.
294    }
295  }
296
297  // Create branch targets for exception handlers.
298  const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(code_item, 0);
299  uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
300  for (uint32_t idx = 0; idx < handlers_size; ++idx) {
301    CatchHandlerIterator iterator(handlers_ptr);
302    for (; iterator.HasNext(); iterator.Next()) {
303      uint32_t address = iterator.GetHandlerAddress();
304      HBasicBlock* block = FindOrCreateBlockStartingAt(address);
305      block->SetTryCatchInformation(
306        new (arena_) TryCatchInformation(iterator.GetHandlerTypeIndex(), *dex_file_));
307    }
308    handlers_ptr = iterator.EndDataPointer();
309  }
310}
311
312// Returns the TryItem stored for `block` or nullptr if there is no info for it.
313static const DexFile::TryItem* GetTryItem(
314    HBasicBlock* block,
315    const ArenaSafeMap<uint32_t, const DexFile::TryItem*>& try_block_info) {
316  auto iterator = try_block_info.find(block->GetBlockId());
317  return (iterator == try_block_info.end()) ? nullptr : iterator->second;
318}
319
320void HGraphBuilder::LinkToCatchBlocks(HTryBoundary* try_boundary,
321                                      const DexFile::CodeItem& code_item,
322                                      const DexFile::TryItem* try_item) {
323  for (CatchHandlerIterator it(code_item, *try_item); it.HasNext(); it.Next()) {
324    try_boundary->AddExceptionHandler(FindBlockStartingAt(it.GetHandlerAddress()));
325  }
326}
327
328void HGraphBuilder::InsertTryBoundaryBlocks(const DexFile::CodeItem& code_item) {
329  if (code_item.tries_size_ == 0) {
330    return;
331  }
332
333  // Keep a map of all try blocks and their respective TryItems. We do not use
334  // the block's pointer but rather its id to ensure deterministic iteration.
335  ArenaSafeMap<uint32_t, const DexFile::TryItem*> try_block_info(
336      std::less<uint32_t>(), arena_->Adapter(kArenaAllocGraphBuilder));
337
338  // Obtain TryItem information for blocks with throwing instructions, and split
339  // blocks which are both try & catch to simplify the graph.
340  // NOTE: We are appending new blocks inside the loop, so we need to use index
341  // because iterators can be invalidated. We remember the initial size to avoid
342  // iterating over the new blocks which cannot throw.
343  for (size_t i = 0, e = graph_->GetBlocks().size(); i < e; ++i) {
344    HBasicBlock* block = graph_->GetBlocks()[i];
345
346    // Do not bother creating exceptional edges for try blocks which have no
347    // throwing instructions. In that case we simply assume that the block is
348    // not covered by a TryItem. This prevents us from creating a throw-catch
349    // loop for synchronized blocks.
350    if (block->HasThrowingInstructions()) {
351      // Try to find a TryItem covering the block.
352      DCHECK_NE(block->GetDexPc(), kNoDexPc) << "Block must have a dec_pc to find its TryItem.";
353      const int32_t try_item_idx = DexFile::FindTryItem(code_item, block->GetDexPc());
354      if (try_item_idx != -1) {
355        // Block throwing and in a TryItem. Store the try block information.
356        HBasicBlock* throwing_block = block;
357        if (block->IsCatchBlock()) {
358          // Simplify blocks which are both try and catch, otherwise we would
359          // need a strategy for splitting exceptional edges. We split the block
360          // after the move-exception (if present) and mark the first part not
361          // throwing. The normal-flow edge between them will be split later.
362          throwing_block = block->SplitCatchBlockAfterMoveException();
363          // Move-exception does not throw and the block has throwing insructions
364          // so it must have been possible to split it.
365          DCHECK(throwing_block != nullptr);
366        }
367
368        try_block_info.Put(throwing_block->GetBlockId(),
369                           DexFile::GetTryItems(code_item, try_item_idx));
370      }
371    }
372  }
373
374  // Do a pass over the try blocks and insert entering TryBoundaries where at
375  // least one predecessor is not covered by the same TryItem as the try block.
376  // We do not split each edge separately, but rather create one boundary block
377  // that all predecessors are relinked to. This preserves loop headers (b/23895756).
378  for (auto entry : try_block_info) {
379    HBasicBlock* try_block = graph_->GetBlocks()[entry.first];
380    for (HBasicBlock* predecessor : try_block->GetPredecessors()) {
381      if (GetTryItem(predecessor, try_block_info) != entry.second) {
382        // Found a predecessor not covered by the same TryItem. Insert entering
383        // boundary block.
384        HTryBoundary* try_entry =
385            new (arena_) HTryBoundary(HTryBoundary::kEntry, try_block->GetDexPc());
386        try_block->CreateImmediateDominator()->AddInstruction(try_entry);
387        LinkToCatchBlocks(try_entry, code_item, entry.second);
388        break;
389      }
390    }
391  }
392
393  // Do a second pass over the try blocks and insert exit TryBoundaries where
394  // the successor is not in the same TryItem.
395  for (auto entry : try_block_info) {
396    HBasicBlock* try_block = graph_->GetBlocks()[entry.first];
397    // NOTE: Do not use iterators because SplitEdge would invalidate them.
398    for (size_t i = 0, e = try_block->GetSuccessors().size(); i < e; ++i) {
399      HBasicBlock* successor = try_block->GetSuccessors()[i];
400
401      // If the successor is a try block, all of its predecessors must be
402      // covered by the same TryItem. Otherwise the previous pass would have
403      // created a non-throwing boundary block.
404      if (GetTryItem(successor, try_block_info) != nullptr) {
405        DCHECK_EQ(entry.second, GetTryItem(successor, try_block_info));
406        continue;
407      }
408
409      // Preserve the invariant that Return(Void) always jumps to Exit by moving
410      // it outside the try block if necessary.
411      HInstruction* last_instruction = try_block->GetLastInstruction();
412      if (last_instruction->IsReturn() || last_instruction->IsReturnVoid()) {
413        DCHECK_EQ(successor, exit_block_);
414        successor = try_block->SplitBefore(last_instruction);
415      }
416
417      // Insert TryBoundary and link to catch blocks.
418      HTryBoundary* try_exit =
419          new (arena_) HTryBoundary(HTryBoundary::kExit, successor->GetDexPc());
420      graph_->SplitEdge(try_block, successor)->AddInstruction(try_exit);
421      LinkToCatchBlocks(try_exit, code_item, entry.second);
422    }
423  }
424}
425
426bool HGraphBuilder::BuildGraph(const DexFile::CodeItem& code_item) {
427  DCHECK(graph_->GetBlocks().empty());
428
429  const uint16_t* code_ptr = code_item.insns_;
430  const uint16_t* code_end = code_item.insns_ + code_item.insns_size_in_code_units_;
431  code_start_ = code_ptr;
432
433  // Setup the graph with the entry block and exit block.
434  entry_block_ = new (arena_) HBasicBlock(graph_, 0);
435  graph_->AddBlock(entry_block_);
436  exit_block_ = new (arena_) HBasicBlock(graph_, kNoDexPc);
437  graph_->SetEntryBlock(entry_block_);
438  graph_->SetExitBlock(exit_block_);
439
440  graph_->SetHasTryCatch(code_item.tries_size_ != 0);
441
442  InitializeLocals(code_item.registers_size_);
443  graph_->SetMaximumNumberOfOutVRegs(code_item.outs_size_);
444
445  // Compute the number of dex instructions, blocks, and branches. We will
446  // check these values against limits given to the compiler.
447  size_t number_of_branches = 0;
448
449  // To avoid splitting blocks, we compute ahead of time the instructions that
450  // start a new block, and create these blocks.
451  if (!ComputeBranchTargets(code_ptr, code_end, &number_of_branches)) {
452    MaybeRecordStat(MethodCompilationStat::kNotCompiledBranchOutsideMethodCode);
453    return false;
454  }
455
456  // Note that the compiler driver is null when unit testing.
457  if ((compiler_driver_ != nullptr) && SkipCompilation(code_item, number_of_branches)) {
458    return false;
459  }
460
461  CreateBlocksForTryCatch(code_item);
462
463  InitializeParameters(code_item.ins_size_);
464
465  size_t dex_pc = 0;
466  while (code_ptr < code_end) {
467    // Update the current block if dex_pc starts a new block.
468    MaybeUpdateCurrentBlock(dex_pc);
469    const Instruction& instruction = *Instruction::At(code_ptr);
470    if (!AnalyzeDexInstruction(instruction, dex_pc)) {
471      return false;
472    }
473    dex_pc += instruction.SizeInCodeUnits();
474    code_ptr += instruction.SizeInCodeUnits();
475  }
476
477  // Add Exit to the exit block.
478  exit_block_->AddInstruction(new (arena_) HExit());
479  // Add the suspend check to the entry block.
480  entry_block_->AddInstruction(new (arena_) HSuspendCheck(0));
481  entry_block_->AddInstruction(new (arena_) HGoto());
482  // Add the exit block at the end.
483  graph_->AddBlock(exit_block_);
484
485  // Iterate over blocks covered by TryItems and insert TryBoundaries at entry
486  // and exit points. This requires all control-flow instructions and
487  // non-exceptional edges to have been created.
488  InsertTryBoundaryBlocks(code_item);
489
490  return true;
491}
492
493void HGraphBuilder::MaybeUpdateCurrentBlock(size_t dex_pc) {
494  HBasicBlock* block = FindBlockStartingAt(dex_pc);
495  if (block == nullptr) {
496    return;
497  }
498
499  if (current_block_ != nullptr) {
500    // Branching instructions clear current_block, so we know
501    // the last instruction of the current block is not a branching
502    // instruction. We add an unconditional goto to the found block.
503    current_block_->AddInstruction(new (arena_) HGoto(dex_pc));
504    current_block_->AddSuccessor(block);
505  }
506  graph_->AddBlock(block);
507  current_block_ = block;
508}
509
510bool HGraphBuilder::ComputeBranchTargets(const uint16_t* code_ptr,
511                                         const uint16_t* code_end,
512                                         size_t* number_of_branches) {
513  branch_targets_.resize(code_end - code_ptr, nullptr);
514
515  // Create the first block for the dex instructions, single successor of the entry block.
516  HBasicBlock* block = new (arena_) HBasicBlock(graph_, 0);
517  branch_targets_[0] = block;
518  entry_block_->AddSuccessor(block);
519
520  // Iterate over all instructions and find branching instructions. Create blocks for
521  // the locations these instructions branch to.
522  uint32_t dex_pc = 0;
523  while (code_ptr < code_end) {
524    const Instruction& instruction = *Instruction::At(code_ptr);
525    if (instruction.IsBranch()) {
526      (*number_of_branches)++;
527      int32_t target = instruction.GetTargetOffset() + dex_pc;
528      // Create a block for the target instruction.
529      FindOrCreateBlockStartingAt(target);
530
531      dex_pc += instruction.SizeInCodeUnits();
532      code_ptr += instruction.SizeInCodeUnits();
533
534      if (instruction.CanFlowThrough()) {
535        if (code_ptr >= code_end) {
536          // In the normal case we should never hit this but someone can artificially forge a dex
537          // file to fall-through out the method code. In this case we bail out compilation.
538          return false;
539        } else {
540          FindOrCreateBlockStartingAt(dex_pc);
541        }
542      }
543    } else if (instruction.IsSwitch()) {
544      SwitchTable table(instruction, dex_pc, instruction.Opcode() == Instruction::SPARSE_SWITCH);
545
546      uint16_t num_entries = table.GetNumEntries();
547
548      // In a packed-switch, the entry at index 0 is the starting key. In a sparse-switch, the
549      // entry at index 0 is the first key, and values are after *all* keys.
550      size_t offset = table.GetFirstValueIndex();
551
552      // Use a larger loop counter type to avoid overflow issues.
553      for (size_t i = 0; i < num_entries; ++i) {
554        // The target of the case.
555        uint32_t target = dex_pc + table.GetEntryAt(i + offset);
556        FindOrCreateBlockStartingAt(target);
557
558        // Create a block for the switch-case logic. The block gets the dex_pc
559        // of the SWITCH instruction because it is part of its semantics.
560        block = new (arena_) HBasicBlock(graph_, dex_pc);
561        branch_targets_[table.GetDexPcForIndex(i)] = block;
562      }
563
564      // Fall-through. Add a block if there is more code afterwards.
565      dex_pc += instruction.SizeInCodeUnits();
566      code_ptr += instruction.SizeInCodeUnits();
567      if (code_ptr >= code_end) {
568        // In the normal case we should never hit this but someone can artificially forge a dex
569        // file to fall-through out the method code. In this case we bail out compilation.
570        // (A switch can fall-through so we don't need to check CanFlowThrough().)
571        return false;
572      } else {
573        FindOrCreateBlockStartingAt(dex_pc);
574      }
575    } else {
576      code_ptr += instruction.SizeInCodeUnits();
577      dex_pc += instruction.SizeInCodeUnits();
578    }
579  }
580  return true;
581}
582
583HBasicBlock* HGraphBuilder::FindBlockStartingAt(int32_t dex_pc) const {
584  DCHECK_GE(dex_pc, 0);
585  return branch_targets_[dex_pc];
586}
587
588HBasicBlock* HGraphBuilder::FindOrCreateBlockStartingAt(int32_t dex_pc) {
589  HBasicBlock* block = FindBlockStartingAt(dex_pc);
590  if (block == nullptr) {
591    block = new (arena_) HBasicBlock(graph_, dex_pc);
592    branch_targets_[dex_pc] = block;
593  }
594  return block;
595}
596
597template<typename T>
598void HGraphBuilder::Unop_12x(const Instruction& instruction,
599                             Primitive::Type type,
600                             uint32_t dex_pc) {
601  HInstruction* first = LoadLocal(instruction.VRegB(), type, dex_pc);
602  current_block_->AddInstruction(new (arena_) T(type, first, dex_pc));
603  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
604}
605
606void HGraphBuilder::Conversion_12x(const Instruction& instruction,
607                                   Primitive::Type input_type,
608                                   Primitive::Type result_type,
609                                   uint32_t dex_pc) {
610  HInstruction* first = LoadLocal(instruction.VRegB(), input_type, dex_pc);
611  current_block_->AddInstruction(new (arena_) HTypeConversion(result_type, first, dex_pc));
612  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
613}
614
615template<typename T>
616void HGraphBuilder::Binop_23x(const Instruction& instruction,
617                              Primitive::Type type,
618                              uint32_t dex_pc) {
619  HInstruction* first = LoadLocal(instruction.VRegB(), type, dex_pc);
620  HInstruction* second = LoadLocal(instruction.VRegC(), type, dex_pc);
621  current_block_->AddInstruction(new (arena_) T(type, first, second, dex_pc));
622  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
623}
624
625template<typename T>
626void HGraphBuilder::Binop_23x_shift(const Instruction& instruction,
627                                    Primitive::Type type,
628                                    uint32_t dex_pc) {
629  HInstruction* first = LoadLocal(instruction.VRegB(), type, dex_pc);
630  HInstruction* second = LoadLocal(instruction.VRegC(), Primitive::kPrimInt, dex_pc);
631  current_block_->AddInstruction(new (arena_) T(type, first, second, dex_pc));
632  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
633}
634
635void HGraphBuilder::Binop_23x_cmp(const Instruction& instruction,
636                                  Primitive::Type type,
637                                  ComparisonBias bias,
638                                  uint32_t dex_pc) {
639  HInstruction* first = LoadLocal(instruction.VRegB(), type, dex_pc);
640  HInstruction* second = LoadLocal(instruction.VRegC(), type, dex_pc);
641  current_block_->AddInstruction(new (arena_) HCompare(type, first, second, bias, dex_pc));
642  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
643}
644
645template<typename T>
646void HGraphBuilder::Binop_12x_shift(const Instruction& instruction, Primitive::Type type,
647                                    uint32_t dex_pc) {
648  HInstruction* first = LoadLocal(instruction.VRegA(), type, dex_pc);
649  HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt, dex_pc);
650  current_block_->AddInstruction(new (arena_) T(type, first, second, dex_pc));
651  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
652}
653
654template<typename T>
655void HGraphBuilder::Binop_12x(const Instruction& instruction,
656                              Primitive::Type type,
657                              uint32_t dex_pc) {
658  HInstruction* first = LoadLocal(instruction.VRegA(), type, dex_pc);
659  HInstruction* second = LoadLocal(instruction.VRegB(), type, dex_pc);
660  current_block_->AddInstruction(new (arena_) T(type, first, second, dex_pc));
661  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
662}
663
664template<typename T>
665void HGraphBuilder::Binop_22s(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
666  HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt, dex_pc);
667  HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22s(), dex_pc);
668  if (reverse) {
669    std::swap(first, second);
670  }
671  current_block_->AddInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
672  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
673}
674
675template<typename T>
676void HGraphBuilder::Binop_22b(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
677  HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt, dex_pc);
678  HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22b(), dex_pc);
679  if (reverse) {
680    std::swap(first, second);
681  }
682  current_block_->AddInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
683  UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
684}
685
686static bool RequiresConstructorBarrier(const DexCompilationUnit* cu, const CompilerDriver& driver) {
687  Thread* self = Thread::Current();
688  return cu->IsConstructor()
689      && driver.RequiresConstructorBarrier(self, cu->GetDexFile(), cu->GetClassDefIndex());
690}
691
692void HGraphBuilder::BuildReturn(const Instruction& instruction,
693                                Primitive::Type type,
694                                uint32_t dex_pc) {
695  if (type == Primitive::kPrimVoid) {
696    if (graph_->ShouldGenerateConstructorBarrier()) {
697      // The compilation unit is null during testing.
698      if (dex_compilation_unit_ != nullptr) {
699        DCHECK(RequiresConstructorBarrier(dex_compilation_unit_, *compiler_driver_))
700          << "Inconsistent use of ShouldGenerateConstructorBarrier. Should not generate a barrier.";
701      }
702      current_block_->AddInstruction(new (arena_) HMemoryBarrier(kStoreStore, dex_pc));
703    }
704    current_block_->AddInstruction(new (arena_) HReturnVoid(dex_pc));
705  } else {
706    HInstruction* value = LoadLocal(instruction.VRegA(), type, dex_pc);
707    current_block_->AddInstruction(new (arena_) HReturn(value, dex_pc));
708  }
709  current_block_->AddSuccessor(exit_block_);
710  current_block_ = nullptr;
711}
712
713static InvokeType GetInvokeTypeFromOpCode(Instruction::Code opcode) {
714  switch (opcode) {
715    case Instruction::INVOKE_STATIC:
716    case Instruction::INVOKE_STATIC_RANGE:
717      return kStatic;
718    case Instruction::INVOKE_DIRECT:
719    case Instruction::INVOKE_DIRECT_RANGE:
720      return kDirect;
721    case Instruction::INVOKE_VIRTUAL:
722    case Instruction::INVOKE_VIRTUAL_QUICK:
723    case Instruction::INVOKE_VIRTUAL_RANGE:
724    case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
725      return kVirtual;
726    case Instruction::INVOKE_INTERFACE:
727    case Instruction::INVOKE_INTERFACE_RANGE:
728      return kInterface;
729    case Instruction::INVOKE_SUPER_RANGE:
730    case Instruction::INVOKE_SUPER:
731      return kSuper;
732    default:
733      LOG(FATAL) << "Unexpected invoke opcode: " << opcode;
734      UNREACHABLE();
735  }
736}
737
738bool HGraphBuilder::BuildInvoke(const Instruction& instruction,
739                                uint32_t dex_pc,
740                                uint32_t method_idx,
741                                uint32_t number_of_vreg_arguments,
742                                bool is_range,
743                                uint32_t* args,
744                                uint32_t register_index) {
745  InvokeType original_invoke_type = GetInvokeTypeFromOpCode(instruction.Opcode());
746  InvokeType optimized_invoke_type = original_invoke_type;
747  const char* descriptor = dex_file_->GetMethodShorty(method_idx);
748  Primitive::Type return_type = Primitive::GetType(descriptor[0]);
749
750  // Remove the return type from the 'proto'.
751  size_t number_of_arguments = strlen(descriptor) - 1;
752  if (original_invoke_type != kStatic) {  // instance call
753    // One extra argument for 'this'.
754    number_of_arguments++;
755  }
756
757  MethodReference target_method(dex_file_, method_idx);
758  int32_t table_index = 0;
759  uintptr_t direct_code = 0;
760  uintptr_t direct_method = 0;
761
762  // Special handling for string init.
763  int32_t string_init_offset = 0;
764  bool is_string_init = compiler_driver_->IsStringInit(method_idx,
765                                                       dex_file_,
766                                                       &string_init_offset);
767  // Replace calls to String.<init> with StringFactory.
768  if (is_string_init) {
769    HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
770        HInvokeStaticOrDirect::MethodLoadKind::kStringInit,
771        HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
772        dchecked_integral_cast<uint64_t>(string_init_offset),
773        0U
774    };
775    HInvoke* invoke = new (arena_) HInvokeStaticOrDirect(
776        arena_,
777        number_of_arguments - 1,
778        Primitive::kPrimNot /*return_type */,
779        dex_pc,
780        method_idx,
781        target_method,
782        dispatch_info,
783        original_invoke_type,
784        kStatic /* optimized_invoke_type */,
785        HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit);
786    return HandleStringInit(invoke,
787                            number_of_vreg_arguments,
788                            args,
789                            register_index,
790                            is_range,
791                            descriptor);
792  }
793
794  // Handle unresolved methods.
795  if (!compiler_driver_->ComputeInvokeInfo(dex_compilation_unit_,
796                                           dex_pc,
797                                           true /* update_stats */,
798                                           true /* enable_devirtualization */,
799                                           &optimized_invoke_type,
800                                           &target_method,
801                                           &table_index,
802                                           &direct_code,
803                                           &direct_method)) {
804    MaybeRecordStat(MethodCompilationStat::kUnresolvedMethod);
805    HInvoke* invoke = new (arena_) HInvokeUnresolved(arena_,
806                                                     number_of_arguments,
807                                                     return_type,
808                                                     dex_pc,
809                                                     method_idx,
810                                                     original_invoke_type);
811    return HandleInvoke(invoke,
812                        number_of_vreg_arguments,
813                        args,
814                        register_index,
815                        is_range,
816                        descriptor,
817                        nullptr /* clinit_check */);
818  }
819
820  // Handle resolved methods (non string init).
821
822  DCHECK(optimized_invoke_type != kSuper);
823
824  // Potential class initialization check, in the case of a static method call.
825  HClinitCheck* clinit_check = nullptr;
826  HInvoke* invoke = nullptr;
827
828  if (optimized_invoke_type == kDirect || optimized_invoke_type == kStatic) {
829    // By default, consider that the called method implicitly requires
830    // an initialization check of its declaring method.
831    HInvokeStaticOrDirect::ClinitCheckRequirement clinit_check_requirement
832        = HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit;
833    if (optimized_invoke_type == kStatic) {
834      clinit_check = ProcessClinitCheckForInvoke(dex_pc, method_idx, &clinit_check_requirement);
835    }
836
837    HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
838        HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod,
839        HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
840        0u,
841        0U
842    };
843    invoke = new (arena_) HInvokeStaticOrDirect(arena_,
844                                                number_of_arguments,
845                                                return_type,
846                                                dex_pc,
847                                                method_idx,
848                                                target_method,
849                                                dispatch_info,
850                                                original_invoke_type,
851                                                optimized_invoke_type,
852                                                clinit_check_requirement);
853  } else if (optimized_invoke_type == kVirtual) {
854    invoke = new (arena_) HInvokeVirtual(arena_,
855                                         number_of_arguments,
856                                         return_type,
857                                         dex_pc,
858                                         method_idx,
859                                         table_index);
860  } else {
861    DCHECK_EQ(optimized_invoke_type, kInterface);
862    invoke = new (arena_) HInvokeInterface(arena_,
863                                           number_of_arguments,
864                                           return_type,
865                                           dex_pc,
866                                           method_idx,
867                                           table_index);
868  }
869
870  return HandleInvoke(invoke,
871                      number_of_vreg_arguments,
872                      args,
873                      register_index,
874                      is_range,
875                      descriptor,
876                      clinit_check);
877}
878
879bool HGraphBuilder::BuildNewInstance(uint16_t type_index, uint32_t dex_pc) {
880  bool finalizable;
881  bool can_throw = NeedsAccessCheck(type_index, &finalizable);
882
883  // Only the non-resolved entrypoint handles the finalizable class case. If we
884  // need access checks, then we haven't resolved the method and the class may
885  // again be finalizable.
886  QuickEntrypointEnum entrypoint = (finalizable || can_throw)
887      ? kQuickAllocObject
888      : kQuickAllocObjectInitialized;
889
890  ScopedObjectAccess soa(Thread::Current());
891  StackHandleScope<3> hs(soa.Self());
892  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
893      dex_compilation_unit_->GetClassLinker()->FindDexCache(
894          soa.Self(), *dex_compilation_unit_->GetDexFile())));
895  Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
896  const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
897  Handle<mirror::DexCache> outer_dex_cache(hs.NewHandle(
898      outer_compilation_unit_->GetClassLinker()->FindDexCache(soa.Self(), outer_dex_file)));
899
900  if (outer_dex_cache.Get() != dex_cache.Get()) {
901    // We currently do not support inlining allocations across dex files.
902    return false;
903  }
904
905  HLoadClass* load_class = new (arena_) HLoadClass(
906      graph_->GetCurrentMethod(),
907      type_index,
908      *dex_compilation_unit_->GetDexFile(),
909      IsOutermostCompilingClass(type_index),
910      dex_pc,
911      /*needs_access_check*/ can_throw);
912
913  current_block_->AddInstruction(load_class);
914  HInstruction* cls = load_class;
915  if (!IsInitialized(resolved_class, type_index)) {
916    cls = new (arena_) HClinitCheck(load_class, dex_pc);
917    current_block_->AddInstruction(cls);
918  }
919
920  current_block_->AddInstruction(new (arena_) HNewInstance(
921      cls,
922      graph_->GetCurrentMethod(),
923      dex_pc,
924      type_index,
925      *dex_compilation_unit_->GetDexFile(),
926      can_throw,
927      finalizable,
928      entrypoint));
929  return true;
930}
931
932bool HGraphBuilder::IsInitialized(Handle<mirror::Class> cls, uint16_t type_index) const {
933  if (cls.Get() == nullptr) {
934    return false;
935  }
936  if (GetOutermostCompilingClass() == cls.Get()) {
937    return true;
938  }
939  // TODO: find out why this check is needed.
940  bool is_in_dex_cache = compiler_driver_->CanAssumeTypeIsPresentInDexCache(
941      *outer_compilation_unit_->GetDexFile(), type_index);
942  return cls->IsInitialized() && is_in_dex_cache;
943}
944
945HClinitCheck* HGraphBuilder::ProcessClinitCheckForInvoke(
946      uint32_t dex_pc,
947      uint32_t method_idx,
948      HInvokeStaticOrDirect::ClinitCheckRequirement* clinit_check_requirement) {
949  ScopedObjectAccess soa(Thread::Current());
950  StackHandleScope<5> hs(soa.Self());
951  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
952      dex_compilation_unit_->GetClassLinker()->FindDexCache(
953          soa.Self(), *dex_compilation_unit_->GetDexFile())));
954  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
955      soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
956  ArtMethod* resolved_method = compiler_driver_->ResolveMethod(
957      soa, dex_cache, class_loader, dex_compilation_unit_, method_idx, InvokeType::kStatic);
958
959  DCHECK(resolved_method != nullptr);
960
961  const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
962  Handle<mirror::DexCache> outer_dex_cache(hs.NewHandle(
963      outer_compilation_unit_->GetClassLinker()->FindDexCache(soa.Self(), outer_dex_file)));
964  Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
965
966  // The index at which the method's class is stored in the DexCache's type array.
967  uint32_t storage_index = DexFile::kDexNoIndex;
968  bool is_outer_class = (resolved_method->GetDeclaringClass() == outer_class.Get());
969  if (is_outer_class) {
970    storage_index = outer_class->GetDexTypeIndex();
971  } else if (outer_dex_cache.Get() == dex_cache.Get()) {
972    // Get `storage_index` from IsClassOfStaticMethodAvailableToReferrer.
973    compiler_driver_->IsClassOfStaticMethodAvailableToReferrer(outer_dex_cache.Get(),
974                                                               GetCompilingClass(),
975                                                               resolved_method,
976                                                               method_idx,
977                                                               &storage_index);
978  }
979
980  HClinitCheck* clinit_check = nullptr;
981
982  if (!outer_class->IsInterface()
983      && outer_class->IsSubClass(resolved_method->GetDeclaringClass())) {
984    // If the outer class is the declaring class or a subclass
985    // of the declaring class, no class initialization is needed
986    // before the static method call.
987    // Note that in case of inlining, we do not need to add clinit checks
988    // to calls that satisfy this subclass check with any inlined methods. This
989    // will be detected by the optimization passes.
990    *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kNone;
991  } else if (storage_index != DexFile::kDexNoIndex) {
992    // If the method's class type index is available, check
993    // whether we should add an explicit class initialization
994    // check for its declaring class before the static method call.
995
996    Handle<mirror::Class> cls(hs.NewHandle(resolved_method->GetDeclaringClass()));
997    if (IsInitialized(cls, storage_index)) {
998      *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kNone;
999    } else {
1000      *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit;
1001      HLoadClass* load_class = new (arena_) HLoadClass(
1002          graph_->GetCurrentMethod(),
1003          storage_index,
1004          *dex_compilation_unit_->GetDexFile(),
1005          is_outer_class,
1006          dex_pc,
1007          /*needs_access_check*/ false);
1008      current_block_->AddInstruction(load_class);
1009      clinit_check = new (arena_) HClinitCheck(load_class, dex_pc);
1010      current_block_->AddInstruction(clinit_check);
1011    }
1012  }
1013  return clinit_check;
1014}
1015
1016bool HGraphBuilder::SetupInvokeArguments(HInvoke* invoke,
1017                                         uint32_t number_of_vreg_arguments,
1018                                         uint32_t* args,
1019                                         uint32_t register_index,
1020                                         bool is_range,
1021                                         const char* descriptor,
1022                                         size_t start_index,
1023                                         size_t* argument_index) {
1024  uint32_t descriptor_index = 1;  // Skip the return type.
1025  uint32_t dex_pc = invoke->GetDexPc();
1026
1027  for (size_t i = start_index;
1028       // Make sure we don't go over the expected arguments or over the number of
1029       // dex registers given. If the instruction was seen as dead by the verifier,
1030       // it hasn't been properly checked.
1031       (i < number_of_vreg_arguments) && (*argument_index < invoke->GetNumberOfArguments());
1032       i++, (*argument_index)++) {
1033    Primitive::Type type = Primitive::GetType(descriptor[descriptor_index++]);
1034    bool is_wide = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble);
1035    if (!is_range
1036        && is_wide
1037        && ((i + 1 == number_of_vreg_arguments) || (args[i] + 1 != args[i + 1]))) {
1038      // Longs and doubles should be in pairs, that is, sequential registers. The verifier should
1039      // reject any class where this is violated. However, the verifier only does these checks
1040      // on non trivially dead instructions, so we just bailout the compilation.
1041      VLOG(compiler) << "Did not compile "
1042                     << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1043                     << " because of non-sequential dex register pair in wide argument";
1044      MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1045      return false;
1046    }
1047    HInstruction* arg = LoadLocal(is_range ? register_index + i : args[i], type, dex_pc);
1048    invoke->SetArgumentAt(*argument_index, arg);
1049    if (is_wide) {
1050      i++;
1051    }
1052  }
1053
1054  if (*argument_index != invoke->GetNumberOfArguments()) {
1055    VLOG(compiler) << "Did not compile "
1056                   << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1057                   << " because of wrong number of arguments in invoke instruction";
1058    MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1059    return false;
1060  }
1061
1062  if (invoke->IsInvokeStaticOrDirect() &&
1063      HInvokeStaticOrDirect::NeedsCurrentMethodInput(
1064          invoke->AsInvokeStaticOrDirect()->GetMethodLoadKind())) {
1065    invoke->SetArgumentAt(*argument_index, graph_->GetCurrentMethod());
1066    (*argument_index)++;
1067  }
1068
1069  return true;
1070}
1071
1072bool HGraphBuilder::HandleInvoke(HInvoke* invoke,
1073                                 uint32_t number_of_vreg_arguments,
1074                                 uint32_t* args,
1075                                 uint32_t register_index,
1076                                 bool is_range,
1077                                 const char* descriptor,
1078                                 HClinitCheck* clinit_check) {
1079  DCHECK(!invoke->IsInvokeStaticOrDirect() || !invoke->AsInvokeStaticOrDirect()->IsStringInit());
1080
1081  size_t start_index = 0;
1082  size_t argument_index = 0;
1083  if (invoke->GetOriginalInvokeType() != InvokeType::kStatic) {  // Instance call.
1084    Temporaries temps(graph_);
1085    HInstruction* arg = LoadLocal(
1086        is_range ? register_index : args[0], Primitive::kPrimNot, invoke->GetDexPc());
1087    HNullCheck* null_check = new (arena_) HNullCheck(arg, invoke->GetDexPc());
1088    current_block_->AddInstruction(null_check);
1089    temps.Add(null_check);
1090    invoke->SetArgumentAt(0, null_check);
1091    start_index = 1;
1092    argument_index = 1;
1093  }
1094
1095  if (!SetupInvokeArguments(invoke,
1096                            number_of_vreg_arguments,
1097                            args,
1098                            register_index,
1099                            is_range,
1100                            descriptor,
1101                            start_index,
1102                            &argument_index)) {
1103    return false;
1104  }
1105
1106  if (clinit_check != nullptr) {
1107    // Add the class initialization check as last input of `invoke`.
1108    DCHECK(invoke->IsInvokeStaticOrDirect());
1109    DCHECK(invoke->AsInvokeStaticOrDirect()->GetClinitCheckRequirement()
1110        == HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit);
1111    invoke->SetArgumentAt(argument_index, clinit_check);
1112    argument_index++;
1113  }
1114
1115  current_block_->AddInstruction(invoke);
1116  latest_result_ = invoke;
1117
1118  return true;
1119}
1120
1121bool HGraphBuilder::HandleStringInit(HInvoke* invoke,
1122                                     uint32_t number_of_vreg_arguments,
1123                                     uint32_t* args,
1124                                     uint32_t register_index,
1125                                     bool is_range,
1126                                     const char* descriptor) {
1127  DCHECK(invoke->IsInvokeStaticOrDirect());
1128  DCHECK(invoke->AsInvokeStaticOrDirect()->IsStringInit());
1129
1130  size_t start_index = 1;
1131  size_t argument_index = 0;
1132  if (!SetupInvokeArguments(invoke,
1133                            number_of_vreg_arguments,
1134                            args,
1135                            register_index,
1136                            is_range,
1137                            descriptor,
1138                            start_index,
1139                            &argument_index)) {
1140    return false;
1141  }
1142
1143  // Add move-result for StringFactory method.
1144  uint32_t orig_this_reg = is_range ? register_index : args[0];
1145  HInstruction* fake_string = LoadLocal(orig_this_reg, Primitive::kPrimNot, invoke->GetDexPc());
1146  invoke->SetArgumentAt(argument_index, fake_string);
1147  current_block_->AddInstruction(invoke);
1148  PotentiallySimplifyFakeString(orig_this_reg, invoke->GetDexPc(), invoke);
1149
1150  latest_result_ = invoke;
1151
1152  return true;
1153}
1154
1155void HGraphBuilder::PotentiallySimplifyFakeString(uint16_t original_dex_register,
1156                                                  uint32_t dex_pc,
1157                                                  HInvoke* actual_string) {
1158  if (!graph_->IsDebuggable()) {
1159    // Notify that we cannot compile with baseline. The dex registers aliasing
1160    // with `original_dex_register` will be handled when we optimize
1161    // (see HInstructionSimplifer::VisitFakeString).
1162    can_use_baseline_for_string_init_ = false;
1163    return;
1164  }
1165  const VerifiedMethod* verified_method =
1166      compiler_driver_->GetVerifiedMethod(dex_file_, dex_compilation_unit_->GetDexMethodIndex());
1167  if (verified_method != nullptr) {
1168    UpdateLocal(original_dex_register, actual_string, dex_pc);
1169    const SafeMap<uint32_t, std::set<uint32_t>>& string_init_map =
1170        verified_method->GetStringInitPcRegMap();
1171    auto map_it = string_init_map.find(dex_pc);
1172    if (map_it != string_init_map.end()) {
1173      for (uint32_t reg : map_it->second) {
1174        HInstruction* load_local = LoadLocal(original_dex_register, Primitive::kPrimNot, dex_pc);
1175        UpdateLocal(reg, load_local, dex_pc);
1176      }
1177    }
1178  } else {
1179    can_use_baseline_for_string_init_ = false;
1180  }
1181}
1182
1183static Primitive::Type GetFieldAccessType(const DexFile& dex_file, uint16_t field_index) {
1184  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_index);
1185  const char* type = dex_file.GetFieldTypeDescriptor(field_id);
1186  return Primitive::GetType(type[0]);
1187}
1188
1189bool HGraphBuilder::BuildInstanceFieldAccess(const Instruction& instruction,
1190                                             uint32_t dex_pc,
1191                                             bool is_put) {
1192  uint32_t source_or_dest_reg = instruction.VRegA_22c();
1193  uint32_t obj_reg = instruction.VRegB_22c();
1194  uint16_t field_index;
1195  if (instruction.IsQuickened()) {
1196    if (!CanDecodeQuickenedInfo()) {
1197      return false;
1198    }
1199    field_index = LookupQuickenedInfo(dex_pc);
1200  } else {
1201    field_index = instruction.VRegC_22c();
1202  }
1203
1204  ScopedObjectAccess soa(Thread::Current());
1205  ArtField* resolved_field =
1206      compiler_driver_->ComputeInstanceFieldInfo(field_index, dex_compilation_unit_, is_put, soa);
1207
1208
1209  HInstruction* object = LoadLocal(obj_reg, Primitive::kPrimNot, dex_pc);
1210  HInstruction* null_check = new (arena_) HNullCheck(object, dex_pc);
1211  current_block_->AddInstruction(null_check);
1212
1213  Primitive::Type field_type = (resolved_field == nullptr)
1214      ? GetFieldAccessType(*dex_file_, field_index)
1215      : resolved_field->GetTypeAsPrimitiveType();
1216  if (is_put) {
1217    Temporaries temps(graph_);
1218    // We need one temporary for the null check.
1219    temps.Add(null_check);
1220    HInstruction* value = LoadLocal(source_or_dest_reg, field_type, dex_pc);
1221    HInstruction* field_set = nullptr;
1222    if (resolved_field == nullptr) {
1223      MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1224      field_set = new (arena_) HUnresolvedInstanceFieldSet(null_check,
1225                                                           value,
1226                                                           field_type,
1227                                                           field_index,
1228                                                           dex_pc);
1229    } else {
1230      uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
1231      field_set = new (arena_) HInstanceFieldSet(null_check,
1232                                                 value,
1233                                                 field_type,
1234                                                 resolved_field->GetOffset(),
1235                                                 resolved_field->IsVolatile(),
1236                                                 field_index,
1237                                                 class_def_index,
1238                                                 *dex_file_,
1239                                                 dex_compilation_unit_->GetDexCache(),
1240                                                 dex_pc);
1241    }
1242    current_block_->AddInstruction(field_set);
1243  } else {
1244    HInstruction* field_get = nullptr;
1245    if (resolved_field == nullptr) {
1246      MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1247      field_get = new (arena_) HUnresolvedInstanceFieldGet(null_check,
1248                                                           field_type,
1249                                                           field_index,
1250                                                           dex_pc);
1251    } else {
1252      uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
1253      field_get = new (arena_) HInstanceFieldGet(null_check,
1254                                                 field_type,
1255                                                 resolved_field->GetOffset(),
1256                                                 resolved_field->IsVolatile(),
1257                                                 field_index,
1258                                                 class_def_index,
1259                                                 *dex_file_,
1260                                                 dex_compilation_unit_->GetDexCache(),
1261                                                 dex_pc);
1262    }
1263    current_block_->AddInstruction(field_get);
1264    UpdateLocal(source_or_dest_reg, field_get, dex_pc);
1265  }
1266
1267  return true;
1268}
1269
1270static mirror::Class* GetClassFrom(CompilerDriver* driver,
1271                                   const DexCompilationUnit& compilation_unit) {
1272  ScopedObjectAccess soa(Thread::Current());
1273  StackHandleScope<2> hs(soa.Self());
1274  const DexFile& dex_file = *compilation_unit.GetDexFile();
1275  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1276      soa.Decode<mirror::ClassLoader*>(compilation_unit.GetClassLoader())));
1277  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
1278      compilation_unit.GetClassLinker()->FindDexCache(soa.Self(), dex_file)));
1279
1280  return driver->ResolveCompilingMethodsClass(soa, dex_cache, class_loader, &compilation_unit);
1281}
1282
1283mirror::Class* HGraphBuilder::GetOutermostCompilingClass() const {
1284  return GetClassFrom(compiler_driver_, *outer_compilation_unit_);
1285}
1286
1287mirror::Class* HGraphBuilder::GetCompilingClass() const {
1288  return GetClassFrom(compiler_driver_, *dex_compilation_unit_);
1289}
1290
1291bool HGraphBuilder::IsOutermostCompilingClass(uint16_t type_index) const {
1292  ScopedObjectAccess soa(Thread::Current());
1293  StackHandleScope<4> hs(soa.Self());
1294  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
1295      dex_compilation_unit_->GetClassLinker()->FindDexCache(
1296          soa.Self(), *dex_compilation_unit_->GetDexFile())));
1297  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1298      soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1299  Handle<mirror::Class> cls(hs.NewHandle(compiler_driver_->ResolveClass(
1300      soa, dex_cache, class_loader, type_index, dex_compilation_unit_)));
1301  Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1302
1303  // GetOutermostCompilingClass returns null when the class is unresolved
1304  // (e.g. if it derives from an unresolved class). This is bogus knowing that
1305  // we are compiling it.
1306  // When this happens we cannot establish a direct relation between the current
1307  // class and the outer class, so we return false.
1308  // (Note that this is only used for optimizing invokes and field accesses)
1309  return (cls.Get() != nullptr) && (outer_class.Get() == cls.Get());
1310}
1311
1312void HGraphBuilder::BuildUnresolvedStaticFieldAccess(const Instruction& instruction,
1313                                                     uint32_t dex_pc,
1314                                                     bool is_put,
1315                                                     Primitive::Type field_type) {
1316  uint32_t source_or_dest_reg = instruction.VRegA_21c();
1317  uint16_t field_index = instruction.VRegB_21c();
1318
1319  if (is_put) {
1320    HInstruction* value = LoadLocal(source_or_dest_reg, field_type, dex_pc);
1321    current_block_->AddInstruction(
1322        new (arena_) HUnresolvedStaticFieldSet(value, field_type, field_index, dex_pc));
1323  } else {
1324    current_block_->AddInstruction(
1325        new (arena_) HUnresolvedStaticFieldGet(field_type, field_index, dex_pc));
1326    UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction(), dex_pc);
1327  }
1328}
1329bool HGraphBuilder::BuildStaticFieldAccess(const Instruction& instruction,
1330                                           uint32_t dex_pc,
1331                                           bool is_put) {
1332  uint32_t source_or_dest_reg = instruction.VRegA_21c();
1333  uint16_t field_index = instruction.VRegB_21c();
1334
1335  ScopedObjectAccess soa(Thread::Current());
1336  StackHandleScope<5> hs(soa.Self());
1337  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
1338      dex_compilation_unit_->GetClassLinker()->FindDexCache(
1339          soa.Self(), *dex_compilation_unit_->GetDexFile())));
1340  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1341      soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1342  ArtField* resolved_field = compiler_driver_->ResolveField(
1343      soa, dex_cache, class_loader, dex_compilation_unit_, field_index, true);
1344
1345  if (resolved_field == nullptr) {
1346    MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1347    Primitive::Type field_type = GetFieldAccessType(*dex_file_, field_index);
1348    BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1349    return true;
1350  }
1351
1352  Primitive::Type field_type = resolved_field->GetTypeAsPrimitiveType();
1353  const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
1354  Handle<mirror::DexCache> outer_dex_cache(hs.NewHandle(
1355      outer_compilation_unit_->GetClassLinker()->FindDexCache(soa.Self(), outer_dex_file)));
1356  Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1357
1358  // The index at which the field's class is stored in the DexCache's type array.
1359  uint32_t storage_index;
1360  bool is_outer_class = (outer_class.Get() == resolved_field->GetDeclaringClass());
1361  if (is_outer_class) {
1362    storage_index = outer_class->GetDexTypeIndex();
1363  } else if (outer_dex_cache.Get() != dex_cache.Get()) {
1364    // The compiler driver cannot currently understand multiple dex caches involved. Just bailout.
1365    return false;
1366  } else {
1367    // TODO: This is rather expensive. Perf it and cache the results if needed.
1368    std::pair<bool, bool> pair = compiler_driver_->IsFastStaticField(
1369        outer_dex_cache.Get(),
1370        GetCompilingClass(),
1371        resolved_field,
1372        field_index,
1373        &storage_index);
1374    bool can_easily_access = is_put ? pair.second : pair.first;
1375    if (!can_easily_access) {
1376      MaybeRecordStat(MethodCompilationStat::kUnresolvedFieldNotAFastAccess);
1377      BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1378      return true;
1379    }
1380  }
1381
1382  HLoadClass* constant = new (arena_) HLoadClass(graph_->GetCurrentMethod(),
1383                                                 storage_index,
1384                                                 *dex_compilation_unit_->GetDexFile(),
1385                                                 is_outer_class,
1386                                                 dex_pc,
1387                                                 /*needs_access_check*/ false);
1388  current_block_->AddInstruction(constant);
1389
1390  HInstruction* cls = constant;
1391
1392  Handle<mirror::Class> klass(hs.NewHandle(resolved_field->GetDeclaringClass()));
1393  if (!IsInitialized(klass, storage_index)) {
1394    cls = new (arena_) HClinitCheck(constant, dex_pc);
1395    current_block_->AddInstruction(cls);
1396  }
1397
1398  uint16_t class_def_index = klass->GetDexClassDefIndex();
1399  if (is_put) {
1400    // We need to keep the class alive before loading the value.
1401    Temporaries temps(graph_);
1402    temps.Add(cls);
1403    HInstruction* value = LoadLocal(source_or_dest_reg, field_type, dex_pc);
1404    DCHECK_EQ(value->GetType(), field_type);
1405    current_block_->AddInstruction(new (arena_) HStaticFieldSet(cls,
1406                                                                value,
1407                                                                field_type,
1408                                                                resolved_field->GetOffset(),
1409                                                                resolved_field->IsVolatile(),
1410                                                                field_index,
1411                                                                class_def_index,
1412                                                                *dex_file_,
1413                                                                dex_cache_,
1414                                                                dex_pc));
1415  } else {
1416    current_block_->AddInstruction(new (arena_) HStaticFieldGet(cls,
1417                                                                field_type,
1418                                                                resolved_field->GetOffset(),
1419                                                                resolved_field->IsVolatile(),
1420                                                                field_index,
1421                                                                class_def_index,
1422                                                                *dex_file_,
1423                                                                dex_cache_,
1424                                                                dex_pc));
1425    UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction(), dex_pc);
1426  }
1427  return true;
1428}
1429
1430void HGraphBuilder::BuildCheckedDivRem(uint16_t out_vreg,
1431                                       uint16_t first_vreg,
1432                                       int64_t second_vreg_or_constant,
1433                                       uint32_t dex_pc,
1434                                       Primitive::Type type,
1435                                       bool second_is_constant,
1436                                       bool isDiv) {
1437  DCHECK(type == Primitive::kPrimInt || type == Primitive::kPrimLong);
1438
1439  HInstruction* first = LoadLocal(first_vreg, type, dex_pc);
1440  HInstruction* second = nullptr;
1441  if (second_is_constant) {
1442    if (type == Primitive::kPrimInt) {
1443      second = graph_->GetIntConstant(second_vreg_or_constant, dex_pc);
1444    } else {
1445      second = graph_->GetLongConstant(second_vreg_or_constant, dex_pc);
1446    }
1447  } else {
1448    second = LoadLocal(second_vreg_or_constant, type, dex_pc);
1449  }
1450
1451  if (!second_is_constant
1452      || (type == Primitive::kPrimInt && second->AsIntConstant()->GetValue() == 0)
1453      || (type == Primitive::kPrimLong && second->AsLongConstant()->GetValue() == 0)) {
1454    second = new (arena_) HDivZeroCheck(second, dex_pc);
1455    Temporaries temps(graph_);
1456    current_block_->AddInstruction(second);
1457    temps.Add(current_block_->GetLastInstruction());
1458  }
1459
1460  if (isDiv) {
1461    current_block_->AddInstruction(new (arena_) HDiv(type, first, second, dex_pc));
1462  } else {
1463    current_block_->AddInstruction(new (arena_) HRem(type, first, second, dex_pc));
1464  }
1465  UpdateLocal(out_vreg, current_block_->GetLastInstruction(), dex_pc);
1466}
1467
1468void HGraphBuilder::BuildArrayAccess(const Instruction& instruction,
1469                                     uint32_t dex_pc,
1470                                     bool is_put,
1471                                     Primitive::Type anticipated_type) {
1472  uint8_t source_or_dest_reg = instruction.VRegA_23x();
1473  uint8_t array_reg = instruction.VRegB_23x();
1474  uint8_t index_reg = instruction.VRegC_23x();
1475
1476  // We need one temporary for the null check, one for the index, and one for the length.
1477  Temporaries temps(graph_);
1478
1479  HInstruction* object = LoadLocal(array_reg, Primitive::kPrimNot, dex_pc);
1480  object = new (arena_) HNullCheck(object, dex_pc);
1481  current_block_->AddInstruction(object);
1482  temps.Add(object);
1483
1484  HInstruction* length = new (arena_) HArrayLength(object, dex_pc);
1485  current_block_->AddInstruction(length);
1486  temps.Add(length);
1487  HInstruction* index = LoadLocal(index_reg, Primitive::kPrimInt, dex_pc);
1488  index = new (arena_) HBoundsCheck(index, length, dex_pc);
1489  current_block_->AddInstruction(index);
1490  temps.Add(index);
1491  if (is_put) {
1492    HInstruction* value = LoadLocal(source_or_dest_reg, anticipated_type, dex_pc);
1493    // TODO: Insert a type check node if the type is Object.
1494    current_block_->AddInstruction(new (arena_) HArraySet(
1495        object, index, value, anticipated_type, dex_pc));
1496  } else {
1497    current_block_->AddInstruction(new (arena_) HArrayGet(object, index, anticipated_type, dex_pc));
1498    UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction(), dex_pc);
1499  }
1500  graph_->SetHasBoundsChecks(true);
1501}
1502
1503void HGraphBuilder::BuildFilledNewArray(uint32_t dex_pc,
1504                                        uint32_t type_index,
1505                                        uint32_t number_of_vreg_arguments,
1506                                        bool is_range,
1507                                        uint32_t* args,
1508                                        uint32_t register_index) {
1509  HInstruction* length = graph_->GetIntConstant(number_of_vreg_arguments, dex_pc);
1510  bool finalizable;
1511  QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
1512      ? kQuickAllocArrayWithAccessCheck
1513      : kQuickAllocArray;
1514  HInstruction* object = new (arena_) HNewArray(length,
1515                                                graph_->GetCurrentMethod(),
1516                                                dex_pc,
1517                                                type_index,
1518                                                *dex_compilation_unit_->GetDexFile(),
1519                                                entrypoint);
1520  current_block_->AddInstruction(object);
1521
1522  const char* descriptor = dex_file_->StringByTypeIdx(type_index);
1523  DCHECK_EQ(descriptor[0], '[') << descriptor;
1524  char primitive = descriptor[1];
1525  DCHECK(primitive == 'I'
1526      || primitive == 'L'
1527      || primitive == '[') << descriptor;
1528  bool is_reference_array = (primitive == 'L') || (primitive == '[');
1529  Primitive::Type type = is_reference_array ? Primitive::kPrimNot : Primitive::kPrimInt;
1530
1531  Temporaries temps(graph_);
1532  temps.Add(object);
1533  for (size_t i = 0; i < number_of_vreg_arguments; ++i) {
1534    HInstruction* value = LoadLocal(is_range ? register_index + i : args[i], type, dex_pc);
1535    HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1536    current_block_->AddInstruction(
1537        new (arena_) HArraySet(object, index, value, type, dex_pc));
1538  }
1539  latest_result_ = object;
1540}
1541
1542template <typename T>
1543void HGraphBuilder::BuildFillArrayData(HInstruction* object,
1544                                       const T* data,
1545                                       uint32_t element_count,
1546                                       Primitive::Type anticipated_type,
1547                                       uint32_t dex_pc) {
1548  for (uint32_t i = 0; i < element_count; ++i) {
1549    HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1550    HInstruction* value = graph_->GetIntConstant(data[i], dex_pc);
1551    current_block_->AddInstruction(new (arena_) HArraySet(
1552      object, index, value, anticipated_type, dex_pc));
1553  }
1554}
1555
1556void HGraphBuilder::BuildFillArrayData(const Instruction& instruction, uint32_t dex_pc) {
1557  Temporaries temps(graph_);
1558  HInstruction* array = LoadLocal(instruction.VRegA_31t(), Primitive::kPrimNot, dex_pc);
1559  HNullCheck* null_check = new (arena_) HNullCheck(array, dex_pc);
1560  current_block_->AddInstruction(null_check);
1561  temps.Add(null_check);
1562
1563  HInstruction* length = new (arena_) HArrayLength(null_check, dex_pc);
1564  current_block_->AddInstruction(length);
1565
1566  int32_t payload_offset = instruction.VRegB_31t() + dex_pc;
1567  const Instruction::ArrayDataPayload* payload =
1568      reinterpret_cast<const Instruction::ArrayDataPayload*>(code_start_ + payload_offset);
1569  const uint8_t* data = payload->data;
1570  uint32_t element_count = payload->element_count;
1571
1572  // Implementation of this DEX instruction seems to be that the bounds check is
1573  // done before doing any stores.
1574  HInstruction* last_index = graph_->GetIntConstant(payload->element_count - 1, dex_pc);
1575  current_block_->AddInstruction(new (arena_) HBoundsCheck(last_index, length, dex_pc));
1576
1577  switch (payload->element_width) {
1578    case 1:
1579      BuildFillArrayData(null_check,
1580                         reinterpret_cast<const int8_t*>(data),
1581                         element_count,
1582                         Primitive::kPrimByte,
1583                         dex_pc);
1584      break;
1585    case 2:
1586      BuildFillArrayData(null_check,
1587                         reinterpret_cast<const int16_t*>(data),
1588                         element_count,
1589                         Primitive::kPrimShort,
1590                         dex_pc);
1591      break;
1592    case 4:
1593      BuildFillArrayData(null_check,
1594                         reinterpret_cast<const int32_t*>(data),
1595                         element_count,
1596                         Primitive::kPrimInt,
1597                         dex_pc);
1598      break;
1599    case 8:
1600      BuildFillWideArrayData(null_check,
1601                             reinterpret_cast<const int64_t*>(data),
1602                             element_count,
1603                             dex_pc);
1604      break;
1605    default:
1606      LOG(FATAL) << "Unknown element width for " << payload->element_width;
1607  }
1608  graph_->SetHasBoundsChecks(true);
1609}
1610
1611void HGraphBuilder::BuildFillWideArrayData(HInstruction* object,
1612                                           const int64_t* data,
1613                                           uint32_t element_count,
1614                                           uint32_t dex_pc) {
1615  for (uint32_t i = 0; i < element_count; ++i) {
1616    HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1617    HInstruction* value = graph_->GetLongConstant(data[i], dex_pc);
1618    current_block_->AddInstruction(new (arena_) HArraySet(
1619      object, index, value, Primitive::kPrimLong, dex_pc));
1620  }
1621}
1622
1623static TypeCheckKind ComputeTypeCheckKind(Handle<mirror::Class> cls)
1624    SHARED_REQUIRES(Locks::mutator_lock_) {
1625  if (cls.Get() == nullptr) {
1626    return TypeCheckKind::kUnresolvedCheck;
1627  } else if (cls->IsInterface()) {
1628    return TypeCheckKind::kInterfaceCheck;
1629  } else if (cls->IsArrayClass()) {
1630    if (cls->GetComponentType()->IsObjectClass()) {
1631      return TypeCheckKind::kArrayObjectCheck;
1632    } else if (cls->CannotBeAssignedFromOtherTypes()) {
1633      return TypeCheckKind::kExactCheck;
1634    } else {
1635      return TypeCheckKind::kArrayCheck;
1636    }
1637  } else if (cls->IsFinal()) {
1638    return TypeCheckKind::kExactCheck;
1639  } else if (cls->IsAbstract()) {
1640    return TypeCheckKind::kAbstractClassCheck;
1641  } else {
1642    return TypeCheckKind::kClassHierarchyCheck;
1643  }
1644}
1645
1646void HGraphBuilder::BuildTypeCheck(const Instruction& instruction,
1647                                   uint8_t destination,
1648                                   uint8_t reference,
1649                                   uint16_t type_index,
1650                                   uint32_t dex_pc) {
1651  bool type_known_final, type_known_abstract, use_declaring_class;
1652  bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
1653      dex_compilation_unit_->GetDexMethodIndex(),
1654      *dex_compilation_unit_->GetDexFile(),
1655      type_index,
1656      &type_known_final,
1657      &type_known_abstract,
1658      &use_declaring_class);
1659
1660  ScopedObjectAccess soa(Thread::Current());
1661  StackHandleScope<2> hs(soa.Self());
1662  Handle<mirror::DexCache> dex_cache(hs.NewHandle(
1663      dex_compilation_unit_->GetClassLinker()->FindDexCache(
1664          soa.Self(), *dex_compilation_unit_->GetDexFile())));
1665  Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
1666
1667  HInstruction* object = LoadLocal(reference, Primitive::kPrimNot, dex_pc);
1668  HLoadClass* cls = new (arena_) HLoadClass(
1669      graph_->GetCurrentMethod(),
1670      type_index,
1671      *dex_compilation_unit_->GetDexFile(),
1672      IsOutermostCompilingClass(type_index),
1673      dex_pc,
1674      !can_access);
1675  current_block_->AddInstruction(cls);
1676
1677  // The class needs a temporary before being used by the type check.
1678  Temporaries temps(graph_);
1679  temps.Add(cls);
1680
1681  TypeCheckKind check_kind = ComputeTypeCheckKind(resolved_class);
1682  if (instruction.Opcode() == Instruction::INSTANCE_OF) {
1683    current_block_->AddInstruction(new (arena_) HInstanceOf(object, cls, check_kind, dex_pc));
1684    UpdateLocal(destination, current_block_->GetLastInstruction(), dex_pc);
1685  } else {
1686    DCHECK_EQ(instruction.Opcode(), Instruction::CHECK_CAST);
1687    current_block_->AddInstruction(new (arena_) HCheckCast(object, cls, check_kind, dex_pc));
1688  }
1689}
1690
1691bool HGraphBuilder::NeedsAccessCheck(uint32_t type_index, bool* finalizable) const {
1692  return !compiler_driver_->CanAccessInstantiableTypeWithoutChecks(
1693      dex_compilation_unit_->GetDexMethodIndex(), *dex_file_, type_index, finalizable);
1694}
1695
1696void HGraphBuilder::BuildSwitchJumpTable(const SwitchTable& table,
1697                                         const Instruction& instruction,
1698                                         HInstruction* value,
1699                                         uint32_t dex_pc) {
1700  // Add the successor blocks to the current block.
1701  uint16_t num_entries = table.GetNumEntries();
1702  for (size_t i = 1; i <= num_entries; i++) {
1703    int32_t target_offset = table.GetEntryAt(i);
1704    HBasicBlock* case_target = FindBlockStartingAt(dex_pc + target_offset);
1705    DCHECK(case_target != nullptr);
1706
1707    // Add the target block as a successor.
1708    current_block_->AddSuccessor(case_target);
1709  }
1710
1711  // Add the default target block as the last successor.
1712  HBasicBlock* default_target = FindBlockStartingAt(dex_pc + instruction.SizeInCodeUnits());
1713  DCHECK(default_target != nullptr);
1714  current_block_->AddSuccessor(default_target);
1715
1716  // Now add the Switch instruction.
1717  int32_t starting_key = table.GetEntryAt(0);
1718  current_block_->AddInstruction(
1719      new (arena_) HPackedSwitch(starting_key, num_entries, value, dex_pc));
1720  // This block ends with control flow.
1721  current_block_ = nullptr;
1722}
1723
1724void HGraphBuilder::BuildPackedSwitch(const Instruction& instruction, uint32_t dex_pc) {
1725  // Verifier guarantees that the payload for PackedSwitch contains:
1726  //   (a) number of entries (may be zero)
1727  //   (b) first and lowest switch case value (entry 0, always present)
1728  //   (c) list of target pcs (entries 1 <= i <= N)
1729  SwitchTable table(instruction, dex_pc, false);
1730
1731  // Value to test against.
1732  HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt, dex_pc);
1733
1734  // Starting key value.
1735  int32_t starting_key = table.GetEntryAt(0);
1736
1737  // Retrieve number of entries.
1738  uint16_t num_entries = table.GetNumEntries();
1739  if (num_entries == 0) {
1740    return;
1741  }
1742
1743  // Don't use a packed switch if there are very few entries.
1744  if (num_entries > kSmallSwitchThreshold) {
1745    BuildSwitchJumpTable(table, instruction, value, dex_pc);
1746  } else {
1747    // Chained cmp-and-branch, starting from starting_key.
1748    for (size_t i = 1; i <= num_entries; i++) {
1749      BuildSwitchCaseHelper(instruction,
1750                            i,
1751                            i == num_entries,
1752                            table,
1753                            value,
1754                            starting_key + i - 1,
1755                            table.GetEntryAt(i),
1756                            dex_pc);
1757    }
1758  }
1759}
1760
1761void HGraphBuilder::BuildSparseSwitch(const Instruction& instruction, uint32_t dex_pc) {
1762  // Verifier guarantees that the payload for SparseSwitch contains:
1763  //   (a) number of entries (may be zero)
1764  //   (b) sorted key values (entries 0 <= i < N)
1765  //   (c) target pcs corresponding to the switch values (entries N <= i < 2*N)
1766  SwitchTable table(instruction, dex_pc, true);
1767
1768  // Value to test against.
1769  HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt, dex_pc);
1770
1771  uint16_t num_entries = table.GetNumEntries();
1772
1773  for (size_t i = 0; i < num_entries; i++) {
1774    BuildSwitchCaseHelper(instruction, i, i == static_cast<size_t>(num_entries) - 1, table, value,
1775                          table.GetEntryAt(i), table.GetEntryAt(i + num_entries), dex_pc);
1776  }
1777}
1778
1779void HGraphBuilder::BuildSwitchCaseHelper(const Instruction& instruction, size_t index,
1780                                          bool is_last_case, const SwitchTable& table,
1781                                          HInstruction* value, int32_t case_value_int,
1782                                          int32_t target_offset, uint32_t dex_pc) {
1783  HBasicBlock* case_target = FindBlockStartingAt(dex_pc + target_offset);
1784  DCHECK(case_target != nullptr);
1785  PotentiallyAddSuspendCheck(case_target, dex_pc);
1786
1787  // The current case's value.
1788  HInstruction* this_case_value = graph_->GetIntConstant(case_value_int, dex_pc);
1789
1790  // Compare value and this_case_value.
1791  HEqual* comparison = new (arena_) HEqual(value, this_case_value, dex_pc);
1792  current_block_->AddInstruction(comparison);
1793  HInstruction* ifinst = new (arena_) HIf(comparison, dex_pc);
1794  current_block_->AddInstruction(ifinst);
1795
1796  // Case hit: use the target offset to determine where to go.
1797  current_block_->AddSuccessor(case_target);
1798
1799  // Case miss: go to the next case (or default fall-through).
1800  // When there is a next case, we use the block stored with the table offset representing this
1801  // case (that is where we registered them in ComputeBranchTargets).
1802  // When there is no next case, we use the following instruction.
1803  // TODO: Find a good way to peel the last iteration to avoid conditional, but still have re-use.
1804  if (!is_last_case) {
1805    HBasicBlock* next_case_target = FindBlockStartingAt(table.GetDexPcForIndex(index));
1806    DCHECK(next_case_target != nullptr);
1807    current_block_->AddSuccessor(next_case_target);
1808
1809    // Need to manually add the block, as there is no dex-pc transition for the cases.
1810    graph_->AddBlock(next_case_target);
1811
1812    current_block_ = next_case_target;
1813  } else {
1814    HBasicBlock* default_target = FindBlockStartingAt(dex_pc + instruction.SizeInCodeUnits());
1815    DCHECK(default_target != nullptr);
1816    current_block_->AddSuccessor(default_target);
1817    current_block_ = nullptr;
1818  }
1819}
1820
1821void HGraphBuilder::PotentiallyAddSuspendCheck(HBasicBlock* target, uint32_t dex_pc) {
1822  int32_t target_offset = target->GetDexPc() - dex_pc;
1823  if (target_offset <= 0) {
1824    // DX generates back edges to the first encountered return. We can save
1825    // time of later passes by not adding redundant suspend checks.
1826    HInstruction* last_in_target = target->GetLastInstruction();
1827    if (last_in_target != nullptr &&
1828        (last_in_target->IsReturn() || last_in_target->IsReturnVoid())) {
1829      return;
1830    }
1831
1832    // Add a suspend check to backward branches which may potentially loop. We
1833    // can remove them after we recognize loops in the graph.
1834    current_block_->AddInstruction(new (arena_) HSuspendCheck(dex_pc));
1835  }
1836}
1837
1838bool HGraphBuilder::CanDecodeQuickenedInfo() const {
1839  return interpreter_metadata_ != nullptr;
1840}
1841
1842uint16_t HGraphBuilder::LookupQuickenedInfo(uint32_t dex_pc) {
1843  DCHECK(interpreter_metadata_ != nullptr);
1844  uint32_t dex_pc_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1845  DCHECK_EQ(dex_pc, dex_pc_in_map);
1846  return DecodeUnsignedLeb128(&interpreter_metadata_);
1847}
1848
1849bool HGraphBuilder::AnalyzeDexInstruction(const Instruction& instruction, uint32_t dex_pc) {
1850  if (current_block_ == nullptr) {
1851    return true;  // Dead code
1852  }
1853
1854  switch (instruction.Opcode()) {
1855    case Instruction::CONST_4: {
1856      int32_t register_index = instruction.VRegA();
1857      HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_11n(), dex_pc);
1858      UpdateLocal(register_index, constant, dex_pc);
1859      break;
1860    }
1861
1862    case Instruction::CONST_16: {
1863      int32_t register_index = instruction.VRegA();
1864      HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21s(), dex_pc);
1865      UpdateLocal(register_index, constant, dex_pc);
1866      break;
1867    }
1868
1869    case Instruction::CONST: {
1870      int32_t register_index = instruction.VRegA();
1871      HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_31i(), dex_pc);
1872      UpdateLocal(register_index, constant, dex_pc);
1873      break;
1874    }
1875
1876    case Instruction::CONST_HIGH16: {
1877      int32_t register_index = instruction.VRegA();
1878      HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21h() << 16, dex_pc);
1879      UpdateLocal(register_index, constant, dex_pc);
1880      break;
1881    }
1882
1883    case Instruction::CONST_WIDE_16: {
1884      int32_t register_index = instruction.VRegA();
1885      // Get 16 bits of constant value, sign extended to 64 bits.
1886      int64_t value = instruction.VRegB_21s();
1887      value <<= 48;
1888      value >>= 48;
1889      HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1890      UpdateLocal(register_index, constant, dex_pc);
1891      break;
1892    }
1893
1894    case Instruction::CONST_WIDE_32: {
1895      int32_t register_index = instruction.VRegA();
1896      // Get 32 bits of constant value, sign extended to 64 bits.
1897      int64_t value = instruction.VRegB_31i();
1898      value <<= 32;
1899      value >>= 32;
1900      HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1901      UpdateLocal(register_index, constant, dex_pc);
1902      break;
1903    }
1904
1905    case Instruction::CONST_WIDE: {
1906      int32_t register_index = instruction.VRegA();
1907      HLongConstant* constant = graph_->GetLongConstant(instruction.VRegB_51l(), dex_pc);
1908      UpdateLocal(register_index, constant, dex_pc);
1909      break;
1910    }
1911
1912    case Instruction::CONST_WIDE_HIGH16: {
1913      int32_t register_index = instruction.VRegA();
1914      int64_t value = static_cast<int64_t>(instruction.VRegB_21h()) << 48;
1915      HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1916      UpdateLocal(register_index, constant, dex_pc);
1917      break;
1918    }
1919
1920    // Note that the SSA building will refine the types.
1921    case Instruction::MOVE:
1922    case Instruction::MOVE_FROM16:
1923    case Instruction::MOVE_16: {
1924      HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimInt, dex_pc);
1925      UpdateLocal(instruction.VRegA(), value, dex_pc);
1926      break;
1927    }
1928
1929    // Note that the SSA building will refine the types.
1930    case Instruction::MOVE_WIDE:
1931    case Instruction::MOVE_WIDE_FROM16:
1932    case Instruction::MOVE_WIDE_16: {
1933      HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimLong, dex_pc);
1934      UpdateLocal(instruction.VRegA(), value, dex_pc);
1935      break;
1936    }
1937
1938    case Instruction::MOVE_OBJECT:
1939    case Instruction::MOVE_OBJECT_16:
1940    case Instruction::MOVE_OBJECT_FROM16: {
1941      HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimNot, dex_pc);
1942      UpdateLocal(instruction.VRegA(), value, dex_pc);
1943      break;
1944    }
1945
1946    case Instruction::RETURN_VOID_NO_BARRIER:
1947    case Instruction::RETURN_VOID: {
1948      BuildReturn(instruction, Primitive::kPrimVoid, dex_pc);
1949      break;
1950    }
1951
1952#define IF_XX(comparison, cond) \
1953    case Instruction::IF_##cond: If_22t<comparison>(instruction, dex_pc); break; \
1954    case Instruction::IF_##cond##Z: If_21t<comparison>(instruction, dex_pc); break
1955
1956    IF_XX(HEqual, EQ);
1957    IF_XX(HNotEqual, NE);
1958    IF_XX(HLessThan, LT);
1959    IF_XX(HLessThanOrEqual, LE);
1960    IF_XX(HGreaterThan, GT);
1961    IF_XX(HGreaterThanOrEqual, GE);
1962
1963    case Instruction::GOTO:
1964    case Instruction::GOTO_16:
1965    case Instruction::GOTO_32: {
1966      int32_t offset = instruction.GetTargetOffset();
1967      HBasicBlock* target = FindBlockStartingAt(offset + dex_pc);
1968      DCHECK(target != nullptr);
1969      PotentiallyAddSuspendCheck(target, dex_pc);
1970      current_block_->AddInstruction(new (arena_) HGoto(dex_pc));
1971      current_block_->AddSuccessor(target);
1972      current_block_ = nullptr;
1973      break;
1974    }
1975
1976    case Instruction::RETURN: {
1977      BuildReturn(instruction, return_type_, dex_pc);
1978      break;
1979    }
1980
1981    case Instruction::RETURN_OBJECT: {
1982      BuildReturn(instruction, return_type_, dex_pc);
1983      break;
1984    }
1985
1986    case Instruction::RETURN_WIDE: {
1987      BuildReturn(instruction, return_type_, dex_pc);
1988      break;
1989    }
1990
1991    case Instruction::INVOKE_DIRECT:
1992    case Instruction::INVOKE_INTERFACE:
1993    case Instruction::INVOKE_STATIC:
1994    case Instruction::INVOKE_SUPER:
1995    case Instruction::INVOKE_VIRTUAL:
1996    case Instruction::INVOKE_VIRTUAL_QUICK: {
1997      uint16_t method_idx;
1998      if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_QUICK) {
1999        if (!CanDecodeQuickenedInfo()) {
2000          return false;
2001        }
2002        method_idx = LookupQuickenedInfo(dex_pc);
2003      } else {
2004        method_idx = instruction.VRegB_35c();
2005      }
2006      uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
2007      uint32_t args[5];
2008      instruction.GetVarArgs(args);
2009      if (!BuildInvoke(instruction, dex_pc, method_idx,
2010                       number_of_vreg_arguments, false, args, -1)) {
2011        return false;
2012      }
2013      break;
2014    }
2015
2016    case Instruction::INVOKE_DIRECT_RANGE:
2017    case Instruction::INVOKE_INTERFACE_RANGE:
2018    case Instruction::INVOKE_STATIC_RANGE:
2019    case Instruction::INVOKE_SUPER_RANGE:
2020    case Instruction::INVOKE_VIRTUAL_RANGE:
2021    case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
2022      uint16_t method_idx;
2023      if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK) {
2024        if (!CanDecodeQuickenedInfo()) {
2025          return false;
2026        }
2027        method_idx = LookupQuickenedInfo(dex_pc);
2028      } else {
2029        method_idx = instruction.VRegB_3rc();
2030      }
2031      uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
2032      uint32_t register_index = instruction.VRegC();
2033      if (!BuildInvoke(instruction, dex_pc, method_idx,
2034                       number_of_vreg_arguments, true, nullptr, register_index)) {
2035        return false;
2036      }
2037      break;
2038    }
2039
2040    case Instruction::NEG_INT: {
2041      Unop_12x<HNeg>(instruction, Primitive::kPrimInt, dex_pc);
2042      break;
2043    }
2044
2045    case Instruction::NEG_LONG: {
2046      Unop_12x<HNeg>(instruction, Primitive::kPrimLong, dex_pc);
2047      break;
2048    }
2049
2050    case Instruction::NEG_FLOAT: {
2051      Unop_12x<HNeg>(instruction, Primitive::kPrimFloat, dex_pc);
2052      break;
2053    }
2054
2055    case Instruction::NEG_DOUBLE: {
2056      Unop_12x<HNeg>(instruction, Primitive::kPrimDouble, dex_pc);
2057      break;
2058    }
2059
2060    case Instruction::NOT_INT: {
2061      Unop_12x<HNot>(instruction, Primitive::kPrimInt, dex_pc);
2062      break;
2063    }
2064
2065    case Instruction::NOT_LONG: {
2066      Unop_12x<HNot>(instruction, Primitive::kPrimLong, dex_pc);
2067      break;
2068    }
2069
2070    case Instruction::INT_TO_LONG: {
2071      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimLong, dex_pc);
2072      break;
2073    }
2074
2075    case Instruction::INT_TO_FLOAT: {
2076      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimFloat, dex_pc);
2077      break;
2078    }
2079
2080    case Instruction::INT_TO_DOUBLE: {
2081      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimDouble, dex_pc);
2082      break;
2083    }
2084
2085    case Instruction::LONG_TO_INT: {
2086      Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimInt, dex_pc);
2087      break;
2088    }
2089
2090    case Instruction::LONG_TO_FLOAT: {
2091      Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimFloat, dex_pc);
2092      break;
2093    }
2094
2095    case Instruction::LONG_TO_DOUBLE: {
2096      Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimDouble, dex_pc);
2097      break;
2098    }
2099
2100    case Instruction::FLOAT_TO_INT: {
2101      Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimInt, dex_pc);
2102      break;
2103    }
2104
2105    case Instruction::FLOAT_TO_LONG: {
2106      Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimLong, dex_pc);
2107      break;
2108    }
2109
2110    case Instruction::FLOAT_TO_DOUBLE: {
2111      Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimDouble, dex_pc);
2112      break;
2113    }
2114
2115    case Instruction::DOUBLE_TO_INT: {
2116      Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimInt, dex_pc);
2117      break;
2118    }
2119
2120    case Instruction::DOUBLE_TO_LONG: {
2121      Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimLong, dex_pc);
2122      break;
2123    }
2124
2125    case Instruction::DOUBLE_TO_FLOAT: {
2126      Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimFloat, dex_pc);
2127      break;
2128    }
2129
2130    case Instruction::INT_TO_BYTE: {
2131      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimByte, dex_pc);
2132      break;
2133    }
2134
2135    case Instruction::INT_TO_SHORT: {
2136      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimShort, dex_pc);
2137      break;
2138    }
2139
2140    case Instruction::INT_TO_CHAR: {
2141      Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimChar, dex_pc);
2142      break;
2143    }
2144
2145    case Instruction::ADD_INT: {
2146      Binop_23x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2147      break;
2148    }
2149
2150    case Instruction::ADD_LONG: {
2151      Binop_23x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2152      break;
2153    }
2154
2155    case Instruction::ADD_DOUBLE: {
2156      Binop_23x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2157      break;
2158    }
2159
2160    case Instruction::ADD_FLOAT: {
2161      Binop_23x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2162      break;
2163    }
2164
2165    case Instruction::SUB_INT: {
2166      Binop_23x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2167      break;
2168    }
2169
2170    case Instruction::SUB_LONG: {
2171      Binop_23x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2172      break;
2173    }
2174
2175    case Instruction::SUB_FLOAT: {
2176      Binop_23x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2177      break;
2178    }
2179
2180    case Instruction::SUB_DOUBLE: {
2181      Binop_23x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2182      break;
2183    }
2184
2185    case Instruction::ADD_INT_2ADDR: {
2186      Binop_12x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2187      break;
2188    }
2189
2190    case Instruction::MUL_INT: {
2191      Binop_23x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2192      break;
2193    }
2194
2195    case Instruction::MUL_LONG: {
2196      Binop_23x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2197      break;
2198    }
2199
2200    case Instruction::MUL_FLOAT: {
2201      Binop_23x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2202      break;
2203    }
2204
2205    case Instruction::MUL_DOUBLE: {
2206      Binop_23x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2207      break;
2208    }
2209
2210    case Instruction::DIV_INT: {
2211      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2212                         dex_pc, Primitive::kPrimInt, false, true);
2213      break;
2214    }
2215
2216    case Instruction::DIV_LONG: {
2217      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2218                         dex_pc, Primitive::kPrimLong, false, true);
2219      break;
2220    }
2221
2222    case Instruction::DIV_FLOAT: {
2223      Binop_23x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2224      break;
2225    }
2226
2227    case Instruction::DIV_DOUBLE: {
2228      Binop_23x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2229      break;
2230    }
2231
2232    case Instruction::REM_INT: {
2233      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2234                         dex_pc, Primitive::kPrimInt, false, false);
2235      break;
2236    }
2237
2238    case Instruction::REM_LONG: {
2239      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2240                         dex_pc, Primitive::kPrimLong, false, false);
2241      break;
2242    }
2243
2244    case Instruction::REM_FLOAT: {
2245      Binop_23x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2246      break;
2247    }
2248
2249    case Instruction::REM_DOUBLE: {
2250      Binop_23x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2251      break;
2252    }
2253
2254    case Instruction::AND_INT: {
2255      Binop_23x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2256      break;
2257    }
2258
2259    case Instruction::AND_LONG: {
2260      Binop_23x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2261      break;
2262    }
2263
2264    case Instruction::SHL_INT: {
2265      Binop_23x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2266      break;
2267    }
2268
2269    case Instruction::SHL_LONG: {
2270      Binop_23x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2271      break;
2272    }
2273
2274    case Instruction::SHR_INT: {
2275      Binop_23x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2276      break;
2277    }
2278
2279    case Instruction::SHR_LONG: {
2280      Binop_23x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2281      break;
2282    }
2283
2284    case Instruction::USHR_INT: {
2285      Binop_23x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2286      break;
2287    }
2288
2289    case Instruction::USHR_LONG: {
2290      Binop_23x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2291      break;
2292    }
2293
2294    case Instruction::OR_INT: {
2295      Binop_23x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2296      break;
2297    }
2298
2299    case Instruction::OR_LONG: {
2300      Binop_23x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2301      break;
2302    }
2303
2304    case Instruction::XOR_INT: {
2305      Binop_23x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2306      break;
2307    }
2308
2309    case Instruction::XOR_LONG: {
2310      Binop_23x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2311      break;
2312    }
2313
2314    case Instruction::ADD_LONG_2ADDR: {
2315      Binop_12x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2316      break;
2317    }
2318
2319    case Instruction::ADD_DOUBLE_2ADDR: {
2320      Binop_12x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2321      break;
2322    }
2323
2324    case Instruction::ADD_FLOAT_2ADDR: {
2325      Binop_12x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2326      break;
2327    }
2328
2329    case Instruction::SUB_INT_2ADDR: {
2330      Binop_12x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2331      break;
2332    }
2333
2334    case Instruction::SUB_LONG_2ADDR: {
2335      Binop_12x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2336      break;
2337    }
2338
2339    case Instruction::SUB_FLOAT_2ADDR: {
2340      Binop_12x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2341      break;
2342    }
2343
2344    case Instruction::SUB_DOUBLE_2ADDR: {
2345      Binop_12x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2346      break;
2347    }
2348
2349    case Instruction::MUL_INT_2ADDR: {
2350      Binop_12x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2351      break;
2352    }
2353
2354    case Instruction::MUL_LONG_2ADDR: {
2355      Binop_12x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2356      break;
2357    }
2358
2359    case Instruction::MUL_FLOAT_2ADDR: {
2360      Binop_12x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2361      break;
2362    }
2363
2364    case Instruction::MUL_DOUBLE_2ADDR: {
2365      Binop_12x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2366      break;
2367    }
2368
2369    case Instruction::DIV_INT_2ADDR: {
2370      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2371                         dex_pc, Primitive::kPrimInt, false, true);
2372      break;
2373    }
2374
2375    case Instruction::DIV_LONG_2ADDR: {
2376      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2377                         dex_pc, Primitive::kPrimLong, false, true);
2378      break;
2379    }
2380
2381    case Instruction::REM_INT_2ADDR: {
2382      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2383                         dex_pc, Primitive::kPrimInt, false, false);
2384      break;
2385    }
2386
2387    case Instruction::REM_LONG_2ADDR: {
2388      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2389                         dex_pc, Primitive::kPrimLong, false, false);
2390      break;
2391    }
2392
2393    case Instruction::REM_FLOAT_2ADDR: {
2394      Binop_12x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2395      break;
2396    }
2397
2398    case Instruction::REM_DOUBLE_2ADDR: {
2399      Binop_12x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2400      break;
2401    }
2402
2403    case Instruction::SHL_INT_2ADDR: {
2404      Binop_12x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2405      break;
2406    }
2407
2408    case Instruction::SHL_LONG_2ADDR: {
2409      Binop_12x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2410      break;
2411    }
2412
2413    case Instruction::SHR_INT_2ADDR: {
2414      Binop_12x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2415      break;
2416    }
2417
2418    case Instruction::SHR_LONG_2ADDR: {
2419      Binop_12x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2420      break;
2421    }
2422
2423    case Instruction::USHR_INT_2ADDR: {
2424      Binop_12x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2425      break;
2426    }
2427
2428    case Instruction::USHR_LONG_2ADDR: {
2429      Binop_12x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2430      break;
2431    }
2432
2433    case Instruction::DIV_FLOAT_2ADDR: {
2434      Binop_12x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2435      break;
2436    }
2437
2438    case Instruction::DIV_DOUBLE_2ADDR: {
2439      Binop_12x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2440      break;
2441    }
2442
2443    case Instruction::AND_INT_2ADDR: {
2444      Binop_12x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2445      break;
2446    }
2447
2448    case Instruction::AND_LONG_2ADDR: {
2449      Binop_12x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2450      break;
2451    }
2452
2453    case Instruction::OR_INT_2ADDR: {
2454      Binop_12x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2455      break;
2456    }
2457
2458    case Instruction::OR_LONG_2ADDR: {
2459      Binop_12x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2460      break;
2461    }
2462
2463    case Instruction::XOR_INT_2ADDR: {
2464      Binop_12x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2465      break;
2466    }
2467
2468    case Instruction::XOR_LONG_2ADDR: {
2469      Binop_12x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2470      break;
2471    }
2472
2473    case Instruction::ADD_INT_LIT16: {
2474      Binop_22s<HAdd>(instruction, false, dex_pc);
2475      break;
2476    }
2477
2478    case Instruction::AND_INT_LIT16: {
2479      Binop_22s<HAnd>(instruction, false, dex_pc);
2480      break;
2481    }
2482
2483    case Instruction::OR_INT_LIT16: {
2484      Binop_22s<HOr>(instruction, false, dex_pc);
2485      break;
2486    }
2487
2488    case Instruction::XOR_INT_LIT16: {
2489      Binop_22s<HXor>(instruction, false, dex_pc);
2490      break;
2491    }
2492
2493    case Instruction::RSUB_INT: {
2494      Binop_22s<HSub>(instruction, true, dex_pc);
2495      break;
2496    }
2497
2498    case Instruction::MUL_INT_LIT16: {
2499      Binop_22s<HMul>(instruction, false, dex_pc);
2500      break;
2501    }
2502
2503    case Instruction::ADD_INT_LIT8: {
2504      Binop_22b<HAdd>(instruction, false, dex_pc);
2505      break;
2506    }
2507
2508    case Instruction::AND_INT_LIT8: {
2509      Binop_22b<HAnd>(instruction, false, dex_pc);
2510      break;
2511    }
2512
2513    case Instruction::OR_INT_LIT8: {
2514      Binop_22b<HOr>(instruction, false, dex_pc);
2515      break;
2516    }
2517
2518    case Instruction::XOR_INT_LIT8: {
2519      Binop_22b<HXor>(instruction, false, dex_pc);
2520      break;
2521    }
2522
2523    case Instruction::RSUB_INT_LIT8: {
2524      Binop_22b<HSub>(instruction, true, dex_pc);
2525      break;
2526    }
2527
2528    case Instruction::MUL_INT_LIT8: {
2529      Binop_22b<HMul>(instruction, false, dex_pc);
2530      break;
2531    }
2532
2533    case Instruction::DIV_INT_LIT16:
2534    case Instruction::DIV_INT_LIT8: {
2535      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2536                         dex_pc, Primitive::kPrimInt, true, true);
2537      break;
2538    }
2539
2540    case Instruction::REM_INT_LIT16:
2541    case Instruction::REM_INT_LIT8: {
2542      BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2543                         dex_pc, Primitive::kPrimInt, true, false);
2544      break;
2545    }
2546
2547    case Instruction::SHL_INT_LIT8: {
2548      Binop_22b<HShl>(instruction, false, dex_pc);
2549      break;
2550    }
2551
2552    case Instruction::SHR_INT_LIT8: {
2553      Binop_22b<HShr>(instruction, false, dex_pc);
2554      break;
2555    }
2556
2557    case Instruction::USHR_INT_LIT8: {
2558      Binop_22b<HUShr>(instruction, false, dex_pc);
2559      break;
2560    }
2561
2562    case Instruction::NEW_INSTANCE: {
2563      uint16_t type_index = instruction.VRegB_21c();
2564      if (compiler_driver_->IsStringTypeIndex(type_index, dex_file_)) {
2565        int32_t register_index = instruction.VRegA();
2566        HFakeString* fake_string = new (arena_) HFakeString(dex_pc);
2567        current_block_->AddInstruction(fake_string);
2568        UpdateLocal(register_index, fake_string, dex_pc);
2569      } else {
2570        if (!BuildNewInstance(type_index, dex_pc)) {
2571          return false;
2572        }
2573        UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction(), dex_pc);
2574      }
2575      break;
2576    }
2577
2578    case Instruction::NEW_ARRAY: {
2579      uint16_t type_index = instruction.VRegC_22c();
2580      HInstruction* length = LoadLocal(instruction.VRegB_22c(), Primitive::kPrimInt, dex_pc);
2581      bool finalizable;
2582      QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
2583          ? kQuickAllocArrayWithAccessCheck
2584          : kQuickAllocArray;
2585      current_block_->AddInstruction(new (arena_) HNewArray(length,
2586                                                            graph_->GetCurrentMethod(),
2587                                                            dex_pc,
2588                                                            type_index,
2589                                                            *dex_compilation_unit_->GetDexFile(),
2590                                                            entrypoint));
2591      UpdateLocal(instruction.VRegA_22c(), current_block_->GetLastInstruction(), dex_pc);
2592      break;
2593    }
2594
2595    case Instruction::FILLED_NEW_ARRAY: {
2596      uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
2597      uint32_t type_index = instruction.VRegB_35c();
2598      uint32_t args[5];
2599      instruction.GetVarArgs(args);
2600      BuildFilledNewArray(dex_pc, type_index, number_of_vreg_arguments, false, args, 0);
2601      break;
2602    }
2603
2604    case Instruction::FILLED_NEW_ARRAY_RANGE: {
2605      uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
2606      uint32_t type_index = instruction.VRegB_3rc();
2607      uint32_t register_index = instruction.VRegC_3rc();
2608      BuildFilledNewArray(
2609          dex_pc, type_index, number_of_vreg_arguments, true, nullptr, register_index);
2610      break;
2611    }
2612
2613    case Instruction::FILL_ARRAY_DATA: {
2614      BuildFillArrayData(instruction, dex_pc);
2615      break;
2616    }
2617
2618    case Instruction::MOVE_RESULT:
2619    case Instruction::MOVE_RESULT_WIDE:
2620    case Instruction::MOVE_RESULT_OBJECT: {
2621      if (latest_result_ == nullptr) {
2622        // Only dead code can lead to this situation, where the verifier
2623        // does not reject the method.
2624      } else {
2625        // An Invoke/FilledNewArray and its MoveResult could have landed in
2626        // different blocks if there was a try/catch block boundary between
2627        // them. For Invoke, we insert a StoreLocal after the instruction. For
2628        // FilledNewArray, the local needs to be updated after the array was
2629        // filled, otherwise we might overwrite an input vreg.
2630        HStoreLocal* update_local =
2631            new (arena_) HStoreLocal(GetLocalAt(instruction.VRegA()), latest_result_, dex_pc);
2632        HBasicBlock* block = latest_result_->GetBlock();
2633        if (block == current_block_) {
2634          // MoveResult and the previous instruction are in the same block.
2635          current_block_->AddInstruction(update_local);
2636        } else {
2637          // The two instructions are in different blocks. Insert the MoveResult
2638          // before the final control-flow instruction of the previous block.
2639          DCHECK(block->EndsWithControlFlowInstruction());
2640          DCHECK(current_block_->GetInstructions().IsEmpty());
2641          block->InsertInstructionBefore(update_local, block->GetLastInstruction());
2642        }
2643        latest_result_ = nullptr;
2644      }
2645      break;
2646    }
2647
2648    case Instruction::CMP_LONG: {
2649      Binop_23x_cmp(instruction, Primitive::kPrimLong, ComparisonBias::kNoBias, dex_pc);
2650      break;
2651    }
2652
2653    case Instruction::CMPG_FLOAT: {
2654      Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kGtBias, dex_pc);
2655      break;
2656    }
2657
2658    case Instruction::CMPG_DOUBLE: {
2659      Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kGtBias, dex_pc);
2660      break;
2661    }
2662
2663    case Instruction::CMPL_FLOAT: {
2664      Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kLtBias, dex_pc);
2665      break;
2666    }
2667
2668    case Instruction::CMPL_DOUBLE: {
2669      Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kLtBias, dex_pc);
2670      break;
2671    }
2672
2673    case Instruction::NOP:
2674      break;
2675
2676    case Instruction::IGET:
2677    case Instruction::IGET_QUICK:
2678    case Instruction::IGET_WIDE:
2679    case Instruction::IGET_WIDE_QUICK:
2680    case Instruction::IGET_OBJECT:
2681    case Instruction::IGET_OBJECT_QUICK:
2682    case Instruction::IGET_BOOLEAN:
2683    case Instruction::IGET_BOOLEAN_QUICK:
2684    case Instruction::IGET_BYTE:
2685    case Instruction::IGET_BYTE_QUICK:
2686    case Instruction::IGET_CHAR:
2687    case Instruction::IGET_CHAR_QUICK:
2688    case Instruction::IGET_SHORT:
2689    case Instruction::IGET_SHORT_QUICK: {
2690      if (!BuildInstanceFieldAccess(instruction, dex_pc, false)) {
2691        return false;
2692      }
2693      break;
2694    }
2695
2696    case Instruction::IPUT:
2697    case Instruction::IPUT_QUICK:
2698    case Instruction::IPUT_WIDE:
2699    case Instruction::IPUT_WIDE_QUICK:
2700    case Instruction::IPUT_OBJECT:
2701    case Instruction::IPUT_OBJECT_QUICK:
2702    case Instruction::IPUT_BOOLEAN:
2703    case Instruction::IPUT_BOOLEAN_QUICK:
2704    case Instruction::IPUT_BYTE:
2705    case Instruction::IPUT_BYTE_QUICK:
2706    case Instruction::IPUT_CHAR:
2707    case Instruction::IPUT_CHAR_QUICK:
2708    case Instruction::IPUT_SHORT:
2709    case Instruction::IPUT_SHORT_QUICK: {
2710      if (!BuildInstanceFieldAccess(instruction, dex_pc, true)) {
2711        return false;
2712      }
2713      break;
2714    }
2715
2716    case Instruction::SGET:
2717    case Instruction::SGET_WIDE:
2718    case Instruction::SGET_OBJECT:
2719    case Instruction::SGET_BOOLEAN:
2720    case Instruction::SGET_BYTE:
2721    case Instruction::SGET_CHAR:
2722    case Instruction::SGET_SHORT: {
2723      if (!BuildStaticFieldAccess(instruction, dex_pc, false)) {
2724        return false;
2725      }
2726      break;
2727    }
2728
2729    case Instruction::SPUT:
2730    case Instruction::SPUT_WIDE:
2731    case Instruction::SPUT_OBJECT:
2732    case Instruction::SPUT_BOOLEAN:
2733    case Instruction::SPUT_BYTE:
2734    case Instruction::SPUT_CHAR:
2735    case Instruction::SPUT_SHORT: {
2736      if (!BuildStaticFieldAccess(instruction, dex_pc, true)) {
2737        return false;
2738      }
2739      break;
2740    }
2741
2742#define ARRAY_XX(kind, anticipated_type)                                          \
2743    case Instruction::AGET##kind: {                                               \
2744      BuildArrayAccess(instruction, dex_pc, false, anticipated_type);         \
2745      break;                                                                      \
2746    }                                                                             \
2747    case Instruction::APUT##kind: {                                               \
2748      BuildArrayAccess(instruction, dex_pc, true, anticipated_type);          \
2749      break;                                                                      \
2750    }
2751
2752    ARRAY_XX(, Primitive::kPrimInt);
2753    ARRAY_XX(_WIDE, Primitive::kPrimLong);
2754    ARRAY_XX(_OBJECT, Primitive::kPrimNot);
2755    ARRAY_XX(_BOOLEAN, Primitive::kPrimBoolean);
2756    ARRAY_XX(_BYTE, Primitive::kPrimByte);
2757    ARRAY_XX(_CHAR, Primitive::kPrimChar);
2758    ARRAY_XX(_SHORT, Primitive::kPrimShort);
2759
2760    case Instruction::ARRAY_LENGTH: {
2761      HInstruction* object = LoadLocal(instruction.VRegB_12x(), Primitive::kPrimNot, dex_pc);
2762      // No need for a temporary for the null check, it is the only input of the following
2763      // instruction.
2764      object = new (arena_) HNullCheck(object, dex_pc);
2765      current_block_->AddInstruction(object);
2766      current_block_->AddInstruction(new (arena_) HArrayLength(object, dex_pc));
2767      UpdateLocal(instruction.VRegA_12x(), current_block_->GetLastInstruction(), dex_pc);
2768      break;
2769    }
2770
2771    case Instruction::CONST_STRING: {
2772      current_block_->AddInstruction(
2773          new (arena_) HLoadString(graph_->GetCurrentMethod(), instruction.VRegB_21c(), dex_pc));
2774      UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction(), dex_pc);
2775      break;
2776    }
2777
2778    case Instruction::CONST_STRING_JUMBO: {
2779      current_block_->AddInstruction(
2780          new (arena_) HLoadString(graph_->GetCurrentMethod(), instruction.VRegB_31c(), dex_pc));
2781      UpdateLocal(instruction.VRegA_31c(), current_block_->GetLastInstruction(), dex_pc);
2782      break;
2783    }
2784
2785    case Instruction::CONST_CLASS: {
2786      uint16_t type_index = instruction.VRegB_21c();
2787      bool type_known_final;
2788      bool type_known_abstract;
2789      bool dont_use_is_referrers_class;
2790      // `CanAccessTypeWithoutChecks` will tell whether the method being
2791      // built is trying to access its own class, so that the generated
2792      // code can optimize for this case. However, the optimization does not
2793      // work for inlining, so we use `IsOutermostCompilingClass` instead.
2794      bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
2795          dex_compilation_unit_->GetDexMethodIndex(), *dex_file_, type_index,
2796          &type_known_final, &type_known_abstract, &dont_use_is_referrers_class);
2797      current_block_->AddInstruction(new (arena_) HLoadClass(
2798          graph_->GetCurrentMethod(),
2799          type_index,
2800          *dex_compilation_unit_->GetDexFile(),
2801          IsOutermostCompilingClass(type_index),
2802          dex_pc,
2803          !can_access));
2804      UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction(), dex_pc);
2805      break;
2806    }
2807
2808    case Instruction::MOVE_EXCEPTION: {
2809      current_block_->AddInstruction(new (arena_) HLoadException(dex_pc));
2810      UpdateLocal(instruction.VRegA_11x(), current_block_->GetLastInstruction(), dex_pc);
2811      current_block_->AddInstruction(new (arena_) HClearException(dex_pc));
2812      break;
2813    }
2814
2815    case Instruction::THROW: {
2816      HInstruction* exception = LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot, dex_pc);
2817      current_block_->AddInstruction(new (arena_) HThrow(exception, dex_pc));
2818      // A throw instruction must branch to the exit block.
2819      current_block_->AddSuccessor(exit_block_);
2820      // We finished building this block. Set the current block to null to avoid
2821      // adding dead instructions to it.
2822      current_block_ = nullptr;
2823      break;
2824    }
2825
2826    case Instruction::INSTANCE_OF: {
2827      uint8_t destination = instruction.VRegA_22c();
2828      uint8_t reference = instruction.VRegB_22c();
2829      uint16_t type_index = instruction.VRegC_22c();
2830      BuildTypeCheck(instruction, destination, reference, type_index, dex_pc);
2831      break;
2832    }
2833
2834    case Instruction::CHECK_CAST: {
2835      uint8_t reference = instruction.VRegA_21c();
2836      uint16_t type_index = instruction.VRegB_21c();
2837      BuildTypeCheck(instruction, -1, reference, type_index, dex_pc);
2838      break;
2839    }
2840
2841    case Instruction::MONITOR_ENTER: {
2842      current_block_->AddInstruction(new (arena_) HMonitorOperation(
2843          LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot, dex_pc),
2844          HMonitorOperation::kEnter,
2845          dex_pc));
2846      break;
2847    }
2848
2849    case Instruction::MONITOR_EXIT: {
2850      current_block_->AddInstruction(new (arena_) HMonitorOperation(
2851          LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot, dex_pc),
2852          HMonitorOperation::kExit,
2853          dex_pc));
2854      break;
2855    }
2856
2857    case Instruction::PACKED_SWITCH: {
2858      BuildPackedSwitch(instruction, dex_pc);
2859      break;
2860    }
2861
2862    case Instruction::SPARSE_SWITCH: {
2863      BuildSparseSwitch(instruction, dex_pc);
2864      break;
2865    }
2866
2867    default:
2868      VLOG(compiler) << "Did not compile "
2869                     << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
2870                     << " because of unhandled instruction "
2871                     << instruction.Name();
2872      MaybeRecordStat(MethodCompilationStat::kNotCompiledUnhandledInstruction);
2873      return false;
2874  }
2875  return true;
2876}  // NOLINT(readability/fn_size)
2877
2878HLocal* HGraphBuilder::GetLocalAt(uint32_t register_index) const {
2879  return locals_[register_index];
2880}
2881
2882void HGraphBuilder::UpdateLocal(uint32_t register_index,
2883                                HInstruction* instruction,
2884                                uint32_t dex_pc) const {
2885  HLocal* local = GetLocalAt(register_index);
2886  current_block_->AddInstruction(new (arena_) HStoreLocal(local, instruction, dex_pc));
2887}
2888
2889HInstruction* HGraphBuilder::LoadLocal(uint32_t register_index,
2890                                       Primitive::Type type,
2891                                       uint32_t dex_pc) const {
2892  HLocal* local = GetLocalAt(register_index);
2893  current_block_->AddInstruction(new (arena_) HLoadLocal(local, type, dex_pc));
2894  return current_block_->GetLastInstruction();
2895}
2896
2897}  // namespace art
2898