blob: 0ef66d2b7018d4a89951f60499a434aaae83fad5 [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"
Vladimir Marko5816ed42013-11-27 17:04:20 +000029
buzbee311ca162013-02-28 15:56:43 -080030namespace art {
31
32#define MAX_PATTERN_LEN 5
33
buzbee1fd33462013-03-25 13:40:45 -070034const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
35 "Phi",
36 "Copy",
37 "FusedCmplFloat",
38 "FusedCmpgFloat",
39 "FusedCmplDouble",
40 "FusedCmpgDouble",
41 "FusedCmpLong",
42 "Nop",
43 "OpNullCheck",
44 "OpRangeCheck",
45 "OpDivZeroCheck",
46 "Check1",
47 "Check2",
48 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040049 "ConstVector",
50 "MoveVector",
51 "PackedMultiply",
52 "PackedAddition",
53 "PackedSubtract",
54 "PackedShiftLeft",
55 "PackedSignedShiftRight",
56 "PackedUnsignedShiftRight",
57 "PackedAnd",
58 "PackedOr",
59 "PackedXor",
60 "PackedAddReduce",
61 "PackedReduce",
62 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070063};
64
buzbee862a7602013-04-05 10:58:54 -070065MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070066 : reg_location_(NULL),
67 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080068 ssa_base_vregs_(NULL),
69 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080070 vreg_to_ssa_map_(NULL),
71 ssa_last_defs_(NULL),
72 is_constant_v_(NULL),
73 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070074 use_counts_(arena, 256, kGrowableArrayMisc),
75 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080076 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070077 dfs_order_(NULL),
78 dfs_post_order_(NULL),
79 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070080 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080081 i_dom_list_(NULL),
82 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000083 temp_scoped_alloc_(),
84 temp_insn_data_(nullptr),
85 temp_bit_vector_size_(0u),
86 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070087 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080088 try_block_addr_(NULL),
89 entry_block_(NULL),
90 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080091 num_blocks_(0),
92 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070093 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080094 current_method_(kInvalidEntry),
95 current_offset_(kInvalidEntry),
96 def_count_(0),
97 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070098 num_ssa_regs_(0),
99 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700100 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
101 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700102 arena_(arena),
103 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800104 forward_branches_(0),
105 compiler_temps_(arena, 6, kGrowableArrayMisc),
106 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800107 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000108 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000109 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000110 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000111 sfield_lowering_infos_(arena, 0u),
112 method_lowering_infos_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700113 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800114 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
115 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800116}
117
Ian Rogers6282dc12013-04-18 15:54:02 -0700118MIRGraph::~MIRGraph() {
119 STLDeleteElements(&m_units_);
120}
121
buzbee311ca162013-02-28 15:56:43 -0800122/*
123 * Parse an instruction, return the length of the instruction
124 */
Ian Rogers29a26482014-05-02 15:27:29 -0700125int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
126 const Instruction* inst = Instruction::At(code_ptr);
127 decoded_instruction->opcode = inst->Opcode();
128 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
129 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
130 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
131 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
132 if (inst->HasVarArgs()) {
133 inst->GetVarArgs(decoded_instruction->arg);
134 }
135 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800136}
137
138
139/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700140BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700141 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700142 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800143 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700144 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800145 while (insn) {
146 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700147 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800148 insn = insn->next;
149 }
150 if (insn == NULL) {
151 LOG(FATAL) << "Break split failed";
152 }
buzbee862a7602013-04-05 10:58:54 -0700153 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
154 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800155
156 bottom_block->start_offset = code_offset;
157 bottom_block->first_mir_insn = insn;
158 bottom_block->last_mir_insn = orig_block->last_mir_insn;
159
160 /* If this block was terminated by a return, the flag needs to go with the bottom block */
161 bottom_block->terminated_by_return = orig_block->terminated_by_return;
162 orig_block->terminated_by_return = false;
163
buzbee311ca162013-02-28 15:56:43 -0800164 /* Handle the taken path */
165 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700166 if (bottom_block->taken != NullBasicBlockId) {
167 orig_block->taken = NullBasicBlockId;
168 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
169 bb_taken->predecessors->Delete(orig_block->id);
170 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800171 }
172
173 /* Handle the fallthrough path */
174 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700175 orig_block->fall_through = bottom_block->id;
176 bottom_block->predecessors->Insert(orig_block->id);
177 if (bottom_block->fall_through != NullBasicBlockId) {
178 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
179 bb_fall_through->predecessors->Delete(orig_block->id);
180 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800181 }
182
183 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700184 if (orig_block->successor_block_list_type != kNotUsed) {
185 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
186 bottom_block->successor_blocks = orig_block->successor_blocks;
187 orig_block->successor_block_list_type = kNotUsed;
188 orig_block->successor_blocks = NULL;
189 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800190 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700191 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800192 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700193 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
194 bb->predecessors->Delete(orig_block->id);
195 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800196 }
197 }
198
buzbee0d829482013-10-11 15:24:55 -0700199 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700200 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800201
buzbee311ca162013-02-28 15:56:43 -0800202 /*
203 * Update the immediate predecessor block pointer so that outgoing edges
204 * can be applied to the proper block.
205 */
206 if (immed_pred_block_p) {
207 DCHECK_EQ(*immed_pred_block_p, orig_block);
208 *immed_pred_block_p = bottom_block;
209 }
buzbeeb48819d2013-09-14 16:15:25 -0700210
211 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000212 DCHECK(insn != nullptr);
213 DCHECK(insn != orig_block->first_mir_insn);
214 DCHECK(insn == bottom_block->first_mir_insn);
215 DCHECK_EQ(insn->offset, bottom_block->start_offset);
216 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
217 !IsPseudoMirOp(insn->dalvikInsn.opcode));
218 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
219 MIR* p = insn;
220 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
221 while (p != bottom_block->last_mir_insn) {
222 p = p->next;
223 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700224 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700225 int opcode = p->dalvikInsn.opcode;
226 /*
227 * Some messiness here to ensure that we only enter real opcodes and only the
228 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000229 * CHECK and work portions. Since the 2nd half of a split operation is always
230 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700231 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000232 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
233 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700234 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
235 }
buzbeeb48819d2013-09-14 16:15:25 -0700236 }
237
buzbee311ca162013-02-28 15:56:43 -0800238 return bottom_block;
239}
240
241/*
242 * Given a code offset, find out the block that starts with it. If the offset
243 * is in the middle of an existing block, split it into two. If immed_pred_block_p
244 * is not non-null and is the block being split, update *immed_pred_block_p to
245 * point to the bottom block so that outgoing edges can be set up properly
246 * (by the caller)
247 * Utilizes a map for fast lookup of the typical cases.
248 */
buzbee0d829482013-10-11 15:24:55 -0700249BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700250 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700251 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800252 return NULL;
253 }
buzbeeb48819d2013-09-14 16:15:25 -0700254
255 int block_id = dex_pc_to_block_map_.Get(code_offset);
256 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
257
258 if ((bb != NULL) && (bb->start_offset == code_offset)) {
259 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700260 return bb;
261 }
buzbee311ca162013-02-28 15:56:43 -0800262
buzbeeb48819d2013-09-14 16:15:25 -0700263 // No direct hit.
264 if (!create) {
265 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800266 }
267
buzbeeb48819d2013-09-14 16:15:25 -0700268 if (bb != NULL) {
269 // The target exists somewhere in an existing block.
270 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
271 }
272
273 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700274 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
275 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800276 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700277 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800278 return bb;
279}
280
buzbeeb48819d2013-09-14 16:15:25 -0700281
buzbee311ca162013-02-28 15:56:43 -0800282/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700283void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800284 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700285 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800286
287 if (tries_size == 0) {
288 return;
289 }
290
291 for (int i = 0; i < tries_size; i++) {
292 const DexFile::TryItem* pTry =
293 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700294 DexOffset start_offset = pTry->start_addr_;
295 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800296 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700297 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800298 }
299 }
300
301 // Iterate over each of the handlers to enqueue the empty Catch blocks
302 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
303 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
304 for (uint32_t idx = 0; idx < handlers_size; idx++) {
305 CatchHandlerIterator iterator(handlers_ptr);
306 for (; iterator.HasNext(); iterator.Next()) {
307 uint32_t address = iterator.GetHandlerAddress();
308 FindBlock(address, false /* split */, true /*create*/,
309 /* immed_pred_block_p */ NULL);
310 }
311 handlers_ptr = iterator.EndDataPointer();
312 }
313}
314
315/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700316BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
317 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700318 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700319 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800320 switch (insn->dalvikInsn.opcode) {
321 case Instruction::GOTO:
322 case Instruction::GOTO_16:
323 case Instruction::GOTO_32:
324 target += insn->dalvikInsn.vA;
325 break;
326 case Instruction::IF_EQ:
327 case Instruction::IF_NE:
328 case Instruction::IF_LT:
329 case Instruction::IF_GE:
330 case Instruction::IF_GT:
331 case Instruction::IF_LE:
332 cur_block->conditional_branch = true;
333 target += insn->dalvikInsn.vC;
334 break;
335 case Instruction::IF_EQZ:
336 case Instruction::IF_NEZ:
337 case Instruction::IF_LTZ:
338 case Instruction::IF_GEZ:
339 case Instruction::IF_GTZ:
340 case Instruction::IF_LEZ:
341 cur_block->conditional_branch = true;
342 target += insn->dalvikInsn.vB;
343 break;
344 default:
345 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
346 }
buzbeeb48819d2013-09-14 16:15:25 -0700347 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800348 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
349 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700350 cur_block->taken = taken_block->id;
351 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800352
353 /* Always terminate the current block for conditional branches */
354 if (flags & Instruction::kContinue) {
355 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
356 /*
357 * If the method is processed
358 * in sequential order from the
359 * beginning, we don't need to
360 * specify split for continue
361 * blocks. However, this
362 * routine can be called by
363 * compileLoop, which starts
364 * parsing the method from an
365 * arbitrary address in the
366 * method body.
367 */
368 true,
369 /* create */
370 true,
371 /* immed_pred_block_p */
372 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700373 cur_block->fall_through = fallthrough_block->id;
374 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800375 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700376 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800377 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800378 }
379 return cur_block;
380}
381
382/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800383BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
384 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800385 const uint16_t* switch_data =
386 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
387 int size;
388 const int* keyTable;
389 const int* target_table;
390 int i;
391 int first_key;
392
393 /*
394 * Packed switch data format:
395 * ushort ident = 0x0100 magic value
396 * ushort size number of entries in the table
397 * int first_key first (and lowest) switch case value
398 * int targets[size] branch targets, relative to switch opcode
399 *
400 * Total size is (4+size*2) 16-bit code units.
401 */
402 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
403 DCHECK_EQ(static_cast<int>(switch_data[0]),
404 static_cast<int>(Instruction::kPackedSwitchSignature));
405 size = switch_data[1];
406 first_key = switch_data[2] | (switch_data[3] << 16);
407 target_table = reinterpret_cast<const int*>(&switch_data[4]);
408 keyTable = NULL; // Make the compiler happy
409 /*
410 * Sparse switch data format:
411 * ushort ident = 0x0200 magic value
412 * ushort size number of entries in the table; > 0
413 * int keys[size] keys, sorted low-to-high; 32-bit aligned
414 * int targets[size] branch targets, relative to switch opcode
415 *
416 * Total size is (2+size*4) 16-bit code units.
417 */
418 } else {
419 DCHECK_EQ(static_cast<int>(switch_data[0]),
420 static_cast<int>(Instruction::kSparseSwitchSignature));
421 size = switch_data[1];
422 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
423 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
424 first_key = 0; // To make the compiler happy
425 }
426
buzbee0d829482013-10-11 15:24:55 -0700427 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800428 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700429 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800430 }
buzbee0d829482013-10-11 15:24:55 -0700431 cur_block->successor_block_list_type =
432 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
433 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700434 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800435
436 for (i = 0; i < size; i++) {
437 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
438 /* create */ true, /* immed_pred_block_p */ &cur_block);
439 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700440 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000441 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700442 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800443 successor_block_info->key =
444 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
445 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700446 cur_block->successor_blocks->Insert(successor_block_info);
447 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800448 }
449
450 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700451 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
452 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700453 cur_block->fall_through = fallthrough_block->id;
454 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800455 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800456}
457
458/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700459BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
460 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700461 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700462 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800463 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
464 bool build_all_edges =
465 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800466
467 /* In try block */
468 if (in_try_block) {
469 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
470
buzbee0d829482013-10-11 15:24:55 -0700471 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800472 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
473 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700474 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800475 }
476
buzbee0d829482013-10-11 15:24:55 -0700477 cur_block->successor_block_list_type = kCatch;
478 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700479 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800480
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700481 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800482 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
483 false /* creat */, NULL /* immed_pred_block_p */);
484 catch_block->catch_entry = true;
485 if (kIsDebugBuild) {
486 catches_.insert(catch_block->start_offset);
487 }
488 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000489 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700490 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800491 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700492 cur_block->successor_blocks->Insert(successor_block_info);
493 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800494 }
buzbee17189ac2013-11-08 11:07:02 -0800495 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700496 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700497 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700498 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800499 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700500 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800501 }
502
buzbee17189ac2013-11-08 11:07:02 -0800503 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800504 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700505 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800506 // Force creation of new block following THROW via side-effect
507 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
508 /* immed_pred_block_p */ NULL);
509 }
510 if (!in_try_block) {
511 // Don't split a THROW that can't rethrow - we're done.
512 return cur_block;
513 }
514 }
515
buzbee17189ac2013-11-08 11:07:02 -0800516 if (!build_all_edges) {
517 /*
518 * Even though there is an exception edge here, control cannot return to this
519 * method. Thus, for the purposes of dataflow analysis and optimization, we can
520 * ignore the edge. Doing this reduces compile time, and increases the scope
521 * of the basic-block level optimization pass.
522 */
523 return cur_block;
524 }
525
buzbee311ca162013-02-28 15:56:43 -0800526 /*
527 * Split the potentially-throwing instruction into two parts.
528 * The first half will be a pseudo-op that captures the exception
529 * edges and terminates the basic block. It always falls through.
530 * Then, create a new basic block that begins with the throwing instruction
531 * (minus exceptions). Note: this new basic block must NOT be entered into
532 * the block_map. If the potentially-throwing instruction is the target of a
533 * future branch, we need to find the check psuedo half. The new
534 * basic block containing the work portion of the instruction should
535 * only be entered via fallthrough from the block containing the
536 * pseudo exception edge MIR. Note also that this new block is
537 * not automatically terminated after the work portion, and may
538 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700539 *
540 * Note also that the dex_pc_to_block_map_ entry for the potentially
541 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800542 */
buzbee862a7602013-04-05 10:58:54 -0700543 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
544 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800545 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700546 cur_block->fall_through = new_block->id;
547 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700548 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800549 *new_insn = *insn;
550 insn->dalvikInsn.opcode =
551 static_cast<Instruction::Code>(kMirOpCheck);
552 // Associate the two halves
553 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700554 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800555 return new_block;
556}
557
558/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
559void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700560 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700561 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800562 current_code_item_ = code_item;
563 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
564 current_method_ = m_units_.size();
565 current_offset_ = 0;
566 // TODO: will need to snapshot stack image and use that as the mir context identification.
567 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000568 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
569 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800570 const uint16_t* code_ptr = current_code_item_->insns_;
571 const uint16_t* code_end =
572 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
573
574 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700575 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700576 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700577 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 -0700578
buzbee311ca162013-02-28 15:56:43 -0800579 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700580 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
581 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800582
583 // If this is the first method, set up default entry and exit blocks.
584 if (current_method_ == 0) {
585 DCHECK(entry_block_ == NULL);
586 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700587 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700588 // Use id 0 to represent a null block.
589 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
590 DCHECK_EQ(null_block->id, NullBasicBlockId);
591 null_block->hidden = true;
592 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700593 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700594 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700595 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700596 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800597 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
598 cu_->dex_file = &dex_file;
599 cu_->class_def_idx = class_def_idx;
600 cu_->method_idx = method_idx;
601 cu_->access_flags = access_flags;
602 cu_->invoke_type = invoke_type;
603 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
604 cu_->num_ins = current_code_item_->ins_size_;
605 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
606 cu_->num_outs = current_code_item_->outs_size_;
607 cu_->num_dalvik_registers = current_code_item_->registers_size_;
608 cu_->insns = current_code_item_->insns_;
609 cu_->code_item = current_code_item_;
610 } else {
611 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
612 /*
613 * Will need to manage storage for ins & outs, push prevous state and update
614 * insert point.
615 */
616 }
617
618 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700619 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700620 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800621 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700622 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700623 // TODO: for inlining support, insert at the insert point rather than entry block.
624 entry_block_->fall_through = cur_block->id;
625 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800626
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000627 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800628 ProcessTryCatchBlocks();
629
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000630 uint64_t merged_df_flags = 0u;
631
buzbee311ca162013-02-28 15:56:43 -0800632 /* Parse all instructions and put them into containing basic blocks */
633 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700634 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800635 insn->offset = current_offset_;
636 insn->m_unit_index = current_method_;
637 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800638 Instruction::Code opcode = insn->dalvikInsn.opcode;
639 if (opcode_count_ != NULL) {
640 opcode_count_[static_cast<int>(opcode)]++;
641 }
642
buzbee311ca162013-02-28 15:56:43 -0800643 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800644 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800645
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700646 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000647 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800648
649 if (df_flags & DF_HAS_DEFS) {
650 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
651 }
652
buzbee1da1e2f2013-11-15 13:37:01 -0800653 if (df_flags & DF_LVN) {
654 cur_block->use_lvn = true; // Run local value numbering on this basic block.
655 }
656
buzbee27247762013-07-28 12:03:58 -0700657 // Check for inline data block signatures
658 if (opcode == Instruction::NOP) {
659 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
660 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
661 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
662 uint16_t following_raw_instruction = code_ptr[1];
663 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
664 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
665 (following_raw_instruction == Instruction::kArrayDataSignature)) {
666 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
667 }
668 }
669 if (width == 1) {
670 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700671 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700672 } else {
buzbee0d829482013-10-11 15:24:55 -0700673 DCHECK(cur_block->fall_through == NullBasicBlockId);
674 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700675 // Unreachable instruction, mark for no continuation.
676 flags &= ~Instruction::kContinue;
677 }
678 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700679 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700680 }
681
buzbeeb48819d2013-09-14 16:15:25 -0700682 // Associate the starting dex_pc for this opcode with its containing basic block.
683 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
684
buzbee27247762013-07-28 12:03:58 -0700685 code_ptr += width;
686
buzbee311ca162013-02-28 15:56:43 -0800687 if (flags & Instruction::kBranch) {
688 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
689 width, flags, code_ptr, code_end);
690 } else if (flags & Instruction::kReturn) {
691 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700692 cur_block->fall_through = exit_block_->id;
693 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800694 /*
695 * Terminate the current block if there are instructions
696 * afterwards.
697 */
698 if (code_ptr < code_end) {
699 /*
700 * Create a fallthrough block for real instructions
701 * (incl. NOP).
702 */
buzbee27247762013-07-28 12:03:58 -0700703 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
704 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800705 }
706 } else if (flags & Instruction::kThrow) {
707 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
708 code_ptr, code_end);
709 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800710 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800711 }
buzbeeb1f1d642014-02-27 12:55:32 -0800712 if (verify_flags & Instruction::kVerifyVarArgRange) {
713 /*
714 * The Quick backend's runtime model includes a gap between a method's
715 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
716 * which spans the gap is somewhat complicated, and should not happen
717 * in normal usage of dx. Punt to the interpreter.
718 */
719 int first_reg_in_range = insn->dalvikInsn.vC;
720 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
721 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
722 punt_to_interpreter_ = true;
723 }
724 }
buzbee311ca162013-02-28 15:56:43 -0800725 current_offset_ += width;
726 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
727 false, /* immed_pred_block_p */ NULL);
728 if (next_block) {
729 /*
730 * The next instruction could be the target of a previously parsed
731 * forward branch so a block is already created. If the current
732 * instruction is not an unconditional branch, connect them through
733 * the fall-through link.
734 */
buzbee0d829482013-10-11 15:24:55 -0700735 DCHECK(cur_block->fall_through == NullBasicBlockId ||
736 GetBasicBlock(cur_block->fall_through) == next_block ||
737 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800738
buzbee0d829482013-10-11 15:24:55 -0700739 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
740 cur_block->fall_through = next_block->id;
741 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800742 }
743 cur_block = next_block;
744 }
745 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000746 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000747
buzbee311ca162013-02-28 15:56:43 -0800748 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
749 DumpCFG("/sdcard/1_post_parse_cfg/", true);
750 }
751
752 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700753 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800754 }
755}
756
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700757void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800758 DCHECK(opcode_count_ != NULL);
759 LOG(INFO) << "Opcode Count";
760 for (int i = 0; i < kNumPackedOpcodes; i++) {
761 if (opcode_count_[i] != 0) {
762 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
763 << " " << opcode_count_[i];
764 }
765 }
766}
767
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700768uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
769 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
770 return oat_data_flow_attributes_[opcode];
771}
772
773uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
774 DCHECK(mir != nullptr);
775 Instruction::Code opcode = mir->dalvikInsn.opcode;
776 return GetDataFlowAttributes(opcode);
777}
778
buzbee311ca162013-02-28 15:56:43 -0800779// TODO: use a configurable base prefix, and adjust callers to supply pass name.
780/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800781void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800782 FILE* file;
783 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
784 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800785 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
786 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
787 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800788 file = fopen(fname.c_str(), "w");
789 if (file == NULL) {
790 return;
791 }
792 fprintf(file, "digraph G {\n");
793
794 fprintf(file, " rankdir=TB\n");
795
796 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
797 int idx;
798
799 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700800 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800801 BasicBlock *bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700802 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800803 if (bb->block_type == kDead) continue;
804 if (bb->block_type == kEntryBlock) {
805 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
806 } else if (bb->block_type == kExitBlock) {
807 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
808 } else if (bb->block_type == kDalvikByteCode) {
809 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
810 bb->start_offset, bb->id);
811 const MIR *mir;
812 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
813 bb->first_mir_insn ? " | " : " ");
814 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
815 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400816 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
817 if (opcode == kMirOpConstVector) {
818 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
819 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
820 mir->dalvikInsn.vA,
821 mir->dalvikInsn.vB,
822 mir->dalvikInsn.arg[0],
823 mir->dalvikInsn.arg[1],
824 mir->dalvikInsn.arg[2],
825 mir->dalvikInsn.arg[3],
826 mir->next ? " | " : " ");
827 } else {
828 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
829 extended_mir_op_names_[opcode - kMirOpFirst],
830 mir->dalvikInsn.vA,
831 mir->dalvikInsn.vB,
832 mir->dalvikInsn.vC,
833 mir->next ? " | " : " ");
834 }
835 } else {
836 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
837 mir->ssa_rep ? GetDalvikDisassembly(mir) :
838 (opcode < kMirOpFirst) ?
839 Instruction::Name(mir->dalvikInsn.opcode) :
840 extended_mir_op_names_[opcode - kMirOpFirst],
841 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
842 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
843 mir->next ? " | " : " ");
844 }
buzbee311ca162013-02-28 15:56:43 -0800845 }
846 fprintf(file, " }\"];\n\n");
847 } else if (bb->block_type == kExceptionHandling) {
848 char block_name[BLOCK_NAME_LEN];
849
850 GetBlockName(bb, block_name);
851 fprintf(file, " %s [shape=invhouse];\n", block_name);
852 }
853
854 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
855
buzbee0d829482013-10-11 15:24:55 -0700856 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800857 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700858 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800859 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
860 block_name1, block_name2);
861 }
buzbee0d829482013-10-11 15:24:55 -0700862 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800863 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700864 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800865 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
866 }
867
buzbee0d829482013-10-11 15:24:55 -0700868 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800869 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
870 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700871 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
872 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700873 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800874
875 int succ_id = 0;
876 while (true) {
877 if (successor_block_info == NULL) break;
878
buzbee0d829482013-10-11 15:24:55 -0700879 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700880 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800881
882 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
883 succ_id++,
884 successor_block_info->key,
885 dest_block->start_offset,
886 (next_successor_block_info != NULL) ? " | " : " ");
887
888 successor_block_info = next_successor_block_info;
889 }
890 fprintf(file, " }\"];\n\n");
891
892 GetBlockName(bb, block_name1);
893 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
894 block_name1, bb->start_offset, bb->id);
895
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700896 // Link the successor pseudo-block with all of its potential targets.
897 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800898
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700899 succ_id = 0;
900 while (true) {
901 SuccessorBlockInfo *successor_block_info = iter.Next();
902 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800903
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700904 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800905
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700906 GetBlockName(dest_block, block_name2);
907 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
908 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800909 }
910 }
911 fprintf(file, "\n");
912
913 if (cu_->verbose) {
914 /* Display the dominator tree */
915 GetBlockName(bb, block_name1);
916 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
917 block_name1, block_name1);
918 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700919 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800920 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
921 }
922 }
923 }
924 fprintf(file, "}\n");
925 fclose(file);
926}
927
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700928/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700929void BasicBlock::AppendMIR(MIR* mir) {
930 if (first_mir_insn == nullptr) {
931 DCHECK(last_mir_insn == nullptr);
932 last_mir_insn = first_mir_insn = mir;
933 mir->next = nullptr;
buzbee1fd33462013-03-25 13:40:45 -0700934 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700935 last_mir_insn->next = mir;
936 mir->next = nullptr;
937 last_mir_insn = mir;
buzbee1fd33462013-03-25 13:40:45 -0700938 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700939
940 mir->bb = id;
buzbee1fd33462013-03-25 13:40:45 -0700941}
942
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700943/* Insert an MIR instruction to the head of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700944void BasicBlock::PrependMIR(MIR* mir) {
945 if (first_mir_insn == nullptr) {
946 DCHECK(last_mir_insn == nullptr);
947 last_mir_insn = first_mir_insn = mir;
948 mir->next = nullptr;
buzbee1fd33462013-03-25 13:40:45 -0700949 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700950 mir->next = first_mir_insn;
951 first_mir_insn = mir;
buzbee1fd33462013-03-25 13:40:45 -0700952 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700953
954 mir->bb = id;
buzbee1fd33462013-03-25 13:40:45 -0700955}
956
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700957/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700958void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700959 new_mir->next = current_mir->next;
960 current_mir->next = new_mir;
961
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700962 if (last_mir_insn == current_mir) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700963 /* Is the last MIR in the block? */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700964 last_mir_insn = new_mir;
buzbee1fd33462013-03-25 13:40:45 -0700965 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700966
967 new_mir->bb = id;
968}
969
970MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
971 MIR* current = first_mir_insn;
972
973 while (current != nullptr) {
974 MIR* next = current->next;
975
976 if (next == mir) {
977 return current;
978 }
979
980 current = next;
981 }
982
983 return nullptr;
984}
985
986void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
987 if (first_mir_insn == current_mir) {
988 /* Is the first MIR in the block? */
989 first_mir_insn = new_mir;
990 new_mir->bb = id;
991 }
992
993 MIR* prev = FindPreviousMIR(current_mir);
994
995 if (prev != nullptr) {
996 prev->next = new_mir;
997 new_mir->next = current_mir;
998 new_mir->bb = id;
999 }
buzbee1fd33462013-03-25 13:40:45 -07001000}
1001
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001002MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001003 MIR* next_mir = nullptr;
1004
1005 if (current != nullptr) {
1006 next_mir = current->next;
1007 }
1008
1009 if (next_mir == nullptr) {
1010 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001011 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1012 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001013 }
1014 }
1015
1016 return next_mir;
1017}
1018
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001019char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001020 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001021 std::string str;
1022 int flags = 0;
1023 int opcode = insn.opcode;
1024 char* ret;
1025 bool nop = false;
1026 SSARepresentation* ssa_rep = mir->ssa_rep;
1027 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
1028 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1029 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1030
1031 // Handle special cases.
1032 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1033 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1034 str.append(": ");
1035 // Recover the original Dex instruction
1036 insn = mir->meta.throw_insn->dalvikInsn;
1037 ssa_rep = mir->meta.throw_insn->ssa_rep;
1038 defs = ssa_rep->num_defs;
1039 uses = ssa_rep->num_uses;
1040 opcode = insn.opcode;
1041 } else if (opcode == kMirOpNop) {
1042 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001043 // Recover original opcode.
1044 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1045 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001046 nop = true;
1047 }
1048
1049 if (opcode >= kMirOpFirst) {
1050 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1051 } else {
1052 dalvik_format = Instruction::FormatOf(insn.opcode);
1053 flags = Instruction::FlagsOf(insn.opcode);
1054 str.append(Instruction::Name(insn.opcode));
1055 }
1056
1057 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001058 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001059 str.append(StringPrintf(" %s = (%s",
1060 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1061 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001062 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001063 int i;
1064 for (i = 1; i < uses; i++) {
1065 str.append(StringPrintf(", %s:%d",
1066 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1067 incoming[i]));
1068 }
1069 str.append(")");
1070 } else if ((flags & Instruction::kBranch) != 0) {
1071 // For branches, decode the instructions to print out the branch targets.
1072 int offset = 0;
1073 switch (dalvik_format) {
1074 case Instruction::k21t:
1075 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1076 offset = insn.vB;
1077 break;
1078 case Instruction::k22t:
1079 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1080 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1081 offset = insn.vC;
1082 break;
1083 case Instruction::k10t:
1084 case Instruction::k20t:
1085 case Instruction::k30t:
1086 offset = insn.vA;
1087 break;
1088 default:
1089 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1090 }
1091 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1092 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1093 } else {
1094 // For invokes-style formats, treat wide regs as a pair of singles
1095 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1096 (dalvik_format == Instruction::k3rc));
1097 if (defs != 0) {
1098 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1099 if (uses != 0) {
1100 str.append(", ");
1101 }
1102 }
1103 for (int i = 0; i < uses; i++) {
1104 str.append(
1105 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1106 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1107 // For the listing, skip the high sreg.
1108 i++;
1109 }
1110 if (i != (uses -1)) {
1111 str.append(",");
1112 }
1113 }
1114 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001115 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001116 case Instruction::k21s:
1117 case Instruction::k31i:
1118 case Instruction::k21h:
1119 str.append(StringPrintf(", #%d", insn.vB));
1120 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001121 case Instruction::k51l: // Add one wide immediate
Ian Rogers23b03b52014-01-24 11:10:03 -08001122 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001123 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001124 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001125 case Instruction::k31c:
1126 str.append(StringPrintf(", index #%d", insn.vB));
1127 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001128 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001129 str.append(StringPrintf(", index #%d", insn.vC));
1130 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001131 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001132 case Instruction::k22b:
1133 str.append(StringPrintf(", #%d", insn.vC));
1134 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001135 default: {
1136 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001137 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001138 }
buzbee1fd33462013-03-25 13:40:45 -07001139 }
1140 if (nop) {
1141 str.append("]--optimized away");
1142 }
1143 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001144 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001145 strncpy(ret, str.c_str(), length);
1146 return ret;
1147}
1148
1149/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001150void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001151 static const struct { const char before; const char after; } match[] = {
1152 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1153 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1154 };
buzbee1fd33462013-03-25 13:40:45 -07001155 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1156 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1157 }
1158}
1159
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001160std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001161 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1162 // the arena. We should be smarter and just place straight into the arena, or compute the
1163 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001164 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1165}
1166
1167// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001168std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001169 if (reg_location_ == NULL) {
1170 // Pre-SSA - just use the standard name
1171 return GetSSAName(ssa_reg);
1172 }
1173 if (IsConst(reg_location_[ssa_reg])) {
1174 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001175 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001176 ConstantValueWide(reg_location_[ssa_reg]));
1177 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001178 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001179 ConstantValue(reg_location_[ssa_reg]));
1180 }
1181 } else {
1182 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1183 }
1184}
1185
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001186void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001187 switch (bb->block_type) {
1188 case kEntryBlock:
1189 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1190 break;
1191 case kExitBlock:
1192 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1193 break;
1194 case kDalvikByteCode:
1195 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1196 break;
1197 case kExceptionHandling:
1198 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1199 bb->id);
1200 break;
1201 default:
1202 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1203 break;
1204 }
1205}
1206
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001207const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001208 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001209 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1210 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1211}
1212
1213/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001214void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001215 BasicBlock* bb;
1216 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001217 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001218 "Entry Block",
1219 "Code Block",
1220 "Exit Block",
1221 "Exception Handling",
1222 "Catch Block"
1223 };
1224
1225 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1226 LOG(INFO) << cu_->insns << " insns";
1227 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001228 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001229
1230 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001231 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001232 if (bb == NULL) break;
1233 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1234 bb->id,
1235 block_type_names[bb->block_type],
1236 bb->start_offset,
1237 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1238 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001239 if (bb->taken != NullBasicBlockId) {
1240 LOG(INFO) << " Taken branch: block " << bb->taken
1241 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001242 }
buzbee0d829482013-10-11 15:24:55 -07001243 if (bb->fall_through != NullBasicBlockId) {
1244 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1245 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001246 }
1247 }
1248}
1249
1250/*
1251 * Build an array of location records for the incoming arguments.
1252 * Note: one location record per word of arguments, with dummy
1253 * high-word loc for wide arguments. Also pull up any following
1254 * MOVE_RESULT and incorporate it into the invoke.
1255 */
1256CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001257 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001258 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001259 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001260 MIR* move_result_mir = FindMoveResult(bb, mir);
1261 if (move_result_mir == NULL) {
1262 info->result.location = kLocInvalid;
1263 } else {
1264 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001265 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1266 }
1267 info->num_arg_words = mir->ssa_rep->num_uses;
1268 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001269 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001270 for (int i = 0; i < info->num_arg_words; i++) {
1271 info->args[i] = GetRawSrc(mir, i);
1272 }
1273 info->opt_flags = mir->optimization_flags;
1274 info->type = type;
1275 info->is_range = is_range;
1276 info->index = mir->dalvikInsn.vB;
1277 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001278 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001279 return info;
1280}
1281
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001282// Allocate a new MIR.
1283MIR* MIRGraph::NewMIR() {
1284 MIR* mir = new (arena_) MIR();
1285 return mir;
1286}
1287
buzbee862a7602013-04-05 10:58:54 -07001288// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001289BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001290 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001291 kArenaAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001292 bb->block_type = block_type;
1293 bb->id = block_id;
1294 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001295 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001296 (block_type == kExitBlock) ? 2048 : 2,
1297 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001298 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001299 block_id_map_.Put(block_id, block_id);
1300 return bb;
1301}
buzbee1fd33462013-03-25 13:40:45 -07001302
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001303void MIRGraph::InitializeConstantPropagation() {
1304 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001305 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001306}
1307
1308void MIRGraph::InitializeMethodUses() {
1309 // The gate starts by initializing the use counts
1310 int num_ssa_regs = GetNumSSARegs();
1311 use_counts_.Resize(num_ssa_regs + 32);
1312 raw_use_counts_.Resize(num_ssa_regs + 32);
1313 // Initialize list
1314 for (int i = 0; i < num_ssa_regs; i++) {
1315 use_counts_.Insert(0);
1316 raw_use_counts_.Insert(0);
1317 }
1318}
1319
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001320void MIRGraph::SSATransformationStart() {
1321 DCHECK(temp_scoped_alloc_.get() == nullptr);
1322 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1323 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1324 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1325 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1326
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001327 /* Compute the DFS order */
1328 ComputeDFSOrders();
1329
1330 /* Compute the dominator info */
1331 ComputeDominators();
1332
1333 /* Allocate data structures in preparation for SSA conversion */
1334 CompilerInitializeSSAConversion();
1335
1336 /* Find out the "Dalvik reg def x block" relation */
1337 ComputeDefBlockMatrix();
1338
1339 /* Insert phi nodes to dominance frontiers for all variables */
1340 InsertPhiNodes();
1341
1342 /* Rename register names by local defs and phi nodes */
1343 ClearAllVisitedFlags();
1344 DoDFSPreOrderSSARename(GetEntryBlock());
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001345}
1346
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001347void MIRGraph::SSATransformationEnd() {
1348 // Verify the dataflow information after the pass.
1349 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1350 VerifyDataflow();
1351 }
1352
1353 temp_bit_vector_size_ = 0u;
1354 temp_bit_vector_ = nullptr;
1355 DCHECK(temp_scoped_alloc_.get() != nullptr);
1356 temp_scoped_alloc_.reset();
1357}
1358
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001359void MIRGraph::ComputeTopologicalSortOrder() {
1360 std::queue<BasicBlock *> q;
1361 std::map<int, int> visited_cnt_values;
1362
1363 // Clear the nodes.
1364 ClearAllVisitedFlags();
1365
1366 // Create the topological order if need be.
1367 if (topological_order_ != nullptr) {
1368 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, 0);
1369 }
1370 topological_order_->Reset();
1371
1372 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1373 // also fill initial queue.
1374 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1375
1376 while (true) {
1377 BasicBlock* bb = iterator.Next();
1378
1379 if (bb == nullptr) {
1380 break;
1381 }
1382
1383 if (bb->hidden == true) {
1384 continue;
1385 }
1386
1387 visited_cnt_values[bb->id] = bb->predecessors->Size();
1388
1389 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1390 // To process loops we should not wait for dominators.
1391 while (true) {
1392 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1393
1394 if (pred_bb == nullptr) {
1395 break;
1396 }
1397
1398 if (pred_bb->dominators == nullptr || pred_bb->hidden == true) {
1399 continue;
1400 }
1401
1402 // Skip the backward branch.
1403 if (pred_bb->dominators->IsBitSet(bb->id) != 0) {
1404 visited_cnt_values[bb->id]--;
1405 }
1406 }
1407
1408 // Add entry block to queue.
1409 if (visited_cnt_values[bb->id] == 0) {
1410 q.push(bb);
1411 }
1412 }
1413
1414 while (q.size() > 0) {
1415 // Get top.
1416 BasicBlock *bb = q.front();
1417 q.pop();
1418
1419 DCHECK_EQ(bb->hidden, false);
1420
1421 if (bb->IsExceptionBlock() == true) {
1422 continue;
1423 }
1424
1425 // We've visited all the predecessors. So, we can visit bb.
1426 if (bb->visited == false) {
1427 bb->visited = true;
1428
1429 // Now add the basic block.
1430 topological_order_->Insert(bb->id);
1431
1432 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1433 ChildBlockIterator succIter(bb, this);
1434 BasicBlock *successor = succIter.Next();
1435 while (successor != nullptr) {
1436 // one more predecessor was visited.
1437 visited_cnt_values[successor->id]--;
1438
1439 if (visited_cnt_values[successor->id] <= 0 && successor->visited == false && successor->hidden == false) {
1440 q.push(successor);
1441 }
1442
1443 // Take next successor.
1444 successor = succIter.Next();
1445 }
1446 }
1447 }
1448}
1449
1450bool BasicBlock::IsExceptionBlock() const {
1451 if (block_type == kExceptionHandling) {
1452 return true;
1453 }
1454 return false;
1455}
1456
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001457ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1458 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1459 visited_taken_(false), have_successors_(false) {
1460 // Check if we actually do have successors.
1461 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1462 have_successors_ = true;
1463 successor_iter_.Reset(basic_block_->successor_blocks);
1464 }
1465}
1466
1467BasicBlock* ChildBlockIterator::Next() {
1468 // We check if we have a basic block. If we don't we cannot get next child.
1469 if (basic_block_ == nullptr) {
1470 return nullptr;
1471 }
1472
1473 // If we haven't visited fallthrough, return that.
1474 if (visited_fallthrough_ == false) {
1475 visited_fallthrough_ = true;
1476
1477 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1478 if (result != nullptr) {
1479 return result;
1480 }
1481 }
1482
1483 // If we haven't visited taken, return that.
1484 if (visited_taken_ == false) {
1485 visited_taken_ = true;
1486
1487 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1488 if (result != nullptr) {
1489 return result;
1490 }
1491 }
1492
1493 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1494 if (have_successors_ == true) {
1495 // Get information about next successor block.
1496 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1497
1498 // If we don't have anymore successors, return nullptr.
1499 if (successor_block_info != nullptr) {
1500 return mir_graph_->GetBasicBlock(successor_block_info->block);
1501 }
1502 }
1503
1504 // We do not have anything.
1505 return nullptr;
1506}
1507
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001508bool BasicBlock::RemoveMIR(MIR* mir) {
1509 if (mir == nullptr) {
1510 return false;
1511 }
1512
1513 // Find the MIR, and the one before it if they exist.
1514 MIR* current = nullptr;
1515 MIR* prev = nullptr;
1516
1517 // Find the mir we are looking for.
1518 for (current = first_mir_insn; current != nullptr; prev = current, current = current->next) {
1519 if (current == mir) {
1520 break;
1521 }
1522 }
1523
1524 // Did we find it?
1525 if (current != nullptr) {
1526 MIR* next = current->next;
1527
1528 // Just update the links of prev and next and current is almost gone.
1529 if (prev != nullptr) {
1530 prev->next = next;
1531 }
1532
1533 // Exceptions are if first or last mirs are invoke.
1534 if (first_mir_insn == current) {
1535 first_mir_insn = next;
1536 }
1537
1538 if (last_mir_insn == current) {
1539 last_mir_insn = prev;
1540 }
1541
1542 // Found it and removed it.
1543 return true;
1544 }
1545
1546 // We did not find it.
1547 return false;
1548}
1549
1550MIR* MIR::Copy(MIRGraph* mir_graph) {
1551 MIR* res = mir_graph->NewMIR();
1552 *res = *this;
1553
1554 // Remove links
1555 res->next = nullptr;
1556 res->bb = NullBasicBlockId;
1557 res->ssa_rep = nullptr;
1558
1559 return res;
1560}
1561
1562MIR* MIR::Copy(CompilationUnit* c_unit) {
1563 return Copy(c_unit->mir_graph.get());
1564}
1565
1566uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1567 // Default result.
1568 int res = 0;
1569
1570 // We are basically setting the iputs to their igets counterparts.
1571 switch (opcode) {
1572 case Instruction::IPUT:
1573 case Instruction::IPUT_OBJECT:
1574 case Instruction::IPUT_BOOLEAN:
1575 case Instruction::IPUT_BYTE:
1576 case Instruction::IPUT_CHAR:
1577 case Instruction::IPUT_SHORT:
1578 case Instruction::IPUT_QUICK:
1579 case Instruction::IPUT_OBJECT_QUICK:
1580 case Instruction::APUT:
1581 case Instruction::APUT_OBJECT:
1582 case Instruction::APUT_BOOLEAN:
1583 case Instruction::APUT_BYTE:
1584 case Instruction::APUT_CHAR:
1585 case Instruction::APUT_SHORT:
1586 case Instruction::SPUT:
1587 case Instruction::SPUT_OBJECT:
1588 case Instruction::SPUT_BOOLEAN:
1589 case Instruction::SPUT_BYTE:
1590 case Instruction::SPUT_CHAR:
1591 case Instruction::SPUT_SHORT:
1592 // Skip the VR containing what to store.
1593 res = 1;
1594 break;
1595 case Instruction::IPUT_WIDE:
1596 case Instruction::IPUT_WIDE_QUICK:
1597 case Instruction::APUT_WIDE:
1598 case Instruction::SPUT_WIDE:
1599 // Skip the two VRs containing what to store.
1600 res = 2;
1601 break;
1602 default:
1603 // Do nothing in the general case.
1604 break;
1605 }
1606
1607 return res;
1608}
1609
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001610} // namespace art