blob: 963a586a843197e502c66e0f55f846dc1a582d37 [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2013 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
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070023#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070026#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010027#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000030#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070031#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010033#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000034
buzbee311ca162013-02-28 15:56:43 -080035namespace art {
36
37#define MAX_PATTERN_LEN 5
38
buzbee1fd33462013-03-25 13:40:45 -070039const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
40 "Phi",
41 "Copy",
42 "FusedCmplFloat",
43 "FusedCmpgFloat",
44 "FusedCmplDouble",
45 "FusedCmpgDouble",
46 "FusedCmpLong",
47 "Nop",
48 "OpNullCheck",
49 "OpRangeCheck",
50 "OpDivZeroCheck",
51 "Check1",
52 "Check2",
53 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040054 "ConstVector",
55 "MoveVector",
56 "PackedMultiply",
57 "PackedAddition",
58 "PackedSubtract",
59 "PackedShiftLeft",
60 "PackedSignedShiftRight",
61 "PackedUnsignedShiftRight",
62 "PackedAnd",
63 "PackedOr",
64 "PackedXor",
65 "PackedAddReduce",
66 "PackedReduce",
67 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070068 "ReserveVectorRegisters",
69 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070070};
71
buzbee862a7602013-04-05 10:58:54 -070072MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070073 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010074 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070075 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080076 ssa_base_vregs_(NULL),
77 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080078 vreg_to_ssa_map_(NULL),
79 ssa_last_defs_(NULL),
80 is_constant_v_(NULL),
81 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070082 use_counts_(arena, 256, kGrowableArrayMisc),
83 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080084 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070085 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070086 dfs_order_(NULL),
87 dfs_post_order_(NULL),
88 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070089 topological_order_(nullptr),
Vladimir Marko55fff042014-07-10 12:42:52 +010090 topological_order_loop_ends_(nullptr),
91 topological_order_indexes_(nullptr),
92 topological_order_loop_head_stack_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080093 i_dom_list_(NULL),
94 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000095 temp_scoped_alloc_(),
96 temp_insn_data_(nullptr),
97 temp_bit_vector_size_(0u),
98 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +010099 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -0700100 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -0800101 try_block_addr_(NULL),
102 entry_block_(NULL),
103 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800104 num_blocks_(0),
105 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700106 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100107 m_units_(arena->Adapter()),
108 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800109 current_method_(kInvalidEntry),
110 current_offset_(kInvalidEntry),
111 def_count_(0),
112 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700113 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100114 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700115 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700116 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
117 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700118 arena_(arena),
119 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800120 forward_branches_(0),
121 compiler_temps_(arena, 6, kGrowableArrayMisc),
122 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800123 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000124 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000125 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000126 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000127 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700128 method_lowering_infos_(arena, 0u),
129 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700130 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800131 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
132 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800133}
134
Ian Rogers6282dc12013-04-18 15:54:02 -0700135MIRGraph::~MIRGraph() {
136 STLDeleteElements(&m_units_);
137}
138
buzbee311ca162013-02-28 15:56:43 -0800139/*
140 * Parse an instruction, return the length of the instruction
141 */
Ian Rogers29a26482014-05-02 15:27:29 -0700142int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
143 const Instruction* inst = Instruction::At(code_ptr);
144 decoded_instruction->opcode = inst->Opcode();
145 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
146 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
147 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
148 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
149 if (inst->HasVarArgs()) {
150 inst->GetVarArgs(decoded_instruction->arg);
151 }
152 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800153}
154
155
156/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700157BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700158 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700159 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800160 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700161 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800162 while (insn) {
163 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700164 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800165 insn = insn->next;
166 }
167 if (insn == NULL) {
168 LOG(FATAL) << "Break split failed";
169 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700170 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700171 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800172
173 bottom_block->start_offset = code_offset;
174 bottom_block->first_mir_insn = insn;
175 bottom_block->last_mir_insn = orig_block->last_mir_insn;
176
Junmo Park90223cc2014-08-04 18:51:21 +0900177 /* If this block was terminated by a return, conditional branch or throw,
178 * the flag needs to go with the bottom block
179 */
buzbee311ca162013-02-28 15:56:43 -0800180 bottom_block->terminated_by_return = orig_block->terminated_by_return;
181 orig_block->terminated_by_return = false;
182
Junmo Park90223cc2014-08-04 18:51:21 +0900183 bottom_block->conditional_branch = orig_block->conditional_branch;
184 orig_block->conditional_branch = false;
185
186 bottom_block->explicit_throw = orig_block->explicit_throw;
187 orig_block->explicit_throw = false;
188
buzbee311ca162013-02-28 15:56:43 -0800189 /* Handle the taken path */
190 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700191 if (bottom_block->taken != NullBasicBlockId) {
192 orig_block->taken = NullBasicBlockId;
193 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
194 bb_taken->predecessors->Delete(orig_block->id);
195 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800196 }
197
198 /* Handle the fallthrough path */
199 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700200 orig_block->fall_through = bottom_block->id;
201 bottom_block->predecessors->Insert(orig_block->id);
202 if (bottom_block->fall_through != NullBasicBlockId) {
203 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
204 bb_fall_through->predecessors->Delete(orig_block->id);
205 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800206 }
207
208 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700209 if (orig_block->successor_block_list_type != kNotUsed) {
210 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
211 bottom_block->successor_blocks = orig_block->successor_blocks;
212 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700213 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700214 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800215 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700216 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700217 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700218 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700219 if (bb != nullptr) {
220 bb->predecessors->Delete(orig_block->id);
221 bb->predecessors->Insert(bottom_block->id);
222 }
buzbee311ca162013-02-28 15:56:43 -0800223 }
224 }
225
buzbee0d829482013-10-11 15:24:55 -0700226 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700227 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800228
buzbee311ca162013-02-28 15:56:43 -0800229 /*
230 * Update the immediate predecessor block pointer so that outgoing edges
231 * can be applied to the proper block.
232 */
233 if (immed_pred_block_p) {
234 DCHECK_EQ(*immed_pred_block_p, orig_block);
235 *immed_pred_block_p = bottom_block;
236 }
buzbeeb48819d2013-09-14 16:15:25 -0700237
238 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000239 DCHECK(insn != nullptr);
240 DCHECK(insn != orig_block->first_mir_insn);
241 DCHECK(insn == bottom_block->first_mir_insn);
242 DCHECK_EQ(insn->offset, bottom_block->start_offset);
243 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700244 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000245 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
246 MIR* p = insn;
247 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
248 while (p != bottom_block->last_mir_insn) {
249 p = p->next;
250 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700251 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700252 int opcode = p->dalvikInsn.opcode;
253 /*
254 * Some messiness here to ensure that we only enter real opcodes and only the
255 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000256 * CHECK and work portions. Since the 2nd half of a split operation is always
257 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700258 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700259 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000260 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700261 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
262 }
buzbeeb48819d2013-09-14 16:15:25 -0700263 }
264
buzbee311ca162013-02-28 15:56:43 -0800265 return bottom_block;
266}
267
268/*
269 * Given a code offset, find out the block that starts with it. If the offset
270 * is in the middle of an existing block, split it into two. If immed_pred_block_p
271 * is not non-null and is the block being split, update *immed_pred_block_p to
272 * point to the bottom block so that outgoing edges can be set up properly
273 * (by the caller)
274 * Utilizes a map for fast lookup of the typical cases.
275 */
buzbee0d829482013-10-11 15:24:55 -0700276BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700277 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700278 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800279 return NULL;
280 }
buzbeeb48819d2013-09-14 16:15:25 -0700281
282 int block_id = dex_pc_to_block_map_.Get(code_offset);
283 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
284
285 if ((bb != NULL) && (bb->start_offset == code_offset)) {
286 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700287 return bb;
288 }
buzbee311ca162013-02-28 15:56:43 -0800289
buzbeeb48819d2013-09-14 16:15:25 -0700290 // No direct hit.
291 if (!create) {
292 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800293 }
294
buzbeeb48819d2013-09-14 16:15:25 -0700295 if (bb != NULL) {
296 // The target exists somewhere in an existing block.
297 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
298 }
299
300 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700301 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
302 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800303 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700304 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800305 return bb;
306}
307
buzbeeb48819d2013-09-14 16:15:25 -0700308
buzbee311ca162013-02-28 15:56:43 -0800309/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700310void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800311 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700312 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800313
314 if (tries_size == 0) {
315 return;
316 }
317
318 for (int i = 0; i < tries_size; i++) {
319 const DexFile::TryItem* pTry =
320 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700321 DexOffset start_offset = pTry->start_addr_;
322 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800323 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700324 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800325 }
326 }
327
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700328 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800329 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
330 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
331 for (uint32_t idx = 0; idx < handlers_size; idx++) {
332 CatchHandlerIterator iterator(handlers_ptr);
333 for (; iterator.HasNext(); iterator.Next()) {
334 uint32_t address = iterator.GetHandlerAddress();
335 FindBlock(address, false /* split */, true /*create*/,
336 /* immed_pred_block_p */ NULL);
337 }
338 handlers_ptr = iterator.EndDataPointer();
339 }
340}
341
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100342bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
343 NarrowDexOffset catch_offset) {
344 // Catches for monitor-exit during stack unwinding have the pattern
345 // move-exception (move)* (goto)? monitor-exit throw
346 // In the currently generated dex bytecode we see these catching a bytecode range including
347 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
348 // it's the case for a given monitor-exit and catch block so that we can ignore it.
349 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
350 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
351 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700352 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100353 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
354 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700355 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100356 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
357 if (check_insn->VRegA_11x() == monitor_reg) {
358 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
359 return false;
360 }
361 check_insn = check_insn->Next();
362 while (true) {
363 int dest = -1;
364 bool wide = false;
365 switch (check_insn->Opcode()) {
366 case Instruction::MOVE_WIDE:
367 wide = true;
368 // Intentional fall-through.
369 case Instruction::MOVE_OBJECT:
370 case Instruction::MOVE:
371 dest = check_insn->VRegA_12x();
372 break;
373
374 case Instruction::MOVE_WIDE_FROM16:
375 wide = true;
376 // Intentional fall-through.
377 case Instruction::MOVE_OBJECT_FROM16:
378 case Instruction::MOVE_FROM16:
379 dest = check_insn->VRegA_22x();
380 break;
381
382 case Instruction::MOVE_WIDE_16:
383 wide = true;
384 // Intentional fall-through.
385 case Instruction::MOVE_OBJECT_16:
386 case Instruction::MOVE_16:
387 dest = check_insn->VRegA_32x();
388 break;
389
390 case Instruction::GOTO:
391 case Instruction::GOTO_16:
392 case Instruction::GOTO_32:
393 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
394 // Intentional fall-through.
395 default:
396 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
397 check_insn->VRegA_11x() == monitor_reg;
398 }
399
400 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
401 return false;
402 }
403
404 check_insn = check_insn->Next();
405 }
406}
407
buzbee311ca162013-02-28 15:56:43 -0800408/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700409BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
410 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700411 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700412 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800413 switch (insn->dalvikInsn.opcode) {
414 case Instruction::GOTO:
415 case Instruction::GOTO_16:
416 case Instruction::GOTO_32:
417 target += insn->dalvikInsn.vA;
418 break;
419 case Instruction::IF_EQ:
420 case Instruction::IF_NE:
421 case Instruction::IF_LT:
422 case Instruction::IF_GE:
423 case Instruction::IF_GT:
424 case Instruction::IF_LE:
425 cur_block->conditional_branch = true;
426 target += insn->dalvikInsn.vC;
427 break;
428 case Instruction::IF_EQZ:
429 case Instruction::IF_NEZ:
430 case Instruction::IF_LTZ:
431 case Instruction::IF_GEZ:
432 case Instruction::IF_GTZ:
433 case Instruction::IF_LEZ:
434 cur_block->conditional_branch = true;
435 target += insn->dalvikInsn.vB;
436 break;
437 default:
438 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
439 }
buzbeeb48819d2013-09-14 16:15:25 -0700440 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700441 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800442 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700443 cur_block->taken = taken_block->id;
444 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800445
446 /* Always terminate the current block for conditional branches */
447 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700448 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800449 /*
450 * If the method is processed
451 * in sequential order from the
452 * beginning, we don't need to
453 * specify split for continue
454 * blocks. However, this
455 * routine can be called by
456 * compileLoop, which starts
457 * parsing the method from an
458 * arbitrary address in the
459 * method body.
460 */
461 true,
462 /* create */
463 true,
464 /* immed_pred_block_p */
465 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700466 cur_block->fall_through = fallthrough_block->id;
467 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800468 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700469 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800470 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800471 }
472 return cur_block;
473}
474
475/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800476BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
477 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800478 const uint16_t* switch_data =
479 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
480 int size;
481 const int* keyTable;
482 const int* target_table;
483 int i;
484 int first_key;
485
486 /*
487 * Packed switch data format:
488 * ushort ident = 0x0100 magic value
489 * ushort size number of entries in the table
490 * int first_key first (and lowest) switch case value
491 * int targets[size] branch targets, relative to switch opcode
492 *
493 * Total size is (4+size*2) 16-bit code units.
494 */
495 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
496 DCHECK_EQ(static_cast<int>(switch_data[0]),
497 static_cast<int>(Instruction::kPackedSwitchSignature));
498 size = switch_data[1];
499 first_key = switch_data[2] | (switch_data[3] << 16);
500 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700501 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800502 /*
503 * Sparse switch data format:
504 * ushort ident = 0x0200 magic value
505 * ushort size number of entries in the table; > 0
506 * int keys[size] keys, sorted low-to-high; 32-bit aligned
507 * int targets[size] branch targets, relative to switch opcode
508 *
509 * Total size is (2+size*4) 16-bit code units.
510 */
511 } else {
512 DCHECK_EQ(static_cast<int>(switch_data[0]),
513 static_cast<int>(Instruction::kSparseSwitchSignature));
514 size = switch_data[1];
515 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
516 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700517 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800518 }
519
buzbee0d829482013-10-11 15:24:55 -0700520 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800521 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700522 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800523 }
buzbee0d829482013-10-11 15:24:55 -0700524 cur_block->successor_block_list_type =
525 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
526 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700527 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800528
529 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700530 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800531 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700532 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700533 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000534 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700535 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800536 successor_block_info->key =
537 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
538 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700539 cur_block->successor_blocks->Insert(successor_block_info);
540 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800541 }
542
543 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700544 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
545 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700546 cur_block->fall_through = fallthrough_block->id;
547 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800548 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800549}
550
551/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700552BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
553 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700554 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700555 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800556 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
557 bool build_all_edges =
558 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800559
560 /* In try block */
561 if (in_try_block) {
562 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
563
buzbee0d829482013-10-11 15:24:55 -0700564 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800565 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
566 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700567 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800568 }
569
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700570 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700571 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800572 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100573 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
574 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
575 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
576 continue;
577 }
578 if (cur_block->successor_block_list_type == kNotUsed) {
579 cur_block->successor_block_list_type = kCatch;
580 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
581 arena_, 2, kGrowableArraySuccessorBlocks);
582 }
buzbee311ca162013-02-28 15:56:43 -0800583 catch_block->catch_entry = true;
584 if (kIsDebugBuild) {
585 catches_.insert(catch_block->start_offset);
586 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700587 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000588 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700589 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800590 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700591 cur_block->successor_blocks->Insert(successor_block_info);
592 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800593 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100594 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
595 }
596 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700597 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700598 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700599 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800600 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700601 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800602 }
603
buzbee17189ac2013-11-08 11:07:02 -0800604 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800605 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700606 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700607 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800608 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
609 /* immed_pred_block_p */ NULL);
610 }
611 if (!in_try_block) {
612 // Don't split a THROW that can't rethrow - we're done.
613 return cur_block;
614 }
615 }
616
buzbee17189ac2013-11-08 11:07:02 -0800617 if (!build_all_edges) {
618 /*
619 * Even though there is an exception edge here, control cannot return to this
620 * method. Thus, for the purposes of dataflow analysis and optimization, we can
621 * ignore the edge. Doing this reduces compile time, and increases the scope
622 * of the basic-block level optimization pass.
623 */
624 return cur_block;
625 }
626
buzbee311ca162013-02-28 15:56:43 -0800627 /*
628 * Split the potentially-throwing instruction into two parts.
629 * The first half will be a pseudo-op that captures the exception
630 * edges and terminates the basic block. It always falls through.
631 * Then, create a new basic block that begins with the throwing instruction
632 * (minus exceptions). Note: this new basic block must NOT be entered into
633 * the block_map. If the potentially-throwing instruction is the target of a
634 * future branch, we need to find the check psuedo half. The new
635 * basic block containing the work portion of the instruction should
636 * only be entered via fallthrough from the block containing the
637 * pseudo exception edge MIR. Note also that this new block is
638 * not automatically terminated after the work portion, and may
639 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700640 *
641 * Note also that the dex_pc_to_block_map_ entry for the potentially
642 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800643 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700644 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700645 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800646 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700647 cur_block->fall_through = new_block->id;
648 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700649 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800650 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700651 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700652 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800653 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700654 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800655 return new_block;
656}
657
658/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
659void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700660 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700661 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800662 current_code_item_ = code_item;
663 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
664 current_method_ = m_units_.size();
665 current_offset_ = 0;
666 // TODO: will need to snapshot stack image and use that as the mir context identification.
667 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000668 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
669 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800670 const uint16_t* code_ptr = current_code_item_->insns_;
671 const uint16_t* code_end =
672 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
673
674 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700675 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700676 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700677 dex_pc_to_block_map_.SetSize(dex_pc_to_block_map_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700678
buzbee311ca162013-02-28 15:56:43 -0800679 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700680 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
681 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800682
683 // If this is the first method, set up default entry and exit blocks.
684 if (current_method_ == 0) {
685 DCHECK(entry_block_ == NULL);
686 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700687 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700688 // Use id 0 to represent a null block.
689 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
690 DCHECK_EQ(null_block->id, NullBasicBlockId);
691 null_block->hidden = true;
692 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700693 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700694 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700695 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700696 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800697 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
698 cu_->dex_file = &dex_file;
699 cu_->class_def_idx = class_def_idx;
700 cu_->method_idx = method_idx;
701 cu_->access_flags = access_flags;
702 cu_->invoke_type = invoke_type;
703 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
704 cu_->num_ins = current_code_item_->ins_size_;
705 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
706 cu_->num_outs = current_code_item_->outs_size_;
707 cu_->num_dalvik_registers = current_code_item_->registers_size_;
708 cu_->insns = current_code_item_->insns_;
709 cu_->code_item = current_code_item_;
710 } else {
711 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
712 /*
713 * Will need to manage storage for ins & outs, push prevous state and update
714 * insert point.
715 */
716 }
717
718 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700719 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700720 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800721 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700722 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700723 // TODO: for inlining support, insert at the insert point rather than entry block.
724 entry_block_->fall_through = cur_block->id;
725 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800726
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000727 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800728 ProcessTryCatchBlocks();
729
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000730 uint64_t merged_df_flags = 0u;
731
buzbee311ca162013-02-28 15:56:43 -0800732 /* Parse all instructions and put them into containing basic blocks */
733 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700734 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800735 insn->offset = current_offset_;
736 insn->m_unit_index = current_method_;
737 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800738 Instruction::Code opcode = insn->dalvikInsn.opcode;
739 if (opcode_count_ != NULL) {
740 opcode_count_[static_cast<int>(opcode)]++;
741 }
742
buzbee311ca162013-02-28 15:56:43 -0800743 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800744 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800745
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700746 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000747 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800748
749 if (df_flags & DF_HAS_DEFS) {
750 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
751 }
752
buzbee1da1e2f2013-11-15 13:37:01 -0800753 if (df_flags & DF_LVN) {
754 cur_block->use_lvn = true; // Run local value numbering on this basic block.
755 }
756
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700757 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700758 if (opcode == Instruction::NOP) {
759 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
760 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
761 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
762 uint16_t following_raw_instruction = code_ptr[1];
763 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
764 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
765 (following_raw_instruction == Instruction::kArrayDataSignature)) {
766 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
767 }
768 }
769 if (width == 1) {
770 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700771 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700772 } else {
buzbee0d829482013-10-11 15:24:55 -0700773 DCHECK(cur_block->fall_through == NullBasicBlockId);
774 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700775 // Unreachable instruction, mark for no continuation.
776 flags &= ~Instruction::kContinue;
777 }
778 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700779 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700780 }
781
buzbeeb48819d2013-09-14 16:15:25 -0700782 // Associate the starting dex_pc for this opcode with its containing basic block.
783 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
784
buzbee27247762013-07-28 12:03:58 -0700785 code_ptr += width;
786
buzbee311ca162013-02-28 15:56:43 -0800787 if (flags & Instruction::kBranch) {
788 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
789 width, flags, code_ptr, code_end);
790 } else if (flags & Instruction::kReturn) {
791 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700792 cur_block->fall_through = exit_block_->id;
793 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800794 /*
795 * Terminate the current block if there are instructions
796 * afterwards.
797 */
798 if (code_ptr < code_end) {
799 /*
800 * Create a fallthrough block for real instructions
801 * (incl. NOP).
802 */
buzbee27247762013-07-28 12:03:58 -0700803 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
804 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800805 }
806 } else if (flags & Instruction::kThrow) {
807 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
808 code_ptr, code_end);
809 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800810 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800811 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700812 if (verify_flags & Instruction::kVerifyVarArgRange ||
813 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800814 /*
815 * The Quick backend's runtime model includes a gap between a method's
816 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
817 * which spans the gap is somewhat complicated, and should not happen
818 * in normal usage of dx. Punt to the interpreter.
819 */
820 int first_reg_in_range = insn->dalvikInsn.vC;
821 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
822 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
823 punt_to_interpreter_ = true;
824 }
825 }
buzbee311ca162013-02-28 15:56:43 -0800826 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700827 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800828 false, /* immed_pred_block_p */ NULL);
829 if (next_block) {
830 /*
831 * The next instruction could be the target of a previously parsed
832 * forward branch so a block is already created. If the current
833 * instruction is not an unconditional branch, connect them through
834 * the fall-through link.
835 */
buzbee0d829482013-10-11 15:24:55 -0700836 DCHECK(cur_block->fall_through == NullBasicBlockId ||
837 GetBasicBlock(cur_block->fall_through) == next_block ||
838 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800839
buzbee0d829482013-10-11 15:24:55 -0700840 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
841 cur_block->fall_through = next_block->id;
842 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800843 }
844 cur_block = next_block;
845 }
846 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000847 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000848
buzbee311ca162013-02-28 15:56:43 -0800849 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
850 DumpCFG("/sdcard/1_post_parse_cfg/", true);
851 }
852
853 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700854 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800855 }
856}
857
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700858void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800859 DCHECK(opcode_count_ != NULL);
860 LOG(INFO) << "Opcode Count";
861 for (int i = 0; i < kNumPackedOpcodes; i++) {
862 if (opcode_count_[i] != 0) {
863 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
864 << " " << opcode_count_[i];
865 }
866 }
867}
868
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700869uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
870 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
871 return oat_data_flow_attributes_[opcode];
872}
873
874uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
875 DCHECK(mir != nullptr);
876 Instruction::Code opcode = mir->dalvikInsn.opcode;
877 return GetDataFlowAttributes(opcode);
878}
879
buzbee311ca162013-02-28 15:56:43 -0800880// TODO: use a configurable base prefix, and adjust callers to supply pass name.
881/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800882void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800883 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700884 static AtomicInteger cnt(0);
885
886 // Increment counter to get a unique file number.
887 cnt++;
888
buzbee311ca162013-02-28 15:56:43 -0800889 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
890 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700891 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800892 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700893 suffix == nullptr ? "" : suffix,
894 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800895 file = fopen(fname.c_str(), "w");
896 if (file == NULL) {
897 return;
898 }
899 fprintf(file, "digraph G {\n");
900
901 fprintf(file, " rankdir=TB\n");
902
903 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
904 int idx;
905
906 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700907 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700908 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700909 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800910 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700911 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800912 if (bb->block_type == kEntryBlock) {
913 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
914 } else if (bb->block_type == kExitBlock) {
915 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
916 } else if (bb->block_type == kDalvikByteCode) {
917 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
918 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700919 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800920 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
921 bb->first_mir_insn ? " | " : " ");
922 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
923 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400924 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
925 if (opcode == kMirOpConstVector) {
926 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
927 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
928 mir->dalvikInsn.vA,
929 mir->dalvikInsn.vB,
930 mir->dalvikInsn.arg[0],
931 mir->dalvikInsn.arg[1],
932 mir->dalvikInsn.arg[2],
933 mir->dalvikInsn.arg[3],
934 mir->next ? " | " : " ");
935 } else {
936 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
937 extended_mir_op_names_[opcode - kMirOpFirst],
938 mir->dalvikInsn.vA,
939 mir->dalvikInsn.vB,
940 mir->dalvikInsn.vC,
941 mir->next ? " | " : " ");
942 }
943 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700944 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400945 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700946 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
947 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400948 extended_mir_op_names_[opcode - kMirOpFirst],
949 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
950 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700951 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400952 mir->next ? " | " : " ");
953 }
buzbee311ca162013-02-28 15:56:43 -0800954 }
955 fprintf(file, " }\"];\n\n");
956 } else if (bb->block_type == kExceptionHandling) {
957 char block_name[BLOCK_NAME_LEN];
958
959 GetBlockName(bb, block_name);
960 fprintf(file, " %s [shape=invhouse];\n", block_name);
961 }
962
963 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
964
buzbee0d829482013-10-11 15:24:55 -0700965 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800966 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700967 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800968 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
969 block_name1, block_name2);
970 }
buzbee0d829482013-10-11 15:24:55 -0700971 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800972 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700973 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800974 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
975 }
976
buzbee0d829482013-10-11 15:24:55 -0700977 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800978 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
979 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700980 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
981 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700982 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800983
984 int succ_id = 0;
985 while (true) {
986 if (successor_block_info == NULL) break;
987
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700988 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700989 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800990
991 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
992 succ_id++,
993 successor_block_info->key,
994 dest_block->start_offset,
995 (next_successor_block_info != NULL) ? " | " : " ");
996
997 successor_block_info = next_successor_block_info;
998 }
999 fprintf(file, " }\"];\n\n");
1000
1001 GetBlockName(bb, block_name1);
1002 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1003 block_name1, bb->start_offset, bb->id);
1004
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001005 // Link the successor pseudo-block with all of its potential targets.
1006 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001007
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001008 succ_id = 0;
1009 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001010 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001011 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001012
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001013 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001014
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001015 GetBlockName(dest_block, block_name2);
1016 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1017 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001018 }
1019 }
1020 fprintf(file, "\n");
1021
1022 if (cu_->verbose) {
1023 /* Display the dominator tree */
1024 GetBlockName(bb, block_name1);
1025 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1026 block_name1, block_name1);
1027 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001028 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001029 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1030 }
1031 }
1032 }
1033 fprintf(file, "}\n");
1034 fclose(file);
1035}
1036
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001037/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001038void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001039 // Insert it after the last MIR.
1040 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001041}
1042
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001043void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1044 // Insert it after the last MIR.
1045 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1046}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001047
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001048void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1049 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1050 MIR* new_mir = *it;
1051
1052 // Add a copy of each MIR.
1053 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1054 }
buzbee1fd33462013-03-25 13:40:45 -07001055}
1056
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001057/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001058void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001059 InsertMIRListAfter(current_mir, new_mir, new_mir);
1060}
buzbee1fd33462013-03-25 13:40:45 -07001061
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001062void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1063 // If no MIR, we are done.
1064 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1065 return;
buzbee1fd33462013-03-25 13:40:45 -07001066 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001067
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001068 // If insert_after is null, assume BB is empty.
1069 if (insert_after == nullptr) {
1070 first_mir_insn = first_list_mir;
1071 last_mir_insn = last_list_mir;
1072 last_list_mir->next = nullptr;
1073 } else {
1074 MIR* after_list = insert_after->next;
1075 insert_after->next = first_list_mir;
1076 last_list_mir->next = after_list;
1077 if (after_list == nullptr) {
1078 last_mir_insn = last_list_mir;
1079 }
1080 }
1081
1082 // Set this BB to be the basic block of the MIRs.
1083 MIR* last = last_list_mir->next;
1084 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1085 mir->bb = id;
1086 }
1087}
1088
1089/* Insert an MIR instruction to the head of a basic block. */
1090void BasicBlock::PrependMIR(MIR* mir) {
1091 InsertMIRListBefore(first_mir_insn, mir, mir);
1092}
1093
1094void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1095 // Insert it before the first MIR.
1096 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1097}
1098
1099void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1100 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1101 MIR* mir = *it;
1102
1103 InsertMIRListBefore(first_mir_insn, mir, mir);
1104 }
1105}
1106
1107/* Insert a MIR instruction before the specified MIR. */
1108void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1109 // Insert as a single element list.
1110 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001111}
1112
1113MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1114 MIR* current = first_mir_insn;
1115
1116 while (current != nullptr) {
1117 MIR* next = current->next;
1118
1119 if (next == mir) {
1120 return current;
1121 }
1122
1123 current = next;
1124 }
1125
1126 return nullptr;
1127}
1128
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001129void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1130 // If no MIR, we are done.
1131 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1132 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001133 }
1134
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001135 // If insert_before is null, assume BB is empty.
1136 if (insert_before == nullptr) {
1137 first_mir_insn = first_list_mir;
1138 last_mir_insn = last_list_mir;
1139 last_list_mir->next = nullptr;
1140 } else {
1141 if (first_mir_insn == insert_before) {
1142 last_list_mir->next = first_mir_insn;
1143 first_mir_insn = first_list_mir;
1144 } else {
1145 // Find the preceding MIR.
1146 MIR* before_list = FindPreviousMIR(insert_before);
1147 DCHECK(before_list != nullptr);
1148 before_list->next = first_list_mir;
1149 last_list_mir->next = insert_before;
1150 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001151 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001152
1153 // Set this BB to be the basic block of the MIRs.
1154 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1155 mir->bb = id;
1156 }
1157}
1158
1159bool BasicBlock::RemoveMIR(MIR* mir) {
1160 // Remove as a single element list.
1161 return RemoveMIRList(mir, mir);
1162}
1163
1164bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1165 if (first_list_mir == nullptr) {
1166 return false;
1167 }
1168
1169 // Try to find the MIR.
1170 MIR* before_list = nullptr;
1171 MIR* after_list = nullptr;
1172
1173 // If we are removing from the beginning of the MIR list.
1174 if (first_mir_insn == first_list_mir) {
1175 before_list = nullptr;
1176 } else {
1177 before_list = FindPreviousMIR(first_list_mir);
1178 if (before_list == nullptr) {
1179 // We did not find the mir.
1180 return false;
1181 }
1182 }
1183
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001184 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001185 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1186 mir->bb = NullBasicBlockId;
1187 }
1188
1189 after_list = last_list_mir->next;
1190
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001191 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001192 if (before_list == nullptr) {
1193 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001194 } else {
1195 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001196 }
1197
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001198 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001199 if (after_list == nullptr) {
1200 last_mir_insn = before_list;
1201 }
1202
1203 return true;
buzbee1fd33462013-03-25 13:40:45 -07001204}
1205
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001206MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001207 MIR* next_mir = nullptr;
1208
1209 if (current != nullptr) {
1210 next_mir = current->next;
1211 }
1212
1213 if (next_mir == nullptr) {
1214 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001215 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1216 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001217 }
1218 }
1219
1220 return next_mir;
1221}
1222
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001223char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001224 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001225 std::string str;
1226 int flags = 0;
1227 int opcode = insn.opcode;
1228 char* ret;
1229 bool nop = false;
1230 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001231 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001232
1233 // Handle special cases.
1234 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1235 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1236 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001237 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001238 insn = mir->meta.throw_insn->dalvikInsn;
1239 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001240 opcode = insn.opcode;
1241 } else if (opcode == kMirOpNop) {
1242 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001243 // Recover original opcode.
1244 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1245 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001246 nop = true;
1247 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001248 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1249 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001250
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001251 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001252 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1253 } else {
1254 dalvik_format = Instruction::FormatOf(insn.opcode);
1255 flags = Instruction::FlagsOf(insn.opcode);
1256 str.append(Instruction::Name(insn.opcode));
1257 }
1258
1259 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001260 BasicBlockId* incoming = mir->meta.phi_incoming;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001261 if (defs > 0 && uses > 0) {
1262 str.append(StringPrintf(" %s = (%s",
1263 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1264 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1265 str.append(StringPrintf(":%d", incoming[0]));
1266 int i;
1267 for (i = 1; i < uses; i++) {
1268 str.append(StringPrintf(", %s:%d",
1269 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1270 incoming[i]));
1271 }
1272 str.append(")");
1273 } else {
1274 str.append(StringPrintf(" v%d", mir->dalvikInsn.vA));
buzbee1fd33462013-03-25 13:40:45 -07001275 }
buzbee1fd33462013-03-25 13:40:45 -07001276 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001277 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001278 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1279 (dalvik_format == Instruction::k3rc));
1280 if (defs != 0) {
1281 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1282 if (uses != 0) {
1283 str.append(", ");
1284 }
1285 }
1286 for (int i = 0; i < uses; i++) {
1287 str.append(
1288 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1289 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1290 // For the listing, skip the high sreg.
1291 i++;
1292 }
1293 if (i != (uses -1)) {
1294 str.append(",");
1295 }
1296 }
1297 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001298 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001299 case Instruction::k21s:
1300 case Instruction::k31i:
1301 case Instruction::k21h:
1302 str.append(StringPrintf(", #%d", insn.vB));
1303 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001304 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001305 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001306 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001307 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001308 case Instruction::k31c:
1309 str.append(StringPrintf(", index #%d", insn.vB));
1310 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001311 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001312 str.append(StringPrintf(", index #%d", insn.vC));
1313 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001314 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001315 case Instruction::k22b:
1316 str.append(StringPrintf(", #%d", insn.vC));
1317 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001318 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001319 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001320 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001321 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001322 if ((flags & Instruction::kBranch) != 0) {
1323 // For branches, decode the instructions to print out the branch targets.
1324 int offset = 0;
1325 switch (dalvik_format) {
1326 case Instruction::k21t:
1327 offset = insn.vB;
1328 break;
1329 case Instruction::k22t:
1330 offset = insn.vC;
1331 break;
1332 case Instruction::k10t:
1333 case Instruction::k20t:
1334 case Instruction::k30t:
1335 offset = insn.vA;
1336 break;
1337 default:
1338 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1339 }
1340 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1341 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1342 }
buzbee1fd33462013-03-25 13:40:45 -07001343 }
1344 if (nop) {
1345 str.append("]--optimized away");
1346 }
1347 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001348 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001349 strncpy(ret, str.c_str(), length);
1350 return ret;
1351}
1352
1353/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001354void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001355 static const struct { const char before; const char after; } match[] = {
1356 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1357 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1358 };
buzbee1fd33462013-03-25 13:40:45 -07001359 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1360 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1361 }
1362}
1363
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001364std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001365 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1366 // the arena. We should be smarter and just place straight into the arena, or compute the
1367 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001368 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1369}
1370
1371// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001372std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001373 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001374 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001375 return GetSSAName(ssa_reg);
1376 }
1377 if (IsConst(reg_location_[ssa_reg])) {
1378 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001379 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001380 ConstantValueWide(reg_location_[ssa_reg]));
1381 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001382 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001383 ConstantValue(reg_location_[ssa_reg]));
1384 }
1385 } else {
1386 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1387 }
1388}
1389
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001390void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001391 switch (bb->block_type) {
1392 case kEntryBlock:
1393 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1394 break;
1395 case kExitBlock:
1396 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1397 break;
1398 case kDalvikByteCode:
1399 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1400 break;
1401 case kExceptionHandling:
1402 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1403 bb->id);
1404 break;
1405 default:
1406 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1407 break;
1408 }
1409}
1410
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001411const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001412 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001413 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1414 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1415}
1416
1417/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001418void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001419 BasicBlock* bb;
1420 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001421 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001422 "Entry Block",
1423 "Code Block",
1424 "Exit Block",
1425 "Exception Handling",
1426 "Catch Block"
1427 };
1428
1429 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1430 LOG(INFO) << cu_->insns << " insns";
1431 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001432 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001433
1434 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001435 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001436 if (bb == NULL) break;
1437 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1438 bb->id,
1439 block_type_names[bb->block_type],
1440 bb->start_offset,
1441 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1442 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001443 if (bb->taken != NullBasicBlockId) {
1444 LOG(INFO) << " Taken branch: block " << bb->taken
1445 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001446 }
buzbee0d829482013-10-11 15:24:55 -07001447 if (bb->fall_through != NullBasicBlockId) {
1448 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1449 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001450 }
1451 }
1452}
1453
1454/*
1455 * Build an array of location records for the incoming arguments.
1456 * Note: one location record per word of arguments, with dummy
1457 * high-word loc for wide arguments. Also pull up any following
1458 * MOVE_RESULT and incorporate it into the invoke.
1459 */
1460CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001461 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001462 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001463 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001464 MIR* move_result_mir = FindMoveResult(bb, mir);
1465 if (move_result_mir == NULL) {
1466 info->result.location = kLocInvalid;
1467 } else {
1468 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001469 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1470 }
1471 info->num_arg_words = mir->ssa_rep->num_uses;
1472 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001473 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001474 for (int i = 0; i < info->num_arg_words; i++) {
1475 info->args[i] = GetRawSrc(mir, i);
1476 }
1477 info->opt_flags = mir->optimization_flags;
1478 info->type = type;
1479 info->is_range = is_range;
1480 info->index = mir->dalvikInsn.vB;
1481 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001482 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001483 return info;
1484}
1485
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001486// Allocate a new MIR.
1487MIR* MIRGraph::NewMIR() {
1488 MIR* mir = new (arena_) MIR();
1489 return mir;
1490}
1491
buzbee862a7602013-04-05 10:58:54 -07001492// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001493BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001494 BasicBlock* bb = new (arena_) BasicBlock();
1495
buzbee862a7602013-04-05 10:58:54 -07001496 bb->block_type = block_type;
1497 bb->id = block_id;
1498 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001499 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001500 (block_type == kExitBlock) ? 2048 : 2,
1501 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001502 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001503 block_id_map_.Put(block_id, block_id);
1504 return bb;
1505}
buzbee1fd33462013-03-25 13:40:45 -07001506
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001507void MIRGraph::InitializeConstantPropagation() {
1508 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001509 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001510}
1511
1512void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001513 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001514 int num_ssa_regs = GetNumSSARegs();
1515 use_counts_.Resize(num_ssa_regs + 32);
1516 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001517 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001518 for (int i = 0; i < num_ssa_regs; i++) {
1519 use_counts_.Insert(0);
1520 raw_use_counts_.Insert(0);
1521 }
1522}
1523
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001524void MIRGraph::SSATransformationStart() {
1525 DCHECK(temp_scoped_alloc_.get() == nullptr);
1526 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1527 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1528 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1529 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1530
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001531 // Update the maximum number of reachable blocks.
1532 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001533}
1534
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001535void MIRGraph::SSATransformationEnd() {
1536 // Verify the dataflow information after the pass.
1537 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1538 VerifyDataflow();
1539 }
1540
1541 temp_bit_vector_size_ = 0u;
1542 temp_bit_vector_ = nullptr;
1543 DCHECK(temp_scoped_alloc_.get() != nullptr);
1544 temp_scoped_alloc_.reset();
1545}
1546
Vladimir Marko55fff042014-07-10 12:42:52 +01001547static BasicBlock* SelectTopologicalSortOrderFallBack(
1548 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1549 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1550 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1551 // No true loop head has been found but there may be true loop heads after the mess we need
1552 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1553 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1554 BasicBlock* fall_back = nullptr;
1555 size_t fall_back_num_reachable = 0u;
1556 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1557 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1558 AllNodesIterator iter(mir_graph);
1559 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1560 if (candidate->hidden || // Hidden, or
1561 candidate->visited || // already processed, or
1562 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1563 (current_loop != nullptr && // outside current loop.
1564 !current_loop->IsBitSet(candidate->id))) {
1565 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001566 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001567 DCHECK(tmp_stack->empty());
1568 tmp_stack->push_back(candidate->id);
1569 candidate_reachable.ClearAllBits();
1570 size_t num_reachable = 0u;
1571 while (!tmp_stack->empty()) {
1572 BasicBlockId current_id = tmp_stack->back();
1573 tmp_stack->pop_back();
1574 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1575 DCHECK(current_bb != nullptr);
1576 ChildBlockIterator child_iter(current_bb, mir_graph);
1577 BasicBlock* child_bb = child_iter.Next();
1578 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1579 DCHECK(!child_bb->hidden);
1580 if (child_bb->visited || // Already processed, or
1581 (current_loop != nullptr && // outside current loop.
1582 !current_loop->IsBitSet(child_bb->id))) {
1583 continue;
1584 }
1585 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1586 candidate_reachable.SetBit(child_bb->id);
1587 tmp_stack->push_back(child_bb->id);
1588 num_reachable += 1u;
1589 }
1590 }
1591 }
1592 if (fall_back_num_reachable < num_reachable) {
1593 fall_back_num_reachable = num_reachable;
1594 fall_back = candidate;
1595 }
1596 }
1597 return fall_back;
1598}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001599
Vladimir Marko55fff042014-07-10 12:42:52 +01001600// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1601static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1602 ArenaBitVector* reachable,
1603 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1604 // NOTE: Loop heads indicated by the "visited" flag.
1605 DCHECK(tmp_stack->empty());
1606 reachable->ClearAllBits();
1607 tmp_stack->push_back(bb_id);
1608 while (!tmp_stack->empty()) {
1609 BasicBlockId current_id = tmp_stack->back();
1610 tmp_stack->pop_back();
1611 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1612 DCHECK(current_bb != nullptr);
1613 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1614 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1615 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1616 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1617 reachable->SetBit(pred_bb->id);
1618 tmp_stack->push_back(pred_bb->id);
1619 }
1620 }
1621 }
1622}
1623
1624void MIRGraph::ComputeTopologicalSortOrder() {
1625 ScopedArenaAllocator allocator(&cu_->arena_stack);
1626 unsigned int num_blocks = GetNumBlocks();
1627
1628 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1629 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1630 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1631 size_t max_nested_loops = 0u;
1632 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1633 loop_exit_blocks.ClearAllBits();
1634
1635 // Count the number of blocks to process and add the entry block(s).
1636 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1637 unsigned int num_blocks_to_process = 0u;
1638 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001639 if (bb->hidden == true) {
1640 continue;
1641 }
1642
Vladimir Marko55fff042014-07-10 12:42:52 +01001643 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001644
Vladimir Marko55fff042014-07-10 12:42:52 +01001645 if (bb->predecessors->Size() == 0u) {
1646 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001647 q.push(bb);
1648 }
1649 }
1650
Vladimir Marko55fff042014-07-10 12:42:52 +01001651 // Create the topological order if need be.
1652 if (topological_order_ == nullptr) {
1653 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1654 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1655 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1656 }
1657 topological_order_->Reset();
1658 topological_order_loop_ends_->Reset();
1659 topological_order_indexes_->Reset();
1660 topological_order_loop_ends_->Resize(num_blocks);
1661 topological_order_indexes_->Resize(num_blocks);
1662 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1663 topological_order_loop_ends_->Insert(0u);
1664 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1665 }
1666
1667 // Mark all blocks as unvisited.
1668 ClearAllVisitedFlags();
1669
1670 // For loop heads, keep track from which blocks they are reachable not going through other
1671 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1672 // in this set go into the loop body, the other children are jumping over the loop.
1673 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1674 loop_head_reachable_from.resize(num_blocks, nullptr);
1675 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1676 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1677
1678 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001679 BasicBlock* bb = nullptr;
1680 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001681 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001682 // Get top.
1683 bb = q.front();
1684 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001685 if (bb->visited) {
1686 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1687 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1688 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1689 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1690 DCHECK_EQ(loop_head_stack.back(), bb->id);
1691 loop_head_stack.pop_back();
1692 ArenaBitVector* reachable =
1693 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1694 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1695 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1696 q.push(GetBasicBlock(candidate_id));
1697 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1698 // so clearing the bit has no effect on the iterator.
1699 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001700 }
1701 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001702 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001703 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001704 } else {
1705 // Find the new loop head.
1706 AllNodesIterator iter(this);
1707 while (true) {
1708 BasicBlock* candidate = iter.Next();
1709 if (candidate == nullptr) {
1710 // We did not find a true loop head, fall back to a reachable block in any loop.
1711 ArenaBitVector* current_loop =
1712 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1713 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1714 &allocator, &tmp_stack);
1715 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1716 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1717 LOG(INFO) << "Topological sort order: Using fall-back in "
1718 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1719 << " @0x" << std::hex << bb->start_offset
1720 << ", num_blocks = " << std::dec << num_blocks;
1721 }
1722 break;
1723 }
1724 if (candidate->hidden || // Hidden, or
1725 candidate->visited || // already processed, or
1726 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1727 (!loop_head_stack.empty() && // outside current loop.
1728 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1729 continue;
1730 }
1731
1732 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1733 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1734 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1735 if (pred_bb != candidate && !pred_bb->visited &&
1736 !pred_bb->dominators->IsBitSet(candidate->id)) {
1737 break; // Keep non-null pred_bb to indicate failure.
1738 }
1739 }
1740 if (pred_bb == nullptr) {
1741 bb = candidate;
1742 break;
1743 }
1744 }
1745 // Compute blocks from which the loop head is reachable and process those blocks first.
1746 ArenaBitVector* reachable =
1747 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1748 loop_head_reachable_from[bb->id] = reachable;
1749 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1750 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1751 loop_head_stack.push_back(bb->id);
1752 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001753 }
1754
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001755 DCHECK_EQ(bb->hidden, false);
1756 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001757 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001758
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001759 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001760 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1761 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001762 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001763
Vladimir Marko55fff042014-07-10 12:42:52 +01001764 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001765 ChildBlockIterator succIter(bb, this);
1766 BasicBlock* successor = succIter.Next();
1767 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001768 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001769 continue;
1770 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001771
Vladimir Marko55fff042014-07-10 12:42:52 +01001772 // One more predecessor was visited.
1773 visited_cnt_values[successor->id] += 1u;
1774 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1775 if (loop_head_stack.empty() ||
1776 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1777 q.push(successor);
1778 } else {
1779 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1780 loop_exit_blocks.SetBit(successor->id);
1781 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001782 }
1783 }
1784 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001785
1786 // Prepare the loop head stack for iteration.
1787 topological_order_loop_head_stack_ =
1788 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001789}
1790
1791bool BasicBlock::IsExceptionBlock() const {
1792 if (block_type == kExceptionHandling) {
1793 return true;
1794 }
1795 return false;
1796}
1797
Wei Jin04f4d8a2014-05-29 18:04:29 -07001798bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1799 BasicBlock* target = GetBasicBlock(target_id);
1800
1801 if (source == nullptr || target == nullptr)
1802 return false;
1803
1804 int idx;
1805 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1806 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1807 if (bb == source)
1808 return true; // The block has been inserted by a suspend check before.
1809 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1810 return true;
1811 }
1812
1813 return false;
1814}
1815
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001816ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1817 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1818 visited_taken_(false), have_successors_(false) {
1819 // Check if we actually do have successors.
1820 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1821 have_successors_ = true;
1822 successor_iter_.Reset(basic_block_->successor_blocks);
1823 }
1824}
1825
1826BasicBlock* ChildBlockIterator::Next() {
1827 // We check if we have a basic block. If we don't we cannot get next child.
1828 if (basic_block_ == nullptr) {
1829 return nullptr;
1830 }
1831
1832 // If we haven't visited fallthrough, return that.
1833 if (visited_fallthrough_ == false) {
1834 visited_fallthrough_ = true;
1835
1836 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1837 if (result != nullptr) {
1838 return result;
1839 }
1840 }
1841
1842 // If we haven't visited taken, return that.
1843 if (visited_taken_ == false) {
1844 visited_taken_ = true;
1845
1846 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1847 if (result != nullptr) {
1848 return result;
1849 }
1850 }
1851
1852 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1853 if (have_successors_ == true) {
1854 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07001855 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1856 successor_block_info != nullptr;
1857 successor_block_info = successor_iter_.Next()) {
1858 // If block was replaced by zero block, take next one.
1859 if (successor_block_info->block != NullBasicBlockId) {
1860 return mir_graph_->GetBasicBlock(successor_block_info->block);
1861 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001862 }
1863 }
1864
1865 // We do not have anything.
1866 return nullptr;
1867}
1868
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001869BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1870 MIRGraph* mir_graph = c_unit->mir_graph.get();
1871 return Copy(mir_graph);
1872}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001873
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001874BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1875 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001876
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001877 // We don't do a memcpy style copy here because it would lead to a lot of things
1878 // to clean up. Let us do it by hand instead.
1879 // Copy in taken and fallthrough.
1880 result_bb->fall_through = fall_through;
1881 result_bb->taken = taken;
1882
1883 // Copy successor links if needed.
1884 ArenaAllocator* arena = mir_graph->GetArena();
1885
1886 result_bb->successor_block_list_type = successor_block_list_type;
1887 if (result_bb->successor_block_list_type != kNotUsed) {
1888 size_t size = successor_blocks->Size();
1889 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1890 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1891 while (true) {
1892 SuccessorBlockInfo* sbi_old = iterator.Next();
1893 if (sbi_old == nullptr) {
1894 break;
1895 }
1896 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1897 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1898 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001899 }
1900 }
1901
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001902 // Copy offset, method.
1903 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001904
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001905 // Now copy instructions.
1906 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1907 // Get a copy first.
1908 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001909
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001910 // Append it.
1911 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001912 }
1913
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001914 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001915}
1916
1917MIR* MIR::Copy(MIRGraph* mir_graph) {
1918 MIR* res = mir_graph->NewMIR();
1919 *res = *this;
1920
1921 // Remove links
1922 res->next = nullptr;
1923 res->bb = NullBasicBlockId;
1924 res->ssa_rep = nullptr;
1925
1926 return res;
1927}
1928
1929MIR* MIR::Copy(CompilationUnit* c_unit) {
1930 return Copy(c_unit->mir_graph.get());
1931}
1932
1933uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1934 // Default result.
1935 int res = 0;
1936
1937 // We are basically setting the iputs to their igets counterparts.
1938 switch (opcode) {
1939 case Instruction::IPUT:
1940 case Instruction::IPUT_OBJECT:
1941 case Instruction::IPUT_BOOLEAN:
1942 case Instruction::IPUT_BYTE:
1943 case Instruction::IPUT_CHAR:
1944 case Instruction::IPUT_SHORT:
1945 case Instruction::IPUT_QUICK:
1946 case Instruction::IPUT_OBJECT_QUICK:
1947 case Instruction::APUT:
1948 case Instruction::APUT_OBJECT:
1949 case Instruction::APUT_BOOLEAN:
1950 case Instruction::APUT_BYTE:
1951 case Instruction::APUT_CHAR:
1952 case Instruction::APUT_SHORT:
1953 case Instruction::SPUT:
1954 case Instruction::SPUT_OBJECT:
1955 case Instruction::SPUT_BOOLEAN:
1956 case Instruction::SPUT_BYTE:
1957 case Instruction::SPUT_CHAR:
1958 case Instruction::SPUT_SHORT:
1959 // Skip the VR containing what to store.
1960 res = 1;
1961 break;
1962 case Instruction::IPUT_WIDE:
1963 case Instruction::IPUT_WIDE_QUICK:
1964 case Instruction::APUT_WIDE:
1965 case Instruction::SPUT_WIDE:
1966 // Skip the two VRs containing what to store.
1967 res = 2;
1968 break;
1969 default:
1970 // Do nothing in the general case.
1971 break;
1972 }
1973
1974 return res;
1975}
1976
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001977/**
1978 * @brief Given a decoded instruction, it checks whether the instruction
1979 * sets a constant and if it does, more information is provided about the
1980 * constant being set.
1981 * @param ptr_value pointer to a 64-bit holder for the constant.
1982 * @param wide Updated by function whether a wide constant is being set by bytecode.
1983 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1984 */
1985bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1986 bool sets_const = true;
1987 int64_t value = vB;
1988
1989 DCHECK(ptr_value != nullptr);
1990 DCHECK(wide != nullptr);
1991
1992 switch (opcode) {
1993 case Instruction::CONST_4:
1994 case Instruction::CONST_16:
1995 case Instruction::CONST:
1996 *wide = false;
1997 value <<= 32; // In order to get the sign extend.
1998 value >>= 32;
1999 break;
2000 case Instruction::CONST_HIGH16:
2001 *wide = false;
2002 value <<= 48; // In order to get the sign extend.
2003 value >>= 32;
2004 break;
2005 case Instruction::CONST_WIDE_16:
2006 case Instruction::CONST_WIDE_32:
2007 *wide = true;
2008 value <<= 32; // In order to get the sign extend.
2009 value >>= 32;
2010 break;
2011 case Instruction::CONST_WIDE:
2012 *wide = true;
2013 value = vB_wide;
2014 break;
2015 case Instruction::CONST_WIDE_HIGH16:
2016 *wide = true;
2017 value <<= 48; // In order to get the sign extend.
2018 break;
2019 default:
2020 sets_const = false;
2021 break;
2022 }
2023
2024 if (sets_const) {
2025 *ptr_value = value;
2026 }
2027
2028 return sets_const;
2029}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002030
2031void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2032 // Reset flags for all MIRs in bb.
2033 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2034 mir->optimization_flags &= (~reset_flags);
2035 }
2036}
2037
2038void BasicBlock::Hide(CompilationUnit* c_unit) {
2039 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2040 block_type = kDalvikByteCode;
2041
2042 // Mark it as hidden.
2043 hidden = true;
2044
2045 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2046 // are updated to know that they no longer have a parent.
2047 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2048 mir->bb = NullBasicBlockId;
2049 }
2050 first_mir_insn = nullptr;
2051 last_mir_insn = nullptr;
2052
2053 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2054
2055 MIRGraph* mir_graph = c_unit->mir_graph.get();
2056 while (true) {
2057 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2058 if (pred_bb == nullptr) {
2059 break;
2060 }
2061
2062 // Sadly we have to go through the children by hand here.
2063 pred_bb->ReplaceChild(id, NullBasicBlockId);
2064 }
2065
2066 // Iterate through children of bb we are hiding.
2067 ChildBlockIterator successorChildIter(this, mir_graph);
2068
2069 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2070 // Replace child with null child.
2071 childPtr->predecessors->Delete(id);
2072 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002073
2074 // Remove link to children.
2075 taken = NullBasicBlockId;
2076 fall_through = NullBasicBlockId;
2077 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002078}
2079
2080bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2081 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2082 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2083 // then it is not live out of this BB.
2084 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2085
2086 int last_ssa_reg = -1;
2087
2088 // Walk through the MIRs backwards.
2089 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2090 // Get ssa rep.
2091 SSARepresentation *ssa_rep = mir->ssa_rep;
2092
2093 // Go through the defines for this MIR.
2094 for (int i = 0; i < ssa_rep->num_defs; i++) {
2095 DCHECK(ssa_rep->defs != nullptr);
2096
2097 // Get the ssa reg.
2098 int def_ssa_reg = ssa_rep->defs[i];
2099
2100 // Get dalvik reg.
2101 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2102
2103 // Compare dalvik regs.
2104 if (dalvik_reg == def_dalvik_reg) {
2105 // We found a def of the register that we are being asked about.
2106 // Remember it.
2107 last_ssa_reg = def_ssa_reg;
2108 }
2109 }
2110 }
2111
2112 if (last_ssa_reg == -1) {
2113 // If we get to this point we couldn't find a define of register user asked about.
2114 // Let's assume the user knows what he's doing so we can be safe and say that if we
2115 // couldn't find a def, it is live out.
2116 return true;
2117 }
2118
2119 // If it is not -1, we found a match, is it ssa_reg?
2120 return (ssa_reg == last_ssa_reg);
2121}
2122
2123bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2124 // We need to check taken, fall_through, and successor_blocks to replace.
2125 bool found = false;
2126 if (taken == old_bb) {
2127 taken = new_bb;
2128 found = true;
2129 }
2130
2131 if (fall_through == old_bb) {
2132 fall_through = new_bb;
2133 found = true;
2134 }
2135
2136 if (successor_block_list_type != kNotUsed) {
2137 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2138 while (true) {
2139 SuccessorBlockInfo* successor_block_info = iterator.Next();
2140 if (successor_block_info == nullptr) {
2141 break;
2142 }
2143 if (successor_block_info->block == old_bb) {
2144 successor_block_info->block = new_bb;
2145 found = true;
2146 }
2147 }
2148 }
2149
2150 return found;
2151}
2152
2153void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2154 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2155 bool found = false;
2156
2157 while (true) {
2158 BasicBlockId pred_bb_id = iterator.Next();
2159
2160 if (pred_bb_id == NullBasicBlockId) {
2161 break;
2162 }
2163
2164 if (pred_bb_id == old_parent) {
2165 size_t idx = iterator.GetIndex() - 1;
2166 predecessors->Put(idx, new_parent);
2167 found = true;
2168 break;
2169 }
2170 }
2171
2172 // If not found, add it.
2173 if (found == false) {
2174 predecessors->Insert(new_parent);
2175 }
2176}
2177
2178// Create a new basic block with block_id as num_blocks_ that is
2179// post-incremented.
2180BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2181 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2182 block_list_.Insert(res);
2183 return res;
2184}
2185
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002186void MIRGraph::CalculateBasicBlockInformation() {
2187 PassDriverMEPostOpt driver(cu_);
2188 driver.Launch();
2189}
2190
2191void MIRGraph::InitializeBasicBlockData() {
2192 num_blocks_ = block_list_.Size();
2193}
2194
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002195} // namespace art