blob: 79edb871fecc9810310bf0c8fda406c5e020714b [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
Ian Rogers6282dc12013-04-18 15:54:02 -070017#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080018#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080019#include "dex_file-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070020#include "leb128.h"
21#include "mir_graph.h"
buzbee311ca162013-02-28 15:56:43 -080022
Vladimir Marko5816ed42013-11-27 17:04:20 +000023#include "dex/quick/dex_file_to_method_inliner_map.h"
24#include "dex/quick/dex_file_method_inliner.h"
25
buzbee311ca162013-02-28 15:56:43 -080026namespace art {
27
28#define MAX_PATTERN_LEN 5
29
buzbee1fd33462013-03-25 13:40:45 -070030const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
31 "Phi",
32 "Copy",
33 "FusedCmplFloat",
34 "FusedCmpgFloat",
35 "FusedCmplDouble",
36 "FusedCmpgDouble",
37 "FusedCmpLong",
38 "Nop",
39 "OpNullCheck",
40 "OpRangeCheck",
41 "OpDivZeroCheck",
42 "Check1",
43 "Check2",
44 "Select",
45};
46
buzbee862a7602013-04-05 10:58:54 -070047MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070048 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070049 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070050 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080051 ssa_base_vregs_(NULL),
52 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080053 vreg_to_ssa_map_(NULL),
54 ssa_last_defs_(NULL),
55 is_constant_v_(NULL),
56 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070057 use_counts_(arena, 256, kGrowableArrayMisc),
58 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080059 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070060 dfs_order_(NULL),
61 dfs_post_order_(NULL),
62 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080063 i_dom_list_(NULL),
64 def_block_matrix_(NULL),
65 temp_block_v_(NULL),
66 temp_dalvik_register_v_(NULL),
67 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070068 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080069 try_block_addr_(NULL),
70 entry_block_(NULL),
71 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080072 num_blocks_(0),
73 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070074 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080075 current_method_(kInvalidEntry),
76 current_offset_(kInvalidEntry),
77 def_count_(0),
78 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070079 num_ssa_regs_(0),
80 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -070081 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
82 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070083 arena_(arena),
84 backward_branches_(0),
85 forward_branches_(0) {
buzbee862a7602013-04-05 10:58:54 -070086 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -080087}
88
Ian Rogers6282dc12013-04-18 15:54:02 -070089MIRGraph::~MIRGraph() {
90 STLDeleteElements(&m_units_);
91}
92
buzbee311ca162013-02-28 15:56:43 -080093/*
94 * Parse an instruction, return the length of the instruction
95 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070096int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -080097 const Instruction* instruction = Instruction::At(code_ptr);
98 *decoded_instruction = DecodedInstruction(instruction);
99
100 return instruction->SizeInCodeUnits();
101}
102
103
104/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700105BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700106 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700107 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800108 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700109 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800110 while (insn) {
111 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700112 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800113 insn = insn->next;
114 }
115 if (insn == NULL) {
116 LOG(FATAL) << "Break split failed";
117 }
buzbee862a7602013-04-05 10:58:54 -0700118 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
119 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800120
121 bottom_block->start_offset = code_offset;
122 bottom_block->first_mir_insn = insn;
123 bottom_block->last_mir_insn = orig_block->last_mir_insn;
124
125 /* If this block was terminated by a return, the flag needs to go with the bottom block */
126 bottom_block->terminated_by_return = orig_block->terminated_by_return;
127 orig_block->terminated_by_return = false;
128
129 /* Add it to the quick lookup cache */
buzbeeb48819d2013-09-14 16:15:25 -0700130 dex_pc_to_block_map_.Put(bottom_block->start_offset, bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800131
132 /* Handle the taken path */
133 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700134 if (bottom_block->taken != NullBasicBlockId) {
135 orig_block->taken = NullBasicBlockId;
136 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
137 bb_taken->predecessors->Delete(orig_block->id);
138 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800139 }
140
141 /* Handle the fallthrough path */
142 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700143 orig_block->fall_through = bottom_block->id;
144 bottom_block->predecessors->Insert(orig_block->id);
145 if (bottom_block->fall_through != NullBasicBlockId) {
146 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
147 bb_fall_through->predecessors->Delete(orig_block->id);
148 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800149 }
150
151 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700152 if (orig_block->successor_block_list_type != kNotUsed) {
153 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
154 bottom_block->successor_blocks = orig_block->successor_blocks;
155 orig_block->successor_block_list_type = kNotUsed;
156 orig_block->successor_blocks = NULL;
157 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800158 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700159 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800160 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700161 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
162 bb->predecessors->Delete(orig_block->id);
163 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800164 }
165 }
166
buzbee0d829482013-10-11 15:24:55 -0700167 orig_block->last_mir_insn = prev;
168 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800169
buzbee311ca162013-02-28 15:56:43 -0800170 /*
171 * Update the immediate predecessor block pointer so that outgoing edges
172 * can be applied to the proper block.
173 */
174 if (immed_pred_block_p) {
175 DCHECK_EQ(*immed_pred_block_p, orig_block);
176 *immed_pred_block_p = bottom_block;
177 }
buzbeeb48819d2013-09-14 16:15:25 -0700178
179 // Associate dex instructions in the bottom block with the new container.
180 MIR* p = bottom_block->first_mir_insn;
181 while (p != NULL) {
182 int opcode = p->dalvikInsn.opcode;
183 /*
184 * Some messiness here to ensure that we only enter real opcodes and only the
185 * first half of a potentially throwing instruction that has been split into
186 * CHECK and work portions. The 2nd half of a split operation will have a non-null
187 * throw_insn pointer that refers to the 1st half.
188 */
189 if ((opcode == kMirOpCheck) || (!IsPseudoMirOp(opcode) && (p->meta.throw_insn == NULL))) {
190 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
191 }
192 p = (p == bottom_block->last_mir_insn) ? NULL : p->next;
193 }
194
buzbee311ca162013-02-28 15:56:43 -0800195 return bottom_block;
196}
197
198/*
199 * Given a code offset, find out the block that starts with it. If the offset
200 * is in the middle of an existing block, split it into two. If immed_pred_block_p
201 * is not non-null and is the block being split, update *immed_pred_block_p to
202 * point to the bottom block so that outgoing edges can be set up properly
203 * (by the caller)
204 * Utilizes a map for fast lookup of the typical cases.
205 */
buzbee0d829482013-10-11 15:24:55 -0700206BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700207 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700208 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800209 return NULL;
210 }
buzbeeb48819d2013-09-14 16:15:25 -0700211
212 int block_id = dex_pc_to_block_map_.Get(code_offset);
213 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
214
215 if ((bb != NULL) && (bb->start_offset == code_offset)) {
216 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700217 return bb;
218 }
buzbee311ca162013-02-28 15:56:43 -0800219
buzbeeb48819d2013-09-14 16:15:25 -0700220 // No direct hit.
221 if (!create) {
222 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800223 }
224
buzbeeb48819d2013-09-14 16:15:25 -0700225 if (bb != NULL) {
226 // The target exists somewhere in an existing block.
227 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
228 }
229
230 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700231 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
232 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800233 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700234 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800235 return bb;
236}
237
buzbeeb48819d2013-09-14 16:15:25 -0700238
buzbee311ca162013-02-28 15:56:43 -0800239/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700240void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800241 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700242 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800243
244 if (tries_size == 0) {
245 return;
246 }
247
248 for (int i = 0; i < tries_size; i++) {
249 const DexFile::TryItem* pTry =
250 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700251 DexOffset start_offset = pTry->start_addr_;
252 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800253 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700254 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800255 }
256 }
257
258 // Iterate over each of the handlers to enqueue the empty Catch blocks
259 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
260 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
261 for (uint32_t idx = 0; idx < handlers_size; idx++) {
262 CatchHandlerIterator iterator(handlers_ptr);
263 for (; iterator.HasNext(); iterator.Next()) {
264 uint32_t address = iterator.GetHandlerAddress();
265 FindBlock(address, false /* split */, true /*create*/,
266 /* immed_pred_block_p */ NULL);
267 }
268 handlers_ptr = iterator.EndDataPointer();
269 }
270}
271
272/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700273BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
274 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700275 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700276 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800277 switch (insn->dalvikInsn.opcode) {
278 case Instruction::GOTO:
279 case Instruction::GOTO_16:
280 case Instruction::GOTO_32:
281 target += insn->dalvikInsn.vA;
282 break;
283 case Instruction::IF_EQ:
284 case Instruction::IF_NE:
285 case Instruction::IF_LT:
286 case Instruction::IF_GE:
287 case Instruction::IF_GT:
288 case Instruction::IF_LE:
289 cur_block->conditional_branch = true;
290 target += insn->dalvikInsn.vC;
291 break;
292 case Instruction::IF_EQZ:
293 case Instruction::IF_NEZ:
294 case Instruction::IF_LTZ:
295 case Instruction::IF_GEZ:
296 case Instruction::IF_GTZ:
297 case Instruction::IF_LEZ:
298 cur_block->conditional_branch = true;
299 target += insn->dalvikInsn.vB;
300 break;
301 default:
302 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
303 }
buzbeeb48819d2013-09-14 16:15:25 -0700304 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800305 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
306 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700307 cur_block->taken = taken_block->id;
308 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800309
310 /* Always terminate the current block for conditional branches */
311 if (flags & Instruction::kContinue) {
312 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
313 /*
314 * If the method is processed
315 * in sequential order from the
316 * beginning, we don't need to
317 * specify split for continue
318 * blocks. However, this
319 * routine can be called by
320 * compileLoop, which starts
321 * parsing the method from an
322 * arbitrary address in the
323 * method body.
324 */
325 true,
326 /* create */
327 true,
328 /* immed_pred_block_p */
329 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700330 cur_block->fall_through = fallthrough_block->id;
331 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800332 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700333 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800334 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800335 }
336 return cur_block;
337}
338
339/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800340BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
341 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800342 const uint16_t* switch_data =
343 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
344 int size;
345 const int* keyTable;
346 const int* target_table;
347 int i;
348 int first_key;
349
350 /*
351 * Packed switch data format:
352 * ushort ident = 0x0100 magic value
353 * ushort size number of entries in the table
354 * int first_key first (and lowest) switch case value
355 * int targets[size] branch targets, relative to switch opcode
356 *
357 * Total size is (4+size*2) 16-bit code units.
358 */
359 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
360 DCHECK_EQ(static_cast<int>(switch_data[0]),
361 static_cast<int>(Instruction::kPackedSwitchSignature));
362 size = switch_data[1];
363 first_key = switch_data[2] | (switch_data[3] << 16);
364 target_table = reinterpret_cast<const int*>(&switch_data[4]);
365 keyTable = NULL; // Make the compiler happy
366 /*
367 * Sparse switch data format:
368 * ushort ident = 0x0200 magic value
369 * ushort size number of entries in the table; > 0
370 * int keys[size] keys, sorted low-to-high; 32-bit aligned
371 * int targets[size] branch targets, relative to switch opcode
372 *
373 * Total size is (2+size*4) 16-bit code units.
374 */
375 } else {
376 DCHECK_EQ(static_cast<int>(switch_data[0]),
377 static_cast<int>(Instruction::kSparseSwitchSignature));
378 size = switch_data[1];
379 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
380 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
381 first_key = 0; // To make the compiler happy
382 }
383
buzbee0d829482013-10-11 15:24:55 -0700384 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800385 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700386 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800387 }
buzbee0d829482013-10-11 15:24:55 -0700388 cur_block->successor_block_list_type =
389 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
390 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700391 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800392
393 for (i = 0; i < size; i++) {
394 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
395 /* create */ true, /* immed_pred_block_p */ &cur_block);
396 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700397 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
398 ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700399 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800400 successor_block_info->key =
401 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
402 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700403 cur_block->successor_blocks->Insert(successor_block_info);
404 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800405 }
406
407 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700408 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
409 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700410 cur_block->fall_through = fallthrough_block->id;
411 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800412 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800413}
414
415/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700416BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
417 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700418 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700419 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800420 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
421 bool build_all_edges =
422 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800423
424 /* In try block */
425 if (in_try_block) {
426 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
427
buzbee0d829482013-10-11 15:24:55 -0700428 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800429 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
430 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700431 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800432 }
433
buzbee0d829482013-10-11 15:24:55 -0700434 cur_block->successor_block_list_type = kCatch;
435 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700436 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800437
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700438 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800439 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
440 false /* creat */, NULL /* immed_pred_block_p */);
441 catch_block->catch_entry = true;
442 if (kIsDebugBuild) {
443 catches_.insert(catch_block->start_offset);
444 }
445 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700446 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700447 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800448 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700449 cur_block->successor_blocks->Insert(successor_block_info);
450 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800451 }
buzbee17189ac2013-11-08 11:07:02 -0800452 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700453 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700454 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700455 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800456 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700457 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800458 }
459
buzbee17189ac2013-11-08 11:07:02 -0800460 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800461 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700462 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800463 // Force creation of new block following THROW via side-effect
464 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
465 /* immed_pred_block_p */ NULL);
466 }
467 if (!in_try_block) {
468 // Don't split a THROW that can't rethrow - we're done.
469 return cur_block;
470 }
471 }
472
buzbee17189ac2013-11-08 11:07:02 -0800473 if (!build_all_edges) {
474 /*
475 * Even though there is an exception edge here, control cannot return to this
476 * method. Thus, for the purposes of dataflow analysis and optimization, we can
477 * ignore the edge. Doing this reduces compile time, and increases the scope
478 * of the basic-block level optimization pass.
479 */
480 return cur_block;
481 }
482
buzbee311ca162013-02-28 15:56:43 -0800483 /*
484 * Split the potentially-throwing instruction into two parts.
485 * The first half will be a pseudo-op that captures the exception
486 * edges and terminates the basic block. It always falls through.
487 * Then, create a new basic block that begins with the throwing instruction
488 * (minus exceptions). Note: this new basic block must NOT be entered into
489 * the block_map. If the potentially-throwing instruction is the target of a
490 * future branch, we need to find the check psuedo half. The new
491 * basic block containing the work portion of the instruction should
492 * only be entered via fallthrough from the block containing the
493 * pseudo exception edge MIR. Note also that this new block is
494 * not automatically terminated after the work portion, and may
495 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700496 *
497 * Note also that the dex_pc_to_block_map_ entry for the potentially
498 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800499 */
buzbee862a7602013-04-05 10:58:54 -0700500 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
501 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800502 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700503 cur_block->fall_through = new_block->id;
504 new_block->predecessors->Insert(cur_block->id);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700505 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800506 *new_insn = *insn;
507 insn->dalvikInsn.opcode =
508 static_cast<Instruction::Code>(kMirOpCheck);
509 // Associate the two halves
510 insn->meta.throw_insn = new_insn;
511 new_insn->meta.throw_insn = insn;
512 AppendMIR(new_block, new_insn);
513 return new_block;
514}
515
516/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
517void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700518 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700519 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800520 current_code_item_ = code_item;
521 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
522 current_method_ = m_units_.size();
523 current_offset_ = 0;
524 // TODO: will need to snapshot stack image and use that as the mir context identification.
525 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
526 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
527 const uint16_t* code_ptr = current_code_item_->insns_;
528 const uint16_t* code_end =
529 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
530
531 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700532 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700533 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700534 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 -0700535
buzbee311ca162013-02-28 15:56:43 -0800536 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700537 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
538 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800539
540 // If this is the first method, set up default entry and exit blocks.
541 if (current_method_ == 0) {
542 DCHECK(entry_block_ == NULL);
543 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700544 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700545 // Use id 0 to represent a null block.
546 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
547 DCHECK_EQ(null_block->id, NullBasicBlockId);
548 null_block->hidden = true;
549 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700550 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700551 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700552 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700553 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800554 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
555 cu_->dex_file = &dex_file;
556 cu_->class_def_idx = class_def_idx;
557 cu_->method_idx = method_idx;
558 cu_->access_flags = access_flags;
559 cu_->invoke_type = invoke_type;
560 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
561 cu_->num_ins = current_code_item_->ins_size_;
562 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
563 cu_->num_outs = current_code_item_->outs_size_;
564 cu_->num_dalvik_registers = current_code_item_->registers_size_;
565 cu_->insns = current_code_item_->insns_;
566 cu_->code_item = current_code_item_;
567 } else {
568 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
569 /*
570 * Will need to manage storage for ins & outs, push prevous state and update
571 * insert point.
572 */
573 }
574
575 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700576 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700577 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800578 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700579 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700580 // TODO: for inlining support, insert at the insert point rather than entry block.
581 entry_block_->fall_through = cur_block->id;
582 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800583
584 /* Identify code range in try blocks and set up the empty catch blocks */
585 ProcessTryCatchBlocks();
586
buzbee311ca162013-02-28 15:56:43 -0800587 /* Parse all instructions and put them into containing basic blocks */
588 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700589 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800590 insn->offset = current_offset_;
591 insn->m_unit_index = current_method_;
592 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
593 insn->width = width;
594 Instruction::Code opcode = insn->dalvikInsn.opcode;
595 if (opcode_count_ != NULL) {
596 opcode_count_[static_cast<int>(opcode)]++;
597 }
598
buzbee311ca162013-02-28 15:56:43 -0800599 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
600
buzbee1da1e2f2013-11-15 13:37:01 -0800601 uint64_t df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800602
603 if (df_flags & DF_HAS_DEFS) {
604 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
605 }
606
buzbee1da1e2f2013-11-15 13:37:01 -0800607 if (df_flags & DF_LVN) {
608 cur_block->use_lvn = true; // Run local value numbering on this basic block.
609 }
610
buzbee27247762013-07-28 12:03:58 -0700611 // Check for inline data block signatures
612 if (opcode == Instruction::NOP) {
613 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
614 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
615 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
616 uint16_t following_raw_instruction = code_ptr[1];
617 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
618 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
619 (following_raw_instruction == Instruction::kArrayDataSignature)) {
620 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
621 }
622 }
623 if (width == 1) {
624 // It is a simple nop - treat normally.
625 AppendMIR(cur_block, insn);
626 } else {
buzbee0d829482013-10-11 15:24:55 -0700627 DCHECK(cur_block->fall_through == NullBasicBlockId);
628 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700629 // Unreachable instruction, mark for no continuation.
630 flags &= ~Instruction::kContinue;
631 }
632 } else {
633 AppendMIR(cur_block, insn);
634 }
635
buzbeeb48819d2013-09-14 16:15:25 -0700636 // Associate the starting dex_pc for this opcode with its containing basic block.
637 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
638
buzbee27247762013-07-28 12:03:58 -0700639 code_ptr += width;
640
buzbee311ca162013-02-28 15:56:43 -0800641 if (flags & Instruction::kBranch) {
642 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
643 width, flags, code_ptr, code_end);
644 } else if (flags & Instruction::kReturn) {
645 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700646 cur_block->fall_through = exit_block_->id;
647 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800648 /*
649 * Terminate the current block if there are instructions
650 * afterwards.
651 */
652 if (code_ptr < code_end) {
653 /*
654 * Create a fallthrough block for real instructions
655 * (incl. NOP).
656 */
buzbee27247762013-07-28 12:03:58 -0700657 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
658 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800659 }
660 } else if (flags & Instruction::kThrow) {
661 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
662 code_ptr, code_end);
663 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800664 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800665 }
666 current_offset_ += width;
667 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
668 false, /* immed_pred_block_p */ NULL);
669 if (next_block) {
670 /*
671 * The next instruction could be the target of a previously parsed
672 * forward branch so a block is already created. If the current
673 * instruction is not an unconditional branch, connect them through
674 * the fall-through link.
675 */
buzbee0d829482013-10-11 15:24:55 -0700676 DCHECK(cur_block->fall_through == NullBasicBlockId ||
677 GetBasicBlock(cur_block->fall_through) == next_block ||
678 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800679
buzbee0d829482013-10-11 15:24:55 -0700680 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
681 cur_block->fall_through = next_block->id;
682 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800683 }
684 cur_block = next_block;
685 }
686 }
Vladimir Marko5816ed42013-11-27 17:04:20 +0000687
buzbee311ca162013-02-28 15:56:43 -0800688 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
689 DumpCFG("/sdcard/1_post_parse_cfg/", true);
690 }
691
692 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700693 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800694 }
695}
696
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700697void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800698 DCHECK(opcode_count_ != NULL);
699 LOG(INFO) << "Opcode Count";
700 for (int i = 0; i < kNumPackedOpcodes; i++) {
701 if (opcode_count_[i] != 0) {
702 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
703 << " " << opcode_count_[i];
704 }
705 }
706}
707
708// TODO: use a configurable base prefix, and adjust callers to supply pass name.
709/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700710void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800711 FILE* file;
712 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
713 ReplaceSpecialChars(fname);
714 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
buzbee0d829482013-10-11 15:24:55 -0700715 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800716 file = fopen(fname.c_str(), "w");
717 if (file == NULL) {
718 return;
719 }
720 fprintf(file, "digraph G {\n");
721
722 fprintf(file, " rankdir=TB\n");
723
724 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
725 int idx;
726
727 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700728 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800729 BasicBlock *bb = GetBasicBlock(block_idx);
730 if (bb == NULL) break;
731 if (bb->block_type == kDead) continue;
732 if (bb->block_type == kEntryBlock) {
733 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
734 } else if (bb->block_type == kExitBlock) {
735 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
736 } else if (bb->block_type == kDalvikByteCode) {
737 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
738 bb->start_offset, bb->id);
739 const MIR *mir;
740 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
741 bb->first_mir_insn ? " | " : " ");
742 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
743 int opcode = mir->dalvikInsn.opcode;
744 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700745 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800746 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700747 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800748 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
749 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
750 mir->next ? " | " : " ");
751 }
752 fprintf(file, " }\"];\n\n");
753 } else if (bb->block_type == kExceptionHandling) {
754 char block_name[BLOCK_NAME_LEN];
755
756 GetBlockName(bb, block_name);
757 fprintf(file, " %s [shape=invhouse];\n", block_name);
758 }
759
760 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
761
buzbee0d829482013-10-11 15:24:55 -0700762 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800763 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700764 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800765 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
766 block_name1, block_name2);
767 }
buzbee0d829482013-10-11 15:24:55 -0700768 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800769 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700770 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800771 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
772 }
773
buzbee0d829482013-10-11 15:24:55 -0700774 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800775 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
776 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700777 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
778 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700779 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800780
781 int succ_id = 0;
782 while (true) {
783 if (successor_block_info == NULL) break;
784
buzbee0d829482013-10-11 15:24:55 -0700785 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700786 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800787
788 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
789 succ_id++,
790 successor_block_info->key,
791 dest_block->start_offset,
792 (next_successor_block_info != NULL) ? " | " : " ");
793
794 successor_block_info = next_successor_block_info;
795 }
796 fprintf(file, " }\"];\n\n");
797
798 GetBlockName(bb, block_name1);
799 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
800 block_name1, bb->start_offset, bb->id);
801
buzbee0d829482013-10-11 15:24:55 -0700802 if (bb->successor_block_list_type == kPackedSwitch ||
803 bb->successor_block_list_type == kSparseSwitch) {
804 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800805
806 succ_id = 0;
807 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700808 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800809 if (successor_block_info == NULL) break;
810
buzbee0d829482013-10-11 15:24:55 -0700811 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800812
813 GetBlockName(dest_block, block_name2);
814 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
815 bb->id, succ_id++, block_name2);
816 }
817 }
818 }
819 fprintf(file, "\n");
820
821 if (cu_->verbose) {
822 /* Display the dominator tree */
823 GetBlockName(bb, block_name1);
824 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
825 block_name1, block_name1);
826 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700827 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800828 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
829 }
830 }
831 }
832 fprintf(file, "}\n");
833 fclose(file);
834}
835
buzbee1fd33462013-03-25 13:40:45 -0700836/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700837void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700838 if (bb->first_mir_insn == NULL) {
839 DCHECK(bb->last_mir_insn == NULL);
840 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700841 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700842 } else {
843 bb->last_mir_insn->next = mir;
buzbee1fd33462013-03-25 13:40:45 -0700844 mir->next = NULL;
845 bb->last_mir_insn = mir;
846 }
847}
848
849/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700850void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700851 if (bb->first_mir_insn == NULL) {
852 DCHECK(bb->last_mir_insn == NULL);
853 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700854 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700855 } else {
buzbee1fd33462013-03-25 13:40:45 -0700856 mir->next = bb->first_mir_insn;
buzbee1fd33462013-03-25 13:40:45 -0700857 bb->first_mir_insn = mir;
858 }
859}
860
861/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700862void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700863 new_mir->next = current_mir->next;
864 current_mir->next = new_mir;
865
buzbee0d829482013-10-11 15:24:55 -0700866 if (bb->last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700867 /* Is the last MIR in the block */
868 bb->last_mir_insn = new_mir;
869 }
870}
871
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700872char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700873 DecodedInstruction insn = mir->dalvikInsn;
874 std::string str;
875 int flags = 0;
876 int opcode = insn.opcode;
877 char* ret;
878 bool nop = false;
879 SSARepresentation* ssa_rep = mir->ssa_rep;
880 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
881 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
882 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
883
884 // Handle special cases.
885 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
886 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
887 str.append(": ");
888 // Recover the original Dex instruction
889 insn = mir->meta.throw_insn->dalvikInsn;
890 ssa_rep = mir->meta.throw_insn->ssa_rep;
891 defs = ssa_rep->num_defs;
892 uses = ssa_rep->num_uses;
893 opcode = insn.opcode;
894 } else if (opcode == kMirOpNop) {
895 str.append("[");
buzbee0d829482013-10-11 15:24:55 -0700896 // Recover original opcode.
897 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
898 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -0700899 nop = true;
900 }
901
902 if (opcode >= kMirOpFirst) {
903 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
904 } else {
905 dalvik_format = Instruction::FormatOf(insn.opcode);
906 flags = Instruction::FlagsOf(insn.opcode);
907 str.append(Instruction::Name(insn.opcode));
908 }
909
910 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -0700911 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -0700912 str.append(StringPrintf(" %s = (%s",
913 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
914 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700915 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700916 int i;
917 for (i = 1; i < uses; i++) {
918 str.append(StringPrintf(", %s:%d",
919 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
920 incoming[i]));
921 }
922 str.append(")");
923 } else if ((flags & Instruction::kBranch) != 0) {
924 // For branches, decode the instructions to print out the branch targets.
925 int offset = 0;
926 switch (dalvik_format) {
927 case Instruction::k21t:
928 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
929 offset = insn.vB;
930 break;
931 case Instruction::k22t:
932 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
933 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
934 offset = insn.vC;
935 break;
936 case Instruction::k10t:
937 case Instruction::k20t:
938 case Instruction::k30t:
939 offset = insn.vA;
940 break;
941 default:
942 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
943 }
944 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
945 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
946 } else {
947 // For invokes-style formats, treat wide regs as a pair of singles
948 bool show_singles = ((dalvik_format == Instruction::k35c) ||
949 (dalvik_format == Instruction::k3rc));
950 if (defs != 0) {
951 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
952 if (uses != 0) {
953 str.append(", ");
954 }
955 }
956 for (int i = 0; i < uses; i++) {
957 str.append(
958 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
959 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
960 // For the listing, skip the high sreg.
961 i++;
962 }
963 if (i != (uses -1)) {
964 str.append(",");
965 }
966 }
967 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700968 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -0700969 case Instruction::k21s:
970 case Instruction::k31i:
971 case Instruction::k21h:
972 str.append(StringPrintf(", #%d", insn.vB));
973 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700974 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -0700975 str.append(StringPrintf(", #%lld", insn.vB_wide));
976 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700977 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700978 case Instruction::k31c:
979 str.append(StringPrintf(", index #%d", insn.vB));
980 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700981 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700982 str.append(StringPrintf(", index #%d", insn.vC));
983 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700984 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -0700985 case Instruction::k22b:
986 str.append(StringPrintf(", #%d", insn.vC));
987 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700988 default: {
989 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -0700990 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700991 }
buzbee1fd33462013-03-25 13:40:45 -0700992 }
993 if (nop) {
994 str.append("]--optimized away");
995 }
996 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700997 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -0700998 strncpy(ret, str.c_str(), length);
999 return ret;
1000}
1001
1002/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001003void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001004 static const struct { const char before; const char after; } match[] = {
1005 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1006 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1007 };
buzbee1fd33462013-03-25 13:40:45 -07001008 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1009 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1010 }
1011}
1012
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001013std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001014 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1015 // the arena. We should be smarter and just place straight into the arena, or compute the
1016 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001017 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1018}
1019
1020// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001021std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001022 if (reg_location_ == NULL) {
1023 // Pre-SSA - just use the standard name
1024 return GetSSAName(ssa_reg);
1025 }
1026 if (IsConst(reg_location_[ssa_reg])) {
1027 if (!singles_only && reg_location_[ssa_reg].wide) {
1028 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1029 ConstantValueWide(reg_location_[ssa_reg]));
1030 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001031 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001032 ConstantValue(reg_location_[ssa_reg]));
1033 }
1034 } else {
1035 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1036 }
1037}
1038
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001039void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001040 switch (bb->block_type) {
1041 case kEntryBlock:
1042 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1043 break;
1044 case kExitBlock:
1045 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1046 break;
1047 case kDalvikByteCode:
1048 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1049 break;
1050 case kExceptionHandling:
1051 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1052 bb->id);
1053 break;
1054 default:
1055 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1056 break;
1057 }
1058}
1059
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001060const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001061 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001062 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1063 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1064}
1065
1066/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001067void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001068 BasicBlock* bb;
1069 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001070 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001071 "Entry Block",
1072 "Code Block",
1073 "Exit Block",
1074 "Exception Handling",
1075 "Catch Block"
1076 };
1077
1078 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1079 LOG(INFO) << cu_->insns << " insns";
1080 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001081 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001082
1083 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001084 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001085 if (bb == NULL) break;
1086 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1087 bb->id,
1088 block_type_names[bb->block_type],
1089 bb->start_offset,
1090 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1091 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001092 if (bb->taken != NullBasicBlockId) {
1093 LOG(INFO) << " Taken branch: block " << bb->taken
1094 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001095 }
buzbee0d829482013-10-11 15:24:55 -07001096 if (bb->fall_through != NullBasicBlockId) {
1097 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1098 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001099 }
1100 }
1101}
1102
1103/*
1104 * Build an array of location records for the incoming arguments.
1105 * Note: one location record per word of arguments, with dummy
1106 * high-word loc for wide arguments. Also pull up any following
1107 * MOVE_RESULT and incorporate it into the invoke.
1108 */
1109CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001110 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001111 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1112 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001113 MIR* move_result_mir = FindMoveResult(bb, mir);
1114 if (move_result_mir == NULL) {
1115 info->result.location = kLocInvalid;
1116 } else {
1117 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001118 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1119 }
1120 info->num_arg_words = mir->ssa_rep->num_uses;
1121 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001122 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001123 for (int i = 0; i < info->num_arg_words; i++) {
1124 info->args[i] = GetRawSrc(mir, i);
1125 }
1126 info->opt_flags = mir->optimization_flags;
1127 info->type = type;
1128 info->is_range = is_range;
1129 info->index = mir->dalvikInsn.vB;
1130 info->offset = mir->offset;
1131 return info;
1132}
1133
buzbee862a7602013-04-05 10:58:54 -07001134// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001135BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001136 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1137 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001138 bb->block_type = block_type;
1139 bb->id = block_id;
1140 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001141 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001142 (block_type == kExitBlock) ? 2048 : 2,
1143 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001144 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001145 block_id_map_.Put(block_id, block_id);
1146 return bb;
1147}
buzbee1fd33462013-03-25 13:40:45 -07001148
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001149} // namespace art