blob: 8ce038952082e30fbe78d43c392618fb34033576 [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 Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070029#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010030#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000031
buzbee311ca162013-02-28 15:56:43 -080032namespace art {
33
34#define MAX_PATTERN_LEN 5
35
buzbee1fd33462013-03-25 13:40:45 -070036const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
37 "Phi",
38 "Copy",
39 "FusedCmplFloat",
40 "FusedCmpgFloat",
41 "FusedCmplDouble",
42 "FusedCmpgDouble",
43 "FusedCmpLong",
44 "Nop",
45 "OpNullCheck",
46 "OpRangeCheck",
47 "OpDivZeroCheck",
48 "Check1",
49 "Check2",
50 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040051 "ConstVector",
52 "MoveVector",
53 "PackedMultiply",
54 "PackedAddition",
55 "PackedSubtract",
56 "PackedShiftLeft",
57 "PackedSignedShiftRight",
58 "PackedUnsignedShiftRight",
59 "PackedAnd",
60 "PackedOr",
61 "PackedXor",
62 "PackedAddReduce",
63 "PackedReduce",
64 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070065 "ReserveVectorRegisters",
66 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070067};
68
buzbee862a7602013-04-05 10:58:54 -070069MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070070 : reg_location_(NULL),
71 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080072 ssa_base_vregs_(NULL),
73 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080074 vreg_to_ssa_map_(NULL),
75 ssa_last_defs_(NULL),
76 is_constant_v_(NULL),
77 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070078 use_counts_(arena, 256, kGrowableArrayMisc),
79 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080080 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070081 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070082 dfs_order_(NULL),
83 dfs_post_order_(NULL),
84 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070085 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080086 i_dom_list_(NULL),
87 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000088 temp_scoped_alloc_(),
89 temp_insn_data_(nullptr),
90 temp_bit_vector_size_(0u),
91 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070092 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080093 try_block_addr_(NULL),
94 entry_block_(NULL),
95 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080096 num_blocks_(0),
97 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070098 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080099 current_method_(kInvalidEntry),
100 current_offset_(kInvalidEntry),
101 def_count_(0),
102 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700103 num_ssa_regs_(0),
104 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700105 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
106 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700107 arena_(arena),
108 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800109 forward_branches_(0),
110 compiler_temps_(arena, 6, kGrowableArrayMisc),
111 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800112 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000113 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000114 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000115 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000116 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700117 method_lowering_infos_(arena, 0u),
118 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700119 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800120 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
121 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800122}
123
Ian Rogers6282dc12013-04-18 15:54:02 -0700124MIRGraph::~MIRGraph() {
125 STLDeleteElements(&m_units_);
126}
127
buzbee311ca162013-02-28 15:56:43 -0800128/*
129 * Parse an instruction, return the length of the instruction
130 */
Ian Rogers29a26482014-05-02 15:27:29 -0700131int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
132 const Instruction* inst = Instruction::At(code_ptr);
133 decoded_instruction->opcode = inst->Opcode();
134 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
135 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
136 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
137 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
138 if (inst->HasVarArgs()) {
139 inst->GetVarArgs(decoded_instruction->arg);
140 }
141 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800142}
143
144
145/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700146BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700147 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700148 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800149 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700150 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800151 while (insn) {
152 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700153 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800154 insn = insn->next;
155 }
156 if (insn == NULL) {
157 LOG(FATAL) << "Break split failed";
158 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700159 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700160 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800161
162 bottom_block->start_offset = code_offset;
163 bottom_block->first_mir_insn = insn;
164 bottom_block->last_mir_insn = orig_block->last_mir_insn;
165
166 /* If this block was terminated by a return, the flag needs to go with the bottom block */
167 bottom_block->terminated_by_return = orig_block->terminated_by_return;
168 orig_block->terminated_by_return = false;
169
buzbee311ca162013-02-28 15:56:43 -0800170 /* Handle the taken path */
171 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700172 if (bottom_block->taken != NullBasicBlockId) {
173 orig_block->taken = NullBasicBlockId;
174 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
175 bb_taken->predecessors->Delete(orig_block->id);
176 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800177 }
178
179 /* Handle the fallthrough path */
180 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700181 orig_block->fall_through = bottom_block->id;
182 bottom_block->predecessors->Insert(orig_block->id);
183 if (bottom_block->fall_through != NullBasicBlockId) {
184 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
185 bb_fall_through->predecessors->Delete(orig_block->id);
186 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800187 }
188
189 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700190 if (orig_block->successor_block_list_type != kNotUsed) {
191 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
192 bottom_block->successor_blocks = orig_block->successor_blocks;
193 orig_block->successor_block_list_type = kNotUsed;
194 orig_block->successor_blocks = NULL;
195 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800196 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700197 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800198 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700199 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700200 bb->predecessors->Delete(orig_block->id);
201 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800202 }
203 }
204
buzbee0d829482013-10-11 15:24:55 -0700205 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700206 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800207
buzbee311ca162013-02-28 15:56:43 -0800208 /*
209 * Update the immediate predecessor block pointer so that outgoing edges
210 * can be applied to the proper block.
211 */
212 if (immed_pred_block_p) {
213 DCHECK_EQ(*immed_pred_block_p, orig_block);
214 *immed_pred_block_p = bottom_block;
215 }
buzbeeb48819d2013-09-14 16:15:25 -0700216
217 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000218 DCHECK(insn != nullptr);
219 DCHECK(insn != orig_block->first_mir_insn);
220 DCHECK(insn == bottom_block->first_mir_insn);
221 DCHECK_EQ(insn->offset, bottom_block->start_offset);
222 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
223 !IsPseudoMirOp(insn->dalvikInsn.opcode));
224 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
225 MIR* p = insn;
226 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
227 while (p != bottom_block->last_mir_insn) {
228 p = p->next;
229 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700230 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700231 int opcode = p->dalvikInsn.opcode;
232 /*
233 * Some messiness here to ensure that we only enter real opcodes and only the
234 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000235 * CHECK and work portions. Since the 2nd half of a split operation is always
236 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700237 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000238 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
239 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700240 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
241 }
buzbeeb48819d2013-09-14 16:15:25 -0700242 }
243
buzbee311ca162013-02-28 15:56:43 -0800244 return bottom_block;
245}
246
247/*
248 * Given a code offset, find out the block that starts with it. If the offset
249 * is in the middle of an existing block, split it into two. If immed_pred_block_p
250 * is not non-null and is the block being split, update *immed_pred_block_p to
251 * point to the bottom block so that outgoing edges can be set up properly
252 * (by the caller)
253 * Utilizes a map for fast lookup of the typical cases.
254 */
buzbee0d829482013-10-11 15:24:55 -0700255BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700256 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700257 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800258 return NULL;
259 }
buzbeeb48819d2013-09-14 16:15:25 -0700260
261 int block_id = dex_pc_to_block_map_.Get(code_offset);
262 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
263
264 if ((bb != NULL) && (bb->start_offset == code_offset)) {
265 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700266 return bb;
267 }
buzbee311ca162013-02-28 15:56:43 -0800268
buzbeeb48819d2013-09-14 16:15:25 -0700269 // No direct hit.
270 if (!create) {
271 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800272 }
273
buzbeeb48819d2013-09-14 16:15:25 -0700274 if (bb != NULL) {
275 // The target exists somewhere in an existing block.
276 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
277 }
278
279 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700280 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
281 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800282 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700283 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800284 return bb;
285}
286
buzbeeb48819d2013-09-14 16:15:25 -0700287
buzbee311ca162013-02-28 15:56:43 -0800288/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700289void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800290 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700291 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800292
293 if (tries_size == 0) {
294 return;
295 }
296
297 for (int i = 0; i < tries_size; i++) {
298 const DexFile::TryItem* pTry =
299 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700300 DexOffset start_offset = pTry->start_addr_;
301 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800302 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700303 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800304 }
305 }
306
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700307 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800308 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
309 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
310 for (uint32_t idx = 0; idx < handlers_size; idx++) {
311 CatchHandlerIterator iterator(handlers_ptr);
312 for (; iterator.HasNext(); iterator.Next()) {
313 uint32_t address = iterator.GetHandlerAddress();
314 FindBlock(address, false /* split */, true /*create*/,
315 /* immed_pred_block_p */ NULL);
316 }
317 handlers_ptr = iterator.EndDataPointer();
318 }
319}
320
321/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700322BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
323 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700324 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700325 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800326 switch (insn->dalvikInsn.opcode) {
327 case Instruction::GOTO:
328 case Instruction::GOTO_16:
329 case Instruction::GOTO_32:
330 target += insn->dalvikInsn.vA;
331 break;
332 case Instruction::IF_EQ:
333 case Instruction::IF_NE:
334 case Instruction::IF_LT:
335 case Instruction::IF_GE:
336 case Instruction::IF_GT:
337 case Instruction::IF_LE:
338 cur_block->conditional_branch = true;
339 target += insn->dalvikInsn.vC;
340 break;
341 case Instruction::IF_EQZ:
342 case Instruction::IF_NEZ:
343 case Instruction::IF_LTZ:
344 case Instruction::IF_GEZ:
345 case Instruction::IF_GTZ:
346 case Instruction::IF_LEZ:
347 cur_block->conditional_branch = true;
348 target += insn->dalvikInsn.vB;
349 break;
350 default:
351 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
352 }
buzbeeb48819d2013-09-14 16:15:25 -0700353 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700354 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800355 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700356 cur_block->taken = taken_block->id;
357 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800358
359 /* Always terminate the current block for conditional branches */
360 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700361 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800362 /*
363 * If the method is processed
364 * in sequential order from the
365 * beginning, we don't need to
366 * specify split for continue
367 * blocks. However, this
368 * routine can be called by
369 * compileLoop, which starts
370 * parsing the method from an
371 * arbitrary address in the
372 * method body.
373 */
374 true,
375 /* create */
376 true,
377 /* immed_pred_block_p */
378 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700379 cur_block->fall_through = fallthrough_block->id;
380 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800381 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700382 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800383 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800384 }
385 return cur_block;
386}
387
388/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800389BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
390 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800391 const uint16_t* switch_data =
392 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
393 int size;
394 const int* keyTable;
395 const int* target_table;
396 int i;
397 int first_key;
398
399 /*
400 * Packed switch data format:
401 * ushort ident = 0x0100 magic value
402 * ushort size number of entries in the table
403 * int first_key first (and lowest) switch case value
404 * int targets[size] branch targets, relative to switch opcode
405 *
406 * Total size is (4+size*2) 16-bit code units.
407 */
408 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
409 DCHECK_EQ(static_cast<int>(switch_data[0]),
410 static_cast<int>(Instruction::kPackedSwitchSignature));
411 size = switch_data[1];
412 first_key = switch_data[2] | (switch_data[3] << 16);
413 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700414 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800415 /*
416 * Sparse switch data format:
417 * ushort ident = 0x0200 magic value
418 * ushort size number of entries in the table; > 0
419 * int keys[size] keys, sorted low-to-high; 32-bit aligned
420 * int targets[size] branch targets, relative to switch opcode
421 *
422 * Total size is (2+size*4) 16-bit code units.
423 */
424 } else {
425 DCHECK_EQ(static_cast<int>(switch_data[0]),
426 static_cast<int>(Instruction::kSparseSwitchSignature));
427 size = switch_data[1];
428 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
429 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700430 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800431 }
432
buzbee0d829482013-10-11 15:24:55 -0700433 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800434 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700435 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800436 }
buzbee0d829482013-10-11 15:24:55 -0700437 cur_block->successor_block_list_type =
438 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
439 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700440 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800441
442 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700443 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800444 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700445 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700446 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000447 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700448 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800449 successor_block_info->key =
450 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
451 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700452 cur_block->successor_blocks->Insert(successor_block_info);
453 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800454 }
455
456 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700457 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
458 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700459 cur_block->fall_through = fallthrough_block->id;
460 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800461 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800462}
463
464/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700465BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
466 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700467 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700468 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800469 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
470 bool build_all_edges =
471 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800472
473 /* In try block */
474 if (in_try_block) {
475 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
476
buzbee0d829482013-10-11 15:24:55 -0700477 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800478 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
479 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700480 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800481 }
482
buzbee0d829482013-10-11 15:24:55 -0700483 cur_block->successor_block_list_type = kCatch;
484 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700485 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800486
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700487 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700488 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800489 false /* creat */, NULL /* immed_pred_block_p */);
490 catch_block->catch_entry = true;
491 if (kIsDebugBuild) {
492 catches_.insert(catch_block->start_offset);
493 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700494 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000495 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700496 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800497 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700498 cur_block->successor_blocks->Insert(successor_block_info);
499 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800500 }
buzbee17189ac2013-11-08 11:07:02 -0800501 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700502 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700503 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700504 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800505 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700506 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800507 }
508
buzbee17189ac2013-11-08 11:07:02 -0800509 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800510 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700511 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700512 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800513 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
514 /* immed_pred_block_p */ NULL);
515 }
516 if (!in_try_block) {
517 // Don't split a THROW that can't rethrow - we're done.
518 return cur_block;
519 }
520 }
521
buzbee17189ac2013-11-08 11:07:02 -0800522 if (!build_all_edges) {
523 /*
524 * Even though there is an exception edge here, control cannot return to this
525 * method. Thus, for the purposes of dataflow analysis and optimization, we can
526 * ignore the edge. Doing this reduces compile time, and increases the scope
527 * of the basic-block level optimization pass.
528 */
529 return cur_block;
530 }
531
buzbee311ca162013-02-28 15:56:43 -0800532 /*
533 * Split the potentially-throwing instruction into two parts.
534 * The first half will be a pseudo-op that captures the exception
535 * edges and terminates the basic block. It always falls through.
536 * Then, create a new basic block that begins with the throwing instruction
537 * (minus exceptions). Note: this new basic block must NOT be entered into
538 * the block_map. If the potentially-throwing instruction is the target of a
539 * future branch, we need to find the check psuedo half. The new
540 * basic block containing the work portion of the instruction should
541 * only be entered via fallthrough from the block containing the
542 * pseudo exception edge MIR. Note also that this new block is
543 * not automatically terminated after the work portion, and may
544 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700545 *
546 * Note also that the dex_pc_to_block_map_ entry for the potentially
547 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800548 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700549 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700550 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800551 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700552 cur_block->fall_through = new_block->id;
553 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700554 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800555 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700556 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700557 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800558 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700559 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800560 return new_block;
561}
562
563/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
564void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700565 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700566 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800567 current_code_item_ = code_item;
568 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
569 current_method_ = m_units_.size();
570 current_offset_ = 0;
571 // TODO: will need to snapshot stack image and use that as the mir context identification.
572 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000573 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
574 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800575 const uint16_t* code_ptr = current_code_item_->insns_;
576 const uint16_t* code_end =
577 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
578
579 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700580 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700581 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700582 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 -0700583
buzbee311ca162013-02-28 15:56:43 -0800584 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700585 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
586 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800587
588 // If this is the first method, set up default entry and exit blocks.
589 if (current_method_ == 0) {
590 DCHECK(entry_block_ == NULL);
591 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700592 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700593 // Use id 0 to represent a null block.
594 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
595 DCHECK_EQ(null_block->id, NullBasicBlockId);
596 null_block->hidden = true;
597 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700598 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700599 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700600 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700601 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800602 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
603 cu_->dex_file = &dex_file;
604 cu_->class_def_idx = class_def_idx;
605 cu_->method_idx = method_idx;
606 cu_->access_flags = access_flags;
607 cu_->invoke_type = invoke_type;
608 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
609 cu_->num_ins = current_code_item_->ins_size_;
610 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
611 cu_->num_outs = current_code_item_->outs_size_;
612 cu_->num_dalvik_registers = current_code_item_->registers_size_;
613 cu_->insns = current_code_item_->insns_;
614 cu_->code_item = current_code_item_;
615 } else {
616 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
617 /*
618 * Will need to manage storage for ins & outs, push prevous state and update
619 * insert point.
620 */
621 }
622
623 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700624 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700625 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800626 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700627 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700628 // TODO: for inlining support, insert at the insert point rather than entry block.
629 entry_block_->fall_through = cur_block->id;
630 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800631
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000632 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800633 ProcessTryCatchBlocks();
634
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000635 uint64_t merged_df_flags = 0u;
636
buzbee311ca162013-02-28 15:56:43 -0800637 /* Parse all instructions and put them into containing basic blocks */
638 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700639 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800640 insn->offset = current_offset_;
641 insn->m_unit_index = current_method_;
642 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800643 Instruction::Code opcode = insn->dalvikInsn.opcode;
644 if (opcode_count_ != NULL) {
645 opcode_count_[static_cast<int>(opcode)]++;
646 }
647
buzbee311ca162013-02-28 15:56:43 -0800648 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800649 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800650
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700651 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000652 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800653
654 if (df_flags & DF_HAS_DEFS) {
655 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
656 }
657
buzbee1da1e2f2013-11-15 13:37:01 -0800658 if (df_flags & DF_LVN) {
659 cur_block->use_lvn = true; // Run local value numbering on this basic block.
660 }
661
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700662 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700663 if (opcode == Instruction::NOP) {
664 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
665 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
666 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
667 uint16_t following_raw_instruction = code_ptr[1];
668 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
669 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
670 (following_raw_instruction == Instruction::kArrayDataSignature)) {
671 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
672 }
673 }
674 if (width == 1) {
675 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700676 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700677 } else {
buzbee0d829482013-10-11 15:24:55 -0700678 DCHECK(cur_block->fall_through == NullBasicBlockId);
679 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700680 // Unreachable instruction, mark for no continuation.
681 flags &= ~Instruction::kContinue;
682 }
683 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700684 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700685 }
686
buzbeeb48819d2013-09-14 16:15:25 -0700687 // Associate the starting dex_pc for this opcode with its containing basic block.
688 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
689
buzbee27247762013-07-28 12:03:58 -0700690 code_ptr += width;
691
buzbee311ca162013-02-28 15:56:43 -0800692 if (flags & Instruction::kBranch) {
693 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
694 width, flags, code_ptr, code_end);
695 } else if (flags & Instruction::kReturn) {
696 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700697 cur_block->fall_through = exit_block_->id;
698 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800699 /*
700 * Terminate the current block if there are instructions
701 * afterwards.
702 */
703 if (code_ptr < code_end) {
704 /*
705 * Create a fallthrough block for real instructions
706 * (incl. NOP).
707 */
buzbee27247762013-07-28 12:03:58 -0700708 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
709 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800710 }
711 } else if (flags & Instruction::kThrow) {
712 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
713 code_ptr, code_end);
714 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800715 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800716 }
buzbeeb1f1d642014-02-27 12:55:32 -0800717 if (verify_flags & Instruction::kVerifyVarArgRange) {
718 /*
719 * The Quick backend's runtime model includes a gap between a method's
720 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
721 * which spans the gap is somewhat complicated, and should not happen
722 * in normal usage of dx. Punt to the interpreter.
723 */
724 int first_reg_in_range = insn->dalvikInsn.vC;
725 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
726 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
727 punt_to_interpreter_ = true;
728 }
729 }
buzbee311ca162013-02-28 15:56:43 -0800730 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700731 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800732 false, /* immed_pred_block_p */ NULL);
733 if (next_block) {
734 /*
735 * The next instruction could be the target of a previously parsed
736 * forward branch so a block is already created. If the current
737 * instruction is not an unconditional branch, connect them through
738 * the fall-through link.
739 */
buzbee0d829482013-10-11 15:24:55 -0700740 DCHECK(cur_block->fall_through == NullBasicBlockId ||
741 GetBasicBlock(cur_block->fall_through) == next_block ||
742 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800743
buzbee0d829482013-10-11 15:24:55 -0700744 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
745 cur_block->fall_through = next_block->id;
746 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800747 }
748 cur_block = next_block;
749 }
750 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000751 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000752
buzbee311ca162013-02-28 15:56:43 -0800753 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
754 DumpCFG("/sdcard/1_post_parse_cfg/", true);
755 }
756
757 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700758 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800759 }
760}
761
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700762void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800763 DCHECK(opcode_count_ != NULL);
764 LOG(INFO) << "Opcode Count";
765 for (int i = 0; i < kNumPackedOpcodes; i++) {
766 if (opcode_count_[i] != 0) {
767 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
768 << " " << opcode_count_[i];
769 }
770 }
771}
772
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700773uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
774 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
775 return oat_data_flow_attributes_[opcode];
776}
777
778uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
779 DCHECK(mir != nullptr);
780 Instruction::Code opcode = mir->dalvikInsn.opcode;
781 return GetDataFlowAttributes(opcode);
782}
783
buzbee311ca162013-02-28 15:56:43 -0800784// TODO: use a configurable base prefix, and adjust callers to supply pass name.
785/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800786void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800787 FILE* file;
788 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
789 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800790 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
791 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
792 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800793 file = fopen(fname.c_str(), "w");
794 if (file == NULL) {
795 return;
796 }
797 fprintf(file, "digraph G {\n");
798
799 fprintf(file, " rankdir=TB\n");
800
801 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
802 int idx;
803
804 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700805 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700806 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700807 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800808 if (bb->block_type == kDead) continue;
809 if (bb->block_type == kEntryBlock) {
810 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
811 } else if (bb->block_type == kExitBlock) {
812 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
813 } else if (bb->block_type == kDalvikByteCode) {
814 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
815 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700816 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800817 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
818 bb->first_mir_insn ? " | " : " ");
819 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
820 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400821 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
822 if (opcode == kMirOpConstVector) {
823 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
824 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
825 mir->dalvikInsn.vA,
826 mir->dalvikInsn.vB,
827 mir->dalvikInsn.arg[0],
828 mir->dalvikInsn.arg[1],
829 mir->dalvikInsn.arg[2],
830 mir->dalvikInsn.arg[3],
831 mir->next ? " | " : " ");
832 } else {
833 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
834 extended_mir_op_names_[opcode - kMirOpFirst],
835 mir->dalvikInsn.vA,
836 mir->dalvikInsn.vB,
837 mir->dalvikInsn.vC,
838 mir->next ? " | " : " ");
839 }
840 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700841 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400842 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700843 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400844 extended_mir_op_names_[opcode - kMirOpFirst],
845 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
846 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700847 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400848 mir->next ? " | " : " ");
849 }
buzbee311ca162013-02-28 15:56:43 -0800850 }
851 fprintf(file, " }\"];\n\n");
852 } else if (bb->block_type == kExceptionHandling) {
853 char block_name[BLOCK_NAME_LEN];
854
855 GetBlockName(bb, block_name);
856 fprintf(file, " %s [shape=invhouse];\n", block_name);
857 }
858
859 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
860
buzbee0d829482013-10-11 15:24:55 -0700861 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800862 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700863 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800864 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
865 block_name1, block_name2);
866 }
buzbee0d829482013-10-11 15:24:55 -0700867 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800868 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700869 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800870 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
871 }
872
buzbee0d829482013-10-11 15:24:55 -0700873 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800874 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
875 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700876 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
877 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700878 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800879
880 int succ_id = 0;
881 while (true) {
882 if (successor_block_info == NULL) break;
883
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700884 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700885 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800886
887 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
888 succ_id++,
889 successor_block_info->key,
890 dest_block->start_offset,
891 (next_successor_block_info != NULL) ? " | " : " ");
892
893 successor_block_info = next_successor_block_info;
894 }
895 fprintf(file, " }\"];\n\n");
896
897 GetBlockName(bb, block_name1);
898 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
899 block_name1, bb->start_offset, bb->id);
900
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700901 // Link the successor pseudo-block with all of its potential targets.
902 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800903
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700904 succ_id = 0;
905 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700906 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700907 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800908
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700909 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800910
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700911 GetBlockName(dest_block, block_name2);
912 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
913 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800914 }
915 }
916 fprintf(file, "\n");
917
918 if (cu_->verbose) {
919 /* Display the dominator tree */
920 GetBlockName(bb, block_name1);
921 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
922 block_name1, block_name1);
923 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700924 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800925 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
926 }
927 }
928 }
929 fprintf(file, "}\n");
930 fclose(file);
931}
932
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700933/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700934void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700935 // Insert it after the last MIR.
936 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -0700937}
938
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700939void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
940 // Insert it after the last MIR.
941 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
942}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700943
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700944void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
945 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
946 MIR* new_mir = *it;
947
948 // Add a copy of each MIR.
949 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
950 }
buzbee1fd33462013-03-25 13:40:45 -0700951}
952
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700953/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700954void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700955 InsertMIRListAfter(current_mir, new_mir, new_mir);
956}
buzbee1fd33462013-03-25 13:40:45 -0700957
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700958void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
959 // If no MIR, we are done.
960 if (first_list_mir == nullptr || last_list_mir == nullptr) {
961 return;
buzbee1fd33462013-03-25 13:40:45 -0700962 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700963
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700964 // If insert_after is null, assume BB is empty.
965 if (insert_after == nullptr) {
966 first_mir_insn = first_list_mir;
967 last_mir_insn = last_list_mir;
968 last_list_mir->next = nullptr;
969 } else {
970 MIR* after_list = insert_after->next;
971 insert_after->next = first_list_mir;
972 last_list_mir->next = after_list;
973 if (after_list == nullptr) {
974 last_mir_insn = last_list_mir;
975 }
976 }
977
978 // Set this BB to be the basic block of the MIRs.
979 MIR* last = last_list_mir->next;
980 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
981 mir->bb = id;
982 }
983}
984
985/* Insert an MIR instruction to the head of a basic block. */
986void BasicBlock::PrependMIR(MIR* mir) {
987 InsertMIRListBefore(first_mir_insn, mir, mir);
988}
989
990void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
991 // Insert it before the first MIR.
992 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
993}
994
995void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
996 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
997 MIR* mir = *it;
998
999 InsertMIRListBefore(first_mir_insn, mir, mir);
1000 }
1001}
1002
1003/* Insert a MIR instruction before the specified MIR. */
1004void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1005 // Insert as a single element list.
1006 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001007}
1008
1009MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1010 MIR* current = first_mir_insn;
1011
1012 while (current != nullptr) {
1013 MIR* next = current->next;
1014
1015 if (next == mir) {
1016 return current;
1017 }
1018
1019 current = next;
1020 }
1021
1022 return nullptr;
1023}
1024
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001025void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1026 // If no MIR, we are done.
1027 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1028 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001029 }
1030
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001031 // If insert_before is null, assume BB is empty.
1032 if (insert_before == nullptr) {
1033 first_mir_insn = first_list_mir;
1034 last_mir_insn = last_list_mir;
1035 last_list_mir->next = nullptr;
1036 } else {
1037 if (first_mir_insn == insert_before) {
1038 last_list_mir->next = first_mir_insn;
1039 first_mir_insn = first_list_mir;
1040 } else {
1041 // Find the preceding MIR.
1042 MIR* before_list = FindPreviousMIR(insert_before);
1043 DCHECK(before_list != nullptr);
1044 before_list->next = first_list_mir;
1045 last_list_mir->next = insert_before;
1046 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001047 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001048
1049 // Set this BB to be the basic block of the MIRs.
1050 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1051 mir->bb = id;
1052 }
1053}
1054
1055bool BasicBlock::RemoveMIR(MIR* mir) {
1056 // Remove as a single element list.
1057 return RemoveMIRList(mir, mir);
1058}
1059
1060bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1061 if (first_list_mir == nullptr) {
1062 return false;
1063 }
1064
1065 // Try to find the MIR.
1066 MIR* before_list = nullptr;
1067 MIR* after_list = nullptr;
1068
1069 // If we are removing from the beginning of the MIR list.
1070 if (first_mir_insn == first_list_mir) {
1071 before_list = nullptr;
1072 } else {
1073 before_list = FindPreviousMIR(first_list_mir);
1074 if (before_list == nullptr) {
1075 // We did not find the mir.
1076 return false;
1077 }
1078 }
1079
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001080 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001081 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1082 mir->bb = NullBasicBlockId;
1083 }
1084
1085 after_list = last_list_mir->next;
1086
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001087 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001088 if (before_list == nullptr) {
1089 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001090 } else {
1091 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001092 }
1093
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001094 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001095 if (after_list == nullptr) {
1096 last_mir_insn = before_list;
1097 }
1098
1099 return true;
buzbee1fd33462013-03-25 13:40:45 -07001100}
1101
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001102MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001103 MIR* next_mir = nullptr;
1104
1105 if (current != nullptr) {
1106 next_mir = current->next;
1107 }
1108
1109 if (next_mir == nullptr) {
1110 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001111 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1112 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001113 }
1114 }
1115
1116 return next_mir;
1117}
1118
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001119char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001120 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001121 std::string str;
1122 int flags = 0;
1123 int opcode = insn.opcode;
1124 char* ret;
1125 bool nop = false;
1126 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001127 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001128 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1129 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1130
1131 // Handle special cases.
1132 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1133 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1134 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001135 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001136 insn = mir->meta.throw_insn->dalvikInsn;
1137 ssa_rep = mir->meta.throw_insn->ssa_rep;
1138 defs = ssa_rep->num_defs;
1139 uses = ssa_rep->num_uses;
1140 opcode = insn.opcode;
1141 } else if (opcode == kMirOpNop) {
1142 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001143 // Recover original opcode.
1144 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1145 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001146 nop = true;
1147 }
1148
buzbee35ba7f32014-05-31 08:59:01 -07001149 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001150 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1151 } else {
1152 dalvik_format = Instruction::FormatOf(insn.opcode);
1153 flags = Instruction::FlagsOf(insn.opcode);
1154 str.append(Instruction::Name(insn.opcode));
1155 }
1156
1157 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001158 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001159 str.append(StringPrintf(" %s = (%s",
1160 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1161 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001162 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001163 int i;
1164 for (i = 1; i < uses; i++) {
1165 str.append(StringPrintf(", %s:%d",
1166 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1167 incoming[i]));
1168 }
1169 str.append(")");
1170 } else if ((flags & Instruction::kBranch) != 0) {
1171 // For branches, decode the instructions to print out the branch targets.
1172 int offset = 0;
1173 switch (dalvik_format) {
1174 case Instruction::k21t:
1175 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1176 offset = insn.vB;
1177 break;
1178 case Instruction::k22t:
1179 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1180 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1181 offset = insn.vC;
1182 break;
1183 case Instruction::k10t:
1184 case Instruction::k20t:
1185 case Instruction::k30t:
1186 offset = insn.vA;
1187 break;
1188 default:
1189 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1190 }
1191 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1192 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1193 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001194 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001195 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1196 (dalvik_format == Instruction::k3rc));
1197 if (defs != 0) {
1198 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1199 if (uses != 0) {
1200 str.append(", ");
1201 }
1202 }
1203 for (int i = 0; i < uses; i++) {
1204 str.append(
1205 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1206 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1207 // For the listing, skip the high sreg.
1208 i++;
1209 }
1210 if (i != (uses -1)) {
1211 str.append(",");
1212 }
1213 }
1214 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001215 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001216 case Instruction::k21s:
1217 case Instruction::k31i:
1218 case Instruction::k21h:
1219 str.append(StringPrintf(", #%d", insn.vB));
1220 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001221 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001222 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001223 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001224 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001225 case Instruction::k31c:
1226 str.append(StringPrintf(", index #%d", insn.vB));
1227 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001228 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001229 str.append(StringPrintf(", index #%d", insn.vC));
1230 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001231 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001232 case Instruction::k22b:
1233 str.append(StringPrintf(", #%d", insn.vC));
1234 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001235 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001236 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001237 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001238 }
buzbee1fd33462013-03-25 13:40:45 -07001239 }
1240 if (nop) {
1241 str.append("]--optimized away");
1242 }
1243 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001244 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001245 strncpy(ret, str.c_str(), length);
1246 return ret;
1247}
1248
1249/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001250void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001251 static const struct { const char before; const char after; } match[] = {
1252 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1253 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1254 };
buzbee1fd33462013-03-25 13:40:45 -07001255 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1256 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1257 }
1258}
1259
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001260std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001261 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1262 // the arena. We should be smarter and just place straight into the arena, or compute the
1263 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001264 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1265}
1266
1267// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001268std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001269 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001270 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001271 return GetSSAName(ssa_reg);
1272 }
1273 if (IsConst(reg_location_[ssa_reg])) {
1274 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001275 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001276 ConstantValueWide(reg_location_[ssa_reg]));
1277 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001278 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001279 ConstantValue(reg_location_[ssa_reg]));
1280 }
1281 } else {
1282 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1283 }
1284}
1285
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001286void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001287 switch (bb->block_type) {
1288 case kEntryBlock:
1289 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1290 break;
1291 case kExitBlock:
1292 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1293 break;
1294 case kDalvikByteCode:
1295 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1296 break;
1297 case kExceptionHandling:
1298 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1299 bb->id);
1300 break;
1301 default:
1302 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1303 break;
1304 }
1305}
1306
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001307const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001308 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001309 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1310 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1311}
1312
1313/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001314void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001315 BasicBlock* bb;
1316 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001317 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001318 "Entry Block",
1319 "Code Block",
1320 "Exit Block",
1321 "Exception Handling",
1322 "Catch Block"
1323 };
1324
1325 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1326 LOG(INFO) << cu_->insns << " insns";
1327 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001328 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001329
1330 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001331 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001332 if (bb == NULL) break;
1333 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1334 bb->id,
1335 block_type_names[bb->block_type],
1336 bb->start_offset,
1337 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1338 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001339 if (bb->taken != NullBasicBlockId) {
1340 LOG(INFO) << " Taken branch: block " << bb->taken
1341 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001342 }
buzbee0d829482013-10-11 15:24:55 -07001343 if (bb->fall_through != NullBasicBlockId) {
1344 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1345 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001346 }
1347 }
1348}
1349
1350/*
1351 * Build an array of location records for the incoming arguments.
1352 * Note: one location record per word of arguments, with dummy
1353 * high-word loc for wide arguments. Also pull up any following
1354 * MOVE_RESULT and incorporate it into the invoke.
1355 */
1356CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001357 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001358 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001359 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001360 MIR* move_result_mir = FindMoveResult(bb, mir);
1361 if (move_result_mir == NULL) {
1362 info->result.location = kLocInvalid;
1363 } else {
1364 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001365 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1366 }
1367 info->num_arg_words = mir->ssa_rep->num_uses;
1368 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001369 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001370 for (int i = 0; i < info->num_arg_words; i++) {
1371 info->args[i] = GetRawSrc(mir, i);
1372 }
1373 info->opt_flags = mir->optimization_flags;
1374 info->type = type;
1375 info->is_range = is_range;
1376 info->index = mir->dalvikInsn.vB;
1377 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001378 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001379 return info;
1380}
1381
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001382// Allocate a new MIR.
1383MIR* MIRGraph::NewMIR() {
1384 MIR* mir = new (arena_) MIR();
1385 return mir;
1386}
1387
buzbee862a7602013-04-05 10:58:54 -07001388// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001389BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001390 BasicBlock* bb = new (arena_) BasicBlock();
1391
buzbee862a7602013-04-05 10:58:54 -07001392 bb->block_type = block_type;
1393 bb->id = block_id;
1394 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001395 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001396 (block_type == kExitBlock) ? 2048 : 2,
1397 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001398 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001399 block_id_map_.Put(block_id, block_id);
1400 return bb;
1401}
buzbee1fd33462013-03-25 13:40:45 -07001402
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001403void MIRGraph::InitializeConstantPropagation() {
1404 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001405 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001406}
1407
1408void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001409 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001410 int num_ssa_regs = GetNumSSARegs();
1411 use_counts_.Resize(num_ssa_regs + 32);
1412 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001413 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001414 for (int i = 0; i < num_ssa_regs; i++) {
1415 use_counts_.Insert(0);
1416 raw_use_counts_.Insert(0);
1417 }
1418}
1419
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001420void MIRGraph::SSATransformationStart() {
1421 DCHECK(temp_scoped_alloc_.get() == nullptr);
1422 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1423 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1424 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1425 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1426
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001427 // Update the maximum number of reachable blocks.
1428 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001429}
1430
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001431void MIRGraph::SSATransformationEnd() {
1432 // Verify the dataflow information after the pass.
1433 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1434 VerifyDataflow();
1435 }
1436
1437 temp_bit_vector_size_ = 0u;
1438 temp_bit_vector_ = nullptr;
1439 DCHECK(temp_scoped_alloc_.get() != nullptr);
1440 temp_scoped_alloc_.reset();
1441}
1442
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001443void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001444 // Clear the nodes.
1445 ClearAllVisitedFlags();
1446
1447 // Create the topological order if need be.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001448 if (topological_order_ == nullptr) {
1449 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, GetNumBlocks());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001450 }
1451 topological_order_->Reset();
1452
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001453 ScopedArenaAllocator allocator(&cu_->arena_stack);
1454 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1455 ScopedArenaVector<size_t> visited_cnt_values(GetNumBlocks(), 0u, allocator.Adapter());
1456
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001457 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1458 // also fill initial queue.
1459 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1460
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001461 size_t num_blocks = 0u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001462 while (true) {
1463 BasicBlock* bb = iterator.Next();
1464
1465 if (bb == nullptr) {
1466 break;
1467 }
1468
1469 if (bb->hidden == true) {
1470 continue;
1471 }
1472
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001473 num_blocks += 1u;
1474 size_t unvisited_predecessor_count = bb->predecessors->Size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001475
1476 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1477 // To process loops we should not wait for dominators.
1478 while (true) {
1479 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1480
1481 if (pred_bb == nullptr) {
1482 break;
1483 }
1484
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001485 // Skip the backward branch or hidden predecessor.
1486 if (pred_bb->hidden ||
1487 (pred_bb->dominators != nullptr && pred_bb->dominators->IsBitSet(bb->id))) {
1488 unvisited_predecessor_count -= 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001489 }
1490 }
1491
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001492 visited_cnt_values[bb->id] = unvisited_predecessor_count;
1493
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001494 // Add entry block to queue.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001495 if (unvisited_predecessor_count == 0) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001496 q.push(bb);
1497 }
1498 }
1499
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001500 // We can theoretically get a cycle where none of the blocks dominates the other. Therefore
1501 // don't stop when the queue is empty, continue until we've processed all the blocks.
1502 // (In practice, we've seen this for a monitor-exit catch handler that erroneously tries to
1503 // handle its own exceptions being broken into two blocks by a jump to to the monitor-exit
1504 // from another catch hanler. http://b/15745363 .)
1505 AllNodesIterator candidate_iter(this); // For the empty queue case.
1506 while (num_blocks != 0u) {
1507 num_blocks -= 1u;
1508 BasicBlock* bb = nullptr;
1509 if (!q.empty()) {
1510 // Get top.
1511 bb = q.front();
1512 q.pop();
1513 } else {
1514 // Find some block we didn't visit yet that has at least one visited predecessor.
1515 while (bb == nullptr) {
1516 BasicBlock* candidate = candidate_iter.Next();
1517 DCHECK(candidate != nullptr);
1518 if (candidate->visited || candidate->hidden) {
1519 continue;
1520 }
1521 GrowableArray<BasicBlockId>::Iterator iter(candidate->predecessors);
1522 for (BasicBlock* pred_bb = GetBasicBlock(iter.Next()); pred_bb != nullptr;
1523 pred_bb = GetBasicBlock(iter.Next())) {
1524 if (!pred_bb->hidden && pred_bb->visited) {
1525 bb = candidate;
1526 break;
1527 }
1528 }
1529 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001530 }
1531
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001532 DCHECK_EQ(bb->hidden, false);
1533 DCHECK_EQ(bb->visited, false);
1534
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001535 // We've visited all the predecessors. So, we can visit bb.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001536 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001537
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001538 // Now add the basic block.
1539 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001540
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001541 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1542 ChildBlockIterator succIter(bb, this);
1543 BasicBlock* successor = succIter.Next();
1544 for ( ; successor != nullptr; successor = succIter.Next()) {
1545 if (successor->visited || successor->hidden) {
1546 continue;
1547 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001548
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001549 // one more predecessor was visited.
1550 DCHECK_NE(visited_cnt_values[successor->id], 0u);
1551 visited_cnt_values[successor->id] -= 1u;
1552 if (visited_cnt_values[successor->id] == 0u) {
1553 q.push(successor);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001554 }
1555 }
1556 }
1557}
1558
1559bool BasicBlock::IsExceptionBlock() const {
1560 if (block_type == kExceptionHandling) {
1561 return true;
1562 }
1563 return false;
1564}
1565
Wei Jin04f4d8a2014-05-29 18:04:29 -07001566bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1567 BasicBlock* target = GetBasicBlock(target_id);
1568
1569 if (source == nullptr || target == nullptr)
1570 return false;
1571
1572 int idx;
1573 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1574 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1575 if (bb == source)
1576 return true; // The block has been inserted by a suspend check before.
1577 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1578 return true;
1579 }
1580
1581 return false;
1582}
1583
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001584ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1585 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1586 visited_taken_(false), have_successors_(false) {
1587 // Check if we actually do have successors.
1588 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1589 have_successors_ = true;
1590 successor_iter_.Reset(basic_block_->successor_blocks);
1591 }
1592}
1593
1594BasicBlock* ChildBlockIterator::Next() {
1595 // We check if we have a basic block. If we don't we cannot get next child.
1596 if (basic_block_ == nullptr) {
1597 return nullptr;
1598 }
1599
1600 // If we haven't visited fallthrough, return that.
1601 if (visited_fallthrough_ == false) {
1602 visited_fallthrough_ = true;
1603
1604 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1605 if (result != nullptr) {
1606 return result;
1607 }
1608 }
1609
1610 // If we haven't visited taken, return that.
1611 if (visited_taken_ == false) {
1612 visited_taken_ = true;
1613
1614 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1615 if (result != nullptr) {
1616 return result;
1617 }
1618 }
1619
1620 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1621 if (have_successors_ == true) {
1622 // Get information about next successor block.
1623 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1624
1625 // If we don't have anymore successors, return nullptr.
1626 if (successor_block_info != nullptr) {
1627 return mir_graph_->GetBasicBlock(successor_block_info->block);
1628 }
1629 }
1630
1631 // We do not have anything.
1632 return nullptr;
1633}
1634
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001635BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1636 MIRGraph* mir_graph = c_unit->mir_graph.get();
1637 return Copy(mir_graph);
1638}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001639
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001640BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1641 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001642
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001643 // We don't do a memcpy style copy here because it would lead to a lot of things
1644 // to clean up. Let us do it by hand instead.
1645 // Copy in taken and fallthrough.
1646 result_bb->fall_through = fall_through;
1647 result_bb->taken = taken;
1648
1649 // Copy successor links if needed.
1650 ArenaAllocator* arena = mir_graph->GetArena();
1651
1652 result_bb->successor_block_list_type = successor_block_list_type;
1653 if (result_bb->successor_block_list_type != kNotUsed) {
1654 size_t size = successor_blocks->Size();
1655 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1656 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1657 while (true) {
1658 SuccessorBlockInfo* sbi_old = iterator.Next();
1659 if (sbi_old == nullptr) {
1660 break;
1661 }
1662 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1663 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1664 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001665 }
1666 }
1667
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001668 // Copy offset, method.
1669 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001670
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001671 // Now copy instructions.
1672 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1673 // Get a copy first.
1674 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001675
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001676 // Append it.
1677 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001678 }
1679
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001680 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001681}
1682
1683MIR* MIR::Copy(MIRGraph* mir_graph) {
1684 MIR* res = mir_graph->NewMIR();
1685 *res = *this;
1686
1687 // Remove links
1688 res->next = nullptr;
1689 res->bb = NullBasicBlockId;
1690 res->ssa_rep = nullptr;
1691
1692 return res;
1693}
1694
1695MIR* MIR::Copy(CompilationUnit* c_unit) {
1696 return Copy(c_unit->mir_graph.get());
1697}
1698
1699uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1700 // Default result.
1701 int res = 0;
1702
1703 // We are basically setting the iputs to their igets counterparts.
1704 switch (opcode) {
1705 case Instruction::IPUT:
1706 case Instruction::IPUT_OBJECT:
1707 case Instruction::IPUT_BOOLEAN:
1708 case Instruction::IPUT_BYTE:
1709 case Instruction::IPUT_CHAR:
1710 case Instruction::IPUT_SHORT:
1711 case Instruction::IPUT_QUICK:
1712 case Instruction::IPUT_OBJECT_QUICK:
1713 case Instruction::APUT:
1714 case Instruction::APUT_OBJECT:
1715 case Instruction::APUT_BOOLEAN:
1716 case Instruction::APUT_BYTE:
1717 case Instruction::APUT_CHAR:
1718 case Instruction::APUT_SHORT:
1719 case Instruction::SPUT:
1720 case Instruction::SPUT_OBJECT:
1721 case Instruction::SPUT_BOOLEAN:
1722 case Instruction::SPUT_BYTE:
1723 case Instruction::SPUT_CHAR:
1724 case Instruction::SPUT_SHORT:
1725 // Skip the VR containing what to store.
1726 res = 1;
1727 break;
1728 case Instruction::IPUT_WIDE:
1729 case Instruction::IPUT_WIDE_QUICK:
1730 case Instruction::APUT_WIDE:
1731 case Instruction::SPUT_WIDE:
1732 // Skip the two VRs containing what to store.
1733 res = 2;
1734 break;
1735 default:
1736 // Do nothing in the general case.
1737 break;
1738 }
1739
1740 return res;
1741}
1742
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001743/**
1744 * @brief Given a decoded instruction, it checks whether the instruction
1745 * sets a constant and if it does, more information is provided about the
1746 * constant being set.
1747 * @param ptr_value pointer to a 64-bit holder for the constant.
1748 * @param wide Updated by function whether a wide constant is being set by bytecode.
1749 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1750 */
1751bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1752 bool sets_const = true;
1753 int64_t value = vB;
1754
1755 DCHECK(ptr_value != nullptr);
1756 DCHECK(wide != nullptr);
1757
1758 switch (opcode) {
1759 case Instruction::CONST_4:
1760 case Instruction::CONST_16:
1761 case Instruction::CONST:
1762 *wide = false;
1763 value <<= 32; // In order to get the sign extend.
1764 value >>= 32;
1765 break;
1766 case Instruction::CONST_HIGH16:
1767 *wide = false;
1768 value <<= 48; // In order to get the sign extend.
1769 value >>= 32;
1770 break;
1771 case Instruction::CONST_WIDE_16:
1772 case Instruction::CONST_WIDE_32:
1773 *wide = true;
1774 value <<= 32; // In order to get the sign extend.
1775 value >>= 32;
1776 break;
1777 case Instruction::CONST_WIDE:
1778 *wide = true;
1779 value = vB_wide;
1780 break;
1781 case Instruction::CONST_WIDE_HIGH16:
1782 *wide = true;
1783 value <<= 48; // In order to get the sign extend.
1784 break;
1785 default:
1786 sets_const = false;
1787 break;
1788 }
1789
1790 if (sets_const) {
1791 *ptr_value = value;
1792 }
1793
1794 return sets_const;
1795}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001796
1797void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1798 // Reset flags for all MIRs in bb.
1799 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1800 mir->optimization_flags &= (~reset_flags);
1801 }
1802}
1803
1804void BasicBlock::Hide(CompilationUnit* c_unit) {
1805 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1806 block_type = kDalvikByteCode;
1807
1808 // Mark it as hidden.
1809 hidden = true;
1810
1811 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1812 // are updated to know that they no longer have a parent.
1813 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1814 mir->bb = NullBasicBlockId;
1815 }
1816 first_mir_insn = nullptr;
1817 last_mir_insn = nullptr;
1818
1819 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1820
1821 MIRGraph* mir_graph = c_unit->mir_graph.get();
1822 while (true) {
1823 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1824 if (pred_bb == nullptr) {
1825 break;
1826 }
1827
1828 // Sadly we have to go through the children by hand here.
1829 pred_bb->ReplaceChild(id, NullBasicBlockId);
1830 }
1831
1832 // Iterate through children of bb we are hiding.
1833 ChildBlockIterator successorChildIter(this, mir_graph);
1834
1835 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1836 // Replace child with null child.
1837 childPtr->predecessors->Delete(id);
1838 }
1839}
1840
1841bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1842 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1843 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1844 // then it is not live out of this BB.
1845 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1846
1847 int last_ssa_reg = -1;
1848
1849 // Walk through the MIRs backwards.
1850 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1851 // Get ssa rep.
1852 SSARepresentation *ssa_rep = mir->ssa_rep;
1853
1854 // Go through the defines for this MIR.
1855 for (int i = 0; i < ssa_rep->num_defs; i++) {
1856 DCHECK(ssa_rep->defs != nullptr);
1857
1858 // Get the ssa reg.
1859 int def_ssa_reg = ssa_rep->defs[i];
1860
1861 // Get dalvik reg.
1862 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1863
1864 // Compare dalvik regs.
1865 if (dalvik_reg == def_dalvik_reg) {
1866 // We found a def of the register that we are being asked about.
1867 // Remember it.
1868 last_ssa_reg = def_ssa_reg;
1869 }
1870 }
1871 }
1872
1873 if (last_ssa_reg == -1) {
1874 // If we get to this point we couldn't find a define of register user asked about.
1875 // Let's assume the user knows what he's doing so we can be safe and say that if we
1876 // couldn't find a def, it is live out.
1877 return true;
1878 }
1879
1880 // If it is not -1, we found a match, is it ssa_reg?
1881 return (ssa_reg == last_ssa_reg);
1882}
1883
1884bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1885 // We need to check taken, fall_through, and successor_blocks to replace.
1886 bool found = false;
1887 if (taken == old_bb) {
1888 taken = new_bb;
1889 found = true;
1890 }
1891
1892 if (fall_through == old_bb) {
1893 fall_through = new_bb;
1894 found = true;
1895 }
1896
1897 if (successor_block_list_type != kNotUsed) {
1898 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1899 while (true) {
1900 SuccessorBlockInfo* successor_block_info = iterator.Next();
1901 if (successor_block_info == nullptr) {
1902 break;
1903 }
1904 if (successor_block_info->block == old_bb) {
1905 successor_block_info->block = new_bb;
1906 found = true;
1907 }
1908 }
1909 }
1910
1911 return found;
1912}
1913
1914void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1915 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1916 bool found = false;
1917
1918 while (true) {
1919 BasicBlockId pred_bb_id = iterator.Next();
1920
1921 if (pred_bb_id == NullBasicBlockId) {
1922 break;
1923 }
1924
1925 if (pred_bb_id == old_parent) {
1926 size_t idx = iterator.GetIndex() - 1;
1927 predecessors->Put(idx, new_parent);
1928 found = true;
1929 break;
1930 }
1931 }
1932
1933 // If not found, add it.
1934 if (found == false) {
1935 predecessors->Insert(new_parent);
1936 }
1937}
1938
1939// Create a new basic block with block_id as num_blocks_ that is
1940// post-incremented.
1941BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1942 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1943 block_list_.Insert(res);
1944 return res;
1945}
1946
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001947void MIRGraph::CalculateBasicBlockInformation() {
1948 PassDriverMEPostOpt driver(cu_);
1949 driver.Launch();
1950}
1951
1952void MIRGraph::InitializeBasicBlockData() {
1953 num_blocks_ = block_list_.Size();
1954}
1955
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001956} // namespace art