blob: cf758fc5dab257ff63c593893be3747acad8cac7 [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
23namespace art {
24
25#define MAX_PATTERN_LEN 5
26
27struct CodePattern {
28 const Instruction::Code opcodes[MAX_PATTERN_LEN];
29 const SpecialCaseHandler handler_code;
30};
31
32static const CodePattern special_patterns[] = {
33 {{Instruction::RETURN_VOID}, kNullMethod},
34 {{Instruction::CONST, Instruction::RETURN}, kConstFunction},
35 {{Instruction::CONST_4, Instruction::RETURN}, kConstFunction},
36 {{Instruction::CONST_4, Instruction::RETURN_OBJECT}, kConstFunction},
37 {{Instruction::CONST_16, Instruction::RETURN}, kConstFunction},
38 {{Instruction::IGET, Instruction:: RETURN}, kIGet},
39 {{Instruction::IGET_BOOLEAN, Instruction::RETURN}, kIGetBoolean},
40 {{Instruction::IGET_OBJECT, Instruction::RETURN_OBJECT}, kIGetObject},
41 {{Instruction::IGET_BYTE, Instruction::RETURN}, kIGetByte},
42 {{Instruction::IGET_CHAR, Instruction::RETURN}, kIGetChar},
43 {{Instruction::IGET_SHORT, Instruction::RETURN}, kIGetShort},
44 {{Instruction::IGET_WIDE, Instruction::RETURN_WIDE}, kIGetWide},
45 {{Instruction::IPUT, Instruction::RETURN_VOID}, kIPut},
46 {{Instruction::IPUT_BOOLEAN, Instruction::RETURN_VOID}, kIPutBoolean},
47 {{Instruction::IPUT_OBJECT, Instruction::RETURN_VOID}, kIPutObject},
48 {{Instruction::IPUT_BYTE, Instruction::RETURN_VOID}, kIPutByte},
49 {{Instruction::IPUT_CHAR, Instruction::RETURN_VOID}, kIPutChar},
50 {{Instruction::IPUT_SHORT, Instruction::RETURN_VOID}, kIPutShort},
51 {{Instruction::IPUT_WIDE, Instruction::RETURN_VOID}, kIPutWide},
52 {{Instruction::RETURN}, kIdentity},
53 {{Instruction::RETURN_OBJECT}, kIdentity},
54 {{Instruction::RETURN_WIDE}, kIdentity},
55};
56
buzbee1fd33462013-03-25 13:40:45 -070057const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
58 "Phi",
59 "Copy",
60 "FusedCmplFloat",
61 "FusedCmpgFloat",
62 "FusedCmplDouble",
63 "FusedCmpgDouble",
64 "FusedCmpLong",
65 "Nop",
66 "OpNullCheck",
67 "OpRangeCheck",
68 "OpDivZeroCheck",
69 "Check1",
70 "Check2",
71 "Select",
72};
73
buzbee862a7602013-04-05 10:58:54 -070074MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070075 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070076 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070077 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080078 ssa_base_vregs_(NULL),
79 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080080 vreg_to_ssa_map_(NULL),
81 ssa_last_defs_(NULL),
82 is_constant_v_(NULL),
83 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070084 use_counts_(arena, 256, kGrowableArrayMisc),
85 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080086 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070087 dfs_order_(NULL),
88 dfs_post_order_(NULL),
89 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080090 i_dom_list_(NULL),
91 def_block_matrix_(NULL),
92 temp_block_v_(NULL),
93 temp_dalvik_register_v_(NULL),
94 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070095 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080096 try_block_addr_(NULL),
97 entry_block_(NULL),
98 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080099 num_blocks_(0),
100 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700101 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -0800102 current_method_(kInvalidEntry),
103 current_offset_(kInvalidEntry),
104 def_count_(0),
105 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700106 num_ssa_regs_(0),
107 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700108 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
109 checkstats_(NULL),
buzbee479f83c2013-07-19 10:58:21 -0700110 special_case_(kNoHandler),
buzbeeb48819d2013-09-14 16:15:25 -0700111 arena_(arena),
112 backward_branches_(0),
113 forward_branches_(0) {
buzbee862a7602013-04-05 10:58:54 -0700114 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -0800115}
116
Ian Rogers6282dc12013-04-18 15:54:02 -0700117MIRGraph::~MIRGraph() {
118 STLDeleteElements(&m_units_);
119}
120
buzbee311ca162013-02-28 15:56:43 -0800121/*
122 * Parse an instruction, return the length of the instruction
123 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700124int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800125 const Instruction* instruction = Instruction::At(code_ptr);
126 *decoded_instruction = DecodedInstruction(instruction);
127
128 return instruction->SizeInCodeUnits();
129}
130
131
132/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700133BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700134 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700135 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800136 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700137 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800138 while (insn) {
139 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700140 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800141 insn = insn->next;
142 }
143 if (insn == NULL) {
144 LOG(FATAL) << "Break split failed";
145 }
buzbee862a7602013-04-05 10:58:54 -0700146 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
147 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800148
149 bottom_block->start_offset = code_offset;
150 bottom_block->first_mir_insn = insn;
151 bottom_block->last_mir_insn = orig_block->last_mir_insn;
152
153 /* If this block was terminated by a return, the flag needs to go with the bottom block */
154 bottom_block->terminated_by_return = orig_block->terminated_by_return;
155 orig_block->terminated_by_return = false;
156
157 /* Add it to the quick lookup cache */
buzbeeb48819d2013-09-14 16:15:25 -0700158 dex_pc_to_block_map_.Put(bottom_block->start_offset, bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800159
160 /* Handle the taken path */
161 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700162 if (bottom_block->taken != NullBasicBlockId) {
163 orig_block->taken = NullBasicBlockId;
164 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
165 bb_taken->predecessors->Delete(orig_block->id);
166 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800167 }
168
169 /* Handle the fallthrough path */
170 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700171 orig_block->fall_through = bottom_block->id;
172 bottom_block->predecessors->Insert(orig_block->id);
173 if (bottom_block->fall_through != NullBasicBlockId) {
174 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
175 bb_fall_through->predecessors->Delete(orig_block->id);
176 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800177 }
178
179 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700180 if (orig_block->successor_block_list_type != kNotUsed) {
181 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
182 bottom_block->successor_blocks = orig_block->successor_blocks;
183 orig_block->successor_block_list_type = kNotUsed;
184 orig_block->successor_blocks = NULL;
185 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800186 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700187 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800188 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700189 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
190 bb->predecessors->Delete(orig_block->id);
191 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800192 }
193 }
194
buzbee0d829482013-10-11 15:24:55 -0700195 orig_block->last_mir_insn = prev;
196 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800197
buzbee311ca162013-02-28 15:56:43 -0800198 /*
199 * Update the immediate predecessor block pointer so that outgoing edges
200 * can be applied to the proper block.
201 */
202 if (immed_pred_block_p) {
203 DCHECK_EQ(*immed_pred_block_p, orig_block);
204 *immed_pred_block_p = bottom_block;
205 }
buzbeeb48819d2013-09-14 16:15:25 -0700206
207 // Associate dex instructions in the bottom block with the new container.
208 MIR* p = bottom_block->first_mir_insn;
209 while (p != NULL) {
210 int opcode = p->dalvikInsn.opcode;
211 /*
212 * Some messiness here to ensure that we only enter real opcodes and only the
213 * first half of a potentially throwing instruction that has been split into
214 * CHECK and work portions. The 2nd half of a split operation will have a non-null
215 * throw_insn pointer that refers to the 1st half.
216 */
217 if ((opcode == kMirOpCheck) || (!IsPseudoMirOp(opcode) && (p->meta.throw_insn == NULL))) {
218 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
219 }
220 p = (p == bottom_block->last_mir_insn) ? NULL : p->next;
221 }
222
buzbee311ca162013-02-28 15:56:43 -0800223 return bottom_block;
224}
225
226/*
227 * Given a code offset, find out the block that starts with it. If the offset
228 * is in the middle of an existing block, split it into two. If immed_pred_block_p
229 * is not non-null and is the block being split, update *immed_pred_block_p to
230 * point to the bottom block so that outgoing edges can be set up properly
231 * (by the caller)
232 * Utilizes a map for fast lookup of the typical cases.
233 */
buzbee0d829482013-10-11 15:24:55 -0700234BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700235 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700236 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800237 return NULL;
238 }
buzbeeb48819d2013-09-14 16:15:25 -0700239
240 int block_id = dex_pc_to_block_map_.Get(code_offset);
241 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
242
243 if ((bb != NULL) && (bb->start_offset == code_offset)) {
244 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700245 return bb;
246 }
buzbee311ca162013-02-28 15:56:43 -0800247
buzbeeb48819d2013-09-14 16:15:25 -0700248 // No direct hit.
249 if (!create) {
250 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800251 }
252
buzbeeb48819d2013-09-14 16:15:25 -0700253 if (bb != NULL) {
254 // The target exists somewhere in an existing block.
255 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
256 }
257
258 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700259 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
260 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800261 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700262 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800263 return bb;
264}
265
buzbeeb48819d2013-09-14 16:15:25 -0700266
buzbee311ca162013-02-28 15:56:43 -0800267/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700268void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800269 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700270 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800271
272 if (tries_size == 0) {
273 return;
274 }
275
276 for (int i = 0; i < tries_size; i++) {
277 const DexFile::TryItem* pTry =
278 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700279 DexOffset start_offset = pTry->start_addr_;
280 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800281 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700282 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800283 }
284 }
285
286 // Iterate over each of the handlers to enqueue the empty Catch blocks
287 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
288 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
289 for (uint32_t idx = 0; idx < handlers_size; idx++) {
290 CatchHandlerIterator iterator(handlers_ptr);
291 for (; iterator.HasNext(); iterator.Next()) {
292 uint32_t address = iterator.GetHandlerAddress();
293 FindBlock(address, false /* split */, true /*create*/,
294 /* immed_pred_block_p */ NULL);
295 }
296 handlers_ptr = iterator.EndDataPointer();
297 }
298}
299
300/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700301BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
302 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700303 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700304 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800305 switch (insn->dalvikInsn.opcode) {
306 case Instruction::GOTO:
307 case Instruction::GOTO_16:
308 case Instruction::GOTO_32:
309 target += insn->dalvikInsn.vA;
310 break;
311 case Instruction::IF_EQ:
312 case Instruction::IF_NE:
313 case Instruction::IF_LT:
314 case Instruction::IF_GE:
315 case Instruction::IF_GT:
316 case Instruction::IF_LE:
317 cur_block->conditional_branch = true;
318 target += insn->dalvikInsn.vC;
319 break;
320 case Instruction::IF_EQZ:
321 case Instruction::IF_NEZ:
322 case Instruction::IF_LTZ:
323 case Instruction::IF_GEZ:
324 case Instruction::IF_GTZ:
325 case Instruction::IF_LEZ:
326 cur_block->conditional_branch = true;
327 target += insn->dalvikInsn.vB;
328 break;
329 default:
330 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
331 }
buzbeeb48819d2013-09-14 16:15:25 -0700332 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800333 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
334 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700335 cur_block->taken = taken_block->id;
336 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800337
338 /* Always terminate the current block for conditional branches */
339 if (flags & Instruction::kContinue) {
340 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
341 /*
342 * If the method is processed
343 * in sequential order from the
344 * beginning, we don't need to
345 * specify split for continue
346 * blocks. However, this
347 * routine can be called by
348 * compileLoop, which starts
349 * parsing the method from an
350 * arbitrary address in the
351 * method body.
352 */
353 true,
354 /* create */
355 true,
356 /* immed_pred_block_p */
357 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700358 cur_block->fall_through = fallthrough_block->id;
359 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800360 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700361 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800362 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800363 }
364 return cur_block;
365}
366
367/* Process instructions with the kSwitch flag */
buzbee0d829482013-10-11 15:24:55 -0700368void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset, int width,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700369 int flags) {
buzbee311ca162013-02-28 15:56:43 -0800370 const uint16_t* switch_data =
371 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
372 int size;
373 const int* keyTable;
374 const int* target_table;
375 int i;
376 int first_key;
377
378 /*
379 * Packed switch data format:
380 * ushort ident = 0x0100 magic value
381 * ushort size number of entries in the table
382 * int first_key first (and lowest) switch case value
383 * int targets[size] branch targets, relative to switch opcode
384 *
385 * Total size is (4+size*2) 16-bit code units.
386 */
387 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
388 DCHECK_EQ(static_cast<int>(switch_data[0]),
389 static_cast<int>(Instruction::kPackedSwitchSignature));
390 size = switch_data[1];
391 first_key = switch_data[2] | (switch_data[3] << 16);
392 target_table = reinterpret_cast<const int*>(&switch_data[4]);
393 keyTable = NULL; // Make the compiler happy
394 /*
395 * Sparse switch data format:
396 * ushort ident = 0x0200 magic value
397 * ushort size number of entries in the table; > 0
398 * int keys[size] keys, sorted low-to-high; 32-bit aligned
399 * int targets[size] branch targets, relative to switch opcode
400 *
401 * Total size is (2+size*4) 16-bit code units.
402 */
403 } else {
404 DCHECK_EQ(static_cast<int>(switch_data[0]),
405 static_cast<int>(Instruction::kSparseSwitchSignature));
406 size = switch_data[1];
407 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
408 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
409 first_key = 0; // To make the compiler happy
410 }
411
buzbee0d829482013-10-11 15:24:55 -0700412 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800413 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700414 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800415 }
buzbee0d829482013-10-11 15:24:55 -0700416 cur_block->successor_block_list_type =
417 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
418 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700419 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800420
421 for (i = 0; i < size; i++) {
422 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
423 /* create */ true, /* immed_pred_block_p */ &cur_block);
424 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700425 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
426 ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700427 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800428 successor_block_info->key =
429 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
430 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700431 cur_block->successor_blocks->Insert(successor_block_info);
432 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800433 }
434
435 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700436 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
437 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700438 cur_block->fall_through = fallthrough_block->id;
439 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800440}
441
442/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700443BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
444 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700445 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700446 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee311ca162013-02-28 15:56:43 -0800447
448 /* In try block */
449 if (in_try_block) {
450 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
451
buzbee0d829482013-10-11 15:24:55 -0700452 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800453 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
454 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700455 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800456 }
457
buzbee0d829482013-10-11 15:24:55 -0700458 cur_block->successor_block_list_type = kCatch;
459 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700460 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800461
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700462 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800463 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
464 false /* creat */, NULL /* immed_pred_block_p */);
465 catch_block->catch_entry = true;
466 if (kIsDebugBuild) {
467 catches_.insert(catch_block->start_offset);
468 }
469 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700470 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700471 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800472 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700473 cur_block->successor_blocks->Insert(successor_block_info);
474 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800475 }
476 } else {
buzbee862a7602013-04-05 10:58:54 -0700477 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700478 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700479 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800480 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700481 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800482 }
483
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700484 if (insn->dalvikInsn.opcode == Instruction::THROW) {
buzbee311ca162013-02-28 15:56:43 -0800485 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700486 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800487 // Force creation of new block following THROW via side-effect
488 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
489 /* immed_pred_block_p */ NULL);
490 }
491 if (!in_try_block) {
492 // Don't split a THROW that can't rethrow - we're done.
493 return cur_block;
494 }
495 }
496
497 /*
498 * Split the potentially-throwing instruction into two parts.
499 * The first half will be a pseudo-op that captures the exception
500 * edges and terminates the basic block. It always falls through.
501 * Then, create a new basic block that begins with the throwing instruction
502 * (minus exceptions). Note: this new basic block must NOT be entered into
503 * the block_map. If the potentially-throwing instruction is the target of a
504 * future branch, we need to find the check psuedo half. The new
505 * basic block containing the work portion of the instruction should
506 * only be entered via fallthrough from the block containing the
507 * pseudo exception edge MIR. Note also that this new block is
508 * not automatically terminated after the work portion, and may
509 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700510 *
511 * Note also that the dex_pc_to_block_map_ entry for the potentially
512 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800513 */
buzbee862a7602013-04-05 10:58:54 -0700514 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
515 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800516 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700517 cur_block->fall_through = new_block->id;
518 new_block->predecessors->Insert(cur_block->id);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700519 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800520 *new_insn = *insn;
521 insn->dalvikInsn.opcode =
522 static_cast<Instruction::Code>(kMirOpCheck);
523 // Associate the two halves
524 insn->meta.throw_insn = new_insn;
525 new_insn->meta.throw_insn = insn;
526 AppendMIR(new_block, new_insn);
527 return new_block;
528}
529
530/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
531void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700532 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700533 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800534 current_code_item_ = code_item;
535 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
536 current_method_ = m_units_.size();
537 current_offset_ = 0;
538 // TODO: will need to snapshot stack image and use that as the mir context identification.
539 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
540 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
541 const uint16_t* code_ptr = current_code_item_->insns_;
542 const uint16_t* code_end =
543 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
544
545 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700546 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700547 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700548 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 -0700549
buzbee311ca162013-02-28 15:56:43 -0800550 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700551 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
552 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800553
554 // If this is the first method, set up default entry and exit blocks.
555 if (current_method_ == 0) {
556 DCHECK(entry_block_ == NULL);
557 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700558 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700559 // Use id 0 to represent a null block.
560 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
561 DCHECK_EQ(null_block->id, NullBasicBlockId);
562 null_block->hidden = true;
563 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700564 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700565 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700566 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700567 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800568 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
569 cu_->dex_file = &dex_file;
570 cu_->class_def_idx = class_def_idx;
571 cu_->method_idx = method_idx;
572 cu_->access_flags = access_flags;
573 cu_->invoke_type = invoke_type;
574 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
575 cu_->num_ins = current_code_item_->ins_size_;
576 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
577 cu_->num_outs = current_code_item_->outs_size_;
578 cu_->num_dalvik_registers = current_code_item_->registers_size_;
579 cu_->insns = current_code_item_->insns_;
580 cu_->code_item = current_code_item_;
581 } else {
582 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
583 /*
584 * Will need to manage storage for ins & outs, push prevous state and update
585 * insert point.
586 */
587 }
588
589 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700590 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700591 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800592 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700593 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700594 // TODO: for inlining support, insert at the insert point rather than entry block.
595 entry_block_->fall_through = cur_block->id;
596 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800597
598 /* Identify code range in try blocks and set up the empty catch blocks */
599 ProcessTryCatchBlocks();
600
601 /* Set up for simple method detection */
602 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
603 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
604 bool* dead_pattern =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700605 static_cast<bool*>(arena_->Alloc(sizeof(bool) * num_patterns, ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800606 int pattern_pos = 0;
607
608 /* Parse all instructions and put them into containing basic blocks */
609 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700610 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800611 insn->offset = current_offset_;
612 insn->m_unit_index = current_method_;
613 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
614 insn->width = width;
615 Instruction::Code opcode = insn->dalvikInsn.opcode;
616 if (opcode_count_ != NULL) {
617 opcode_count_[static_cast<int>(opcode)]++;
618 }
619
buzbee311ca162013-02-28 15:56:43 -0800620 /* Possible simple method? */
621 if (live_pattern) {
622 live_pattern = false;
buzbee479f83c2013-07-19 10:58:21 -0700623 special_case_ = kNoHandler;
buzbee311ca162013-02-28 15:56:43 -0800624 for (int i = 0; i < num_patterns; i++) {
625 if (!dead_pattern[i]) {
626 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
627 live_pattern = true;
buzbee479f83c2013-07-19 10:58:21 -0700628 special_case_ = special_patterns[i].handler_code;
buzbee311ca162013-02-28 15:56:43 -0800629 } else {
630 dead_pattern[i] = true;
631 }
632 }
633 }
634 pattern_pos++;
635 }
636
buzbee311ca162013-02-28 15:56:43 -0800637 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
638
buzbee1fd33462013-03-25 13:40:45 -0700639 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800640
641 if (df_flags & DF_HAS_DEFS) {
642 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
643 }
644
buzbee27247762013-07-28 12:03:58 -0700645 // Check for inline data block signatures
646 if (opcode == Instruction::NOP) {
647 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
648 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
649 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
650 uint16_t following_raw_instruction = code_ptr[1];
651 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
652 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
653 (following_raw_instruction == Instruction::kArrayDataSignature)) {
654 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
655 }
656 }
657 if (width == 1) {
658 // It is a simple nop - treat normally.
659 AppendMIR(cur_block, insn);
660 } else {
buzbee0d829482013-10-11 15:24:55 -0700661 DCHECK(cur_block->fall_through == NullBasicBlockId);
662 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700663 // Unreachable instruction, mark for no continuation.
664 flags &= ~Instruction::kContinue;
665 }
666 } else {
667 AppendMIR(cur_block, insn);
668 }
669
buzbeeb48819d2013-09-14 16:15:25 -0700670 // Associate the starting dex_pc for this opcode with its containing basic block.
671 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
672
buzbee27247762013-07-28 12:03:58 -0700673 code_ptr += width;
674
buzbee311ca162013-02-28 15:56:43 -0800675 if (flags & Instruction::kBranch) {
676 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
677 width, flags, code_ptr, code_end);
678 } else if (flags & Instruction::kReturn) {
679 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700680 cur_block->fall_through = exit_block_->id;
681 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800682 /*
683 * Terminate the current block if there are instructions
684 * afterwards.
685 */
686 if (code_ptr < code_end) {
687 /*
688 * Create a fallthrough block for real instructions
689 * (incl. NOP).
690 */
buzbee27247762013-07-28 12:03:58 -0700691 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
692 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800693 }
694 } else if (flags & Instruction::kThrow) {
695 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
696 code_ptr, code_end);
697 } else if (flags & Instruction::kSwitch) {
698 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
699 }
700 current_offset_ += width;
701 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
702 false, /* immed_pred_block_p */ NULL);
703 if (next_block) {
704 /*
705 * The next instruction could be the target of a previously parsed
706 * forward branch so a block is already created. If the current
707 * instruction is not an unconditional branch, connect them through
708 * the fall-through link.
709 */
buzbee0d829482013-10-11 15:24:55 -0700710 DCHECK(cur_block->fall_through == NullBasicBlockId ||
711 GetBasicBlock(cur_block->fall_through) == next_block ||
712 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800713
buzbee0d829482013-10-11 15:24:55 -0700714 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
715 cur_block->fall_through = next_block->id;
716 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800717 }
718 cur_block = next_block;
719 }
720 }
721 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
722 DumpCFG("/sdcard/1_post_parse_cfg/", true);
723 }
724
725 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700726 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800727 }
728}
729
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700730void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800731 DCHECK(opcode_count_ != NULL);
732 LOG(INFO) << "Opcode Count";
733 for (int i = 0; i < kNumPackedOpcodes; i++) {
734 if (opcode_count_[i] != 0) {
735 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
736 << " " << opcode_count_[i];
737 }
738 }
739}
740
741// TODO: use a configurable base prefix, and adjust callers to supply pass name.
742/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700743void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800744 FILE* file;
745 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
746 ReplaceSpecialChars(fname);
747 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
buzbee0d829482013-10-11 15:24:55 -0700748 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800749 file = fopen(fname.c_str(), "w");
750 if (file == NULL) {
751 return;
752 }
753 fprintf(file, "digraph G {\n");
754
755 fprintf(file, " rankdir=TB\n");
756
757 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
758 int idx;
759
760 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700761 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800762 BasicBlock *bb = GetBasicBlock(block_idx);
763 if (bb == NULL) break;
764 if (bb->block_type == kDead) continue;
765 if (bb->block_type == kEntryBlock) {
766 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
767 } else if (bb->block_type == kExitBlock) {
768 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
769 } else if (bb->block_type == kDalvikByteCode) {
770 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
771 bb->start_offset, bb->id);
772 const MIR *mir;
773 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
774 bb->first_mir_insn ? " | " : " ");
775 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
776 int opcode = mir->dalvikInsn.opcode;
777 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700778 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800779 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700780 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800781 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
782 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
783 mir->next ? " | " : " ");
784 }
785 fprintf(file, " }\"];\n\n");
786 } else if (bb->block_type == kExceptionHandling) {
787 char block_name[BLOCK_NAME_LEN];
788
789 GetBlockName(bb, block_name);
790 fprintf(file, " %s [shape=invhouse];\n", block_name);
791 }
792
793 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
794
buzbee0d829482013-10-11 15:24:55 -0700795 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800796 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700797 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800798 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
799 block_name1, block_name2);
800 }
buzbee0d829482013-10-11 15:24:55 -0700801 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800802 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700803 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800804 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
805 }
806
buzbee0d829482013-10-11 15:24:55 -0700807 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800808 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
809 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700810 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
811 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700812 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800813
814 int succ_id = 0;
815 while (true) {
816 if (successor_block_info == NULL) break;
817
buzbee0d829482013-10-11 15:24:55 -0700818 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700819 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800820
821 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
822 succ_id++,
823 successor_block_info->key,
824 dest_block->start_offset,
825 (next_successor_block_info != NULL) ? " | " : " ");
826
827 successor_block_info = next_successor_block_info;
828 }
829 fprintf(file, " }\"];\n\n");
830
831 GetBlockName(bb, block_name1);
832 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
833 block_name1, bb->start_offset, bb->id);
834
buzbee0d829482013-10-11 15:24:55 -0700835 if (bb->successor_block_list_type == kPackedSwitch ||
836 bb->successor_block_list_type == kSparseSwitch) {
837 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800838
839 succ_id = 0;
840 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700841 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800842 if (successor_block_info == NULL) break;
843
buzbee0d829482013-10-11 15:24:55 -0700844 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800845
846 GetBlockName(dest_block, block_name2);
847 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
848 bb->id, succ_id++, block_name2);
849 }
850 }
851 }
852 fprintf(file, "\n");
853
854 if (cu_->verbose) {
855 /* Display the dominator tree */
856 GetBlockName(bb, block_name1);
857 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
858 block_name1, block_name1);
859 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700860 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800861 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
862 }
863 }
864 }
865 fprintf(file, "}\n");
866 fclose(file);
867}
868
buzbee1fd33462013-03-25 13:40:45 -0700869/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700870void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700871 if (bb->first_mir_insn == NULL) {
872 DCHECK(bb->last_mir_insn == NULL);
873 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700874 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700875 } else {
876 bb->last_mir_insn->next = mir;
buzbee1fd33462013-03-25 13:40:45 -0700877 mir->next = NULL;
878 bb->last_mir_insn = mir;
879 }
880}
881
882/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700883void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700884 if (bb->first_mir_insn == NULL) {
885 DCHECK(bb->last_mir_insn == NULL);
886 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700887 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700888 } else {
buzbee1fd33462013-03-25 13:40:45 -0700889 mir->next = bb->first_mir_insn;
buzbee1fd33462013-03-25 13:40:45 -0700890 bb->first_mir_insn = mir;
891 }
892}
893
894/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700895void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700896 new_mir->next = current_mir->next;
897 current_mir->next = new_mir;
898
buzbee0d829482013-10-11 15:24:55 -0700899 if (bb->last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700900 /* Is the last MIR in the block */
901 bb->last_mir_insn = new_mir;
902 }
903}
904
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700905char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700906 DecodedInstruction insn = mir->dalvikInsn;
907 std::string str;
908 int flags = 0;
909 int opcode = insn.opcode;
910 char* ret;
911 bool nop = false;
912 SSARepresentation* ssa_rep = mir->ssa_rep;
913 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
914 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
915 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
916
917 // Handle special cases.
918 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
919 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
920 str.append(": ");
921 // Recover the original Dex instruction
922 insn = mir->meta.throw_insn->dalvikInsn;
923 ssa_rep = mir->meta.throw_insn->ssa_rep;
924 defs = ssa_rep->num_defs;
925 uses = ssa_rep->num_uses;
926 opcode = insn.opcode;
927 } else if (opcode == kMirOpNop) {
928 str.append("[");
buzbee0d829482013-10-11 15:24:55 -0700929 // Recover original opcode.
930 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
931 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -0700932 nop = true;
933 }
934
935 if (opcode >= kMirOpFirst) {
936 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
937 } else {
938 dalvik_format = Instruction::FormatOf(insn.opcode);
939 flags = Instruction::FlagsOf(insn.opcode);
940 str.append(Instruction::Name(insn.opcode));
941 }
942
943 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -0700944 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -0700945 str.append(StringPrintf(" %s = (%s",
946 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
947 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700948 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700949 int i;
950 for (i = 1; i < uses; i++) {
951 str.append(StringPrintf(", %s:%d",
952 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
953 incoming[i]));
954 }
955 str.append(")");
956 } else if ((flags & Instruction::kBranch) != 0) {
957 // For branches, decode the instructions to print out the branch targets.
958 int offset = 0;
959 switch (dalvik_format) {
960 case Instruction::k21t:
961 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
962 offset = insn.vB;
963 break;
964 case Instruction::k22t:
965 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
966 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
967 offset = insn.vC;
968 break;
969 case Instruction::k10t:
970 case Instruction::k20t:
971 case Instruction::k30t:
972 offset = insn.vA;
973 break;
974 default:
975 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
976 }
977 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
978 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
979 } else {
980 // For invokes-style formats, treat wide regs as a pair of singles
981 bool show_singles = ((dalvik_format == Instruction::k35c) ||
982 (dalvik_format == Instruction::k3rc));
983 if (defs != 0) {
984 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
985 if (uses != 0) {
986 str.append(", ");
987 }
988 }
989 for (int i = 0; i < uses; i++) {
990 str.append(
991 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
992 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
993 // For the listing, skip the high sreg.
994 i++;
995 }
996 if (i != (uses -1)) {
997 str.append(",");
998 }
999 }
1000 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001001 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001002 case Instruction::k21s:
1003 case Instruction::k31i:
1004 case Instruction::k21h:
1005 str.append(StringPrintf(", #%d", insn.vB));
1006 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001007 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -07001008 str.append(StringPrintf(", #%lld", insn.vB_wide));
1009 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001010 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001011 case Instruction::k31c:
1012 str.append(StringPrintf(", index #%d", insn.vB));
1013 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001014 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001015 str.append(StringPrintf(", index #%d", insn.vC));
1016 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001017 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001018 case Instruction::k22b:
1019 str.append(StringPrintf(", #%d", insn.vC));
1020 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001021 default: {
1022 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001023 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001024 }
buzbee1fd33462013-03-25 13:40:45 -07001025 }
1026 if (nop) {
1027 str.append("]--optimized away");
1028 }
1029 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001030 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001031 strncpy(ret, str.c_str(), length);
1032 return ret;
1033}
1034
1035/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001036void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001037 static const struct { const char before; const char after; } match[] = {
1038 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1039 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1040 };
buzbee1fd33462013-03-25 13:40:45 -07001041 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1042 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1043 }
1044}
1045
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001046std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001047 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1048 // the arena. We should be smarter and just place straight into the arena, or compute the
1049 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001050 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1051}
1052
1053// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001054std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001055 if (reg_location_ == NULL) {
1056 // Pre-SSA - just use the standard name
1057 return GetSSAName(ssa_reg);
1058 }
1059 if (IsConst(reg_location_[ssa_reg])) {
1060 if (!singles_only && reg_location_[ssa_reg].wide) {
1061 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1062 ConstantValueWide(reg_location_[ssa_reg]));
1063 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001064 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001065 ConstantValue(reg_location_[ssa_reg]));
1066 }
1067 } else {
1068 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1069 }
1070}
1071
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001072void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001073 switch (bb->block_type) {
1074 case kEntryBlock:
1075 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1076 break;
1077 case kExitBlock:
1078 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1079 break;
1080 case kDalvikByteCode:
1081 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1082 break;
1083 case kExceptionHandling:
1084 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1085 bb->id);
1086 break;
1087 default:
1088 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1089 break;
1090 }
1091}
1092
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001093const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001094 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001095 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1096 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1097}
1098
1099/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001100void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001101 BasicBlock* bb;
1102 const char* block_type_names[] = {
1103 "Entry Block",
1104 "Code Block",
1105 "Exit Block",
1106 "Exception Handling",
1107 "Catch Block"
1108 };
1109
1110 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1111 LOG(INFO) << cu_->insns << " insns";
1112 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001113 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001114
1115 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001116 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001117 if (bb == NULL) break;
1118 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1119 bb->id,
1120 block_type_names[bb->block_type],
1121 bb->start_offset,
1122 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1123 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001124 if (bb->taken != NullBasicBlockId) {
1125 LOG(INFO) << " Taken branch: block " << bb->taken
1126 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001127 }
buzbee0d829482013-10-11 15:24:55 -07001128 if (bb->fall_through != NullBasicBlockId) {
1129 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1130 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001131 }
1132 }
1133}
1134
1135/*
1136 * Build an array of location records for the incoming arguments.
1137 * Note: one location record per word of arguments, with dummy
1138 * high-word loc for wide arguments. Also pull up any following
1139 * MOVE_RESULT and incorporate it into the invoke.
1140 */
1141CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001142 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001143 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1144 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001145 MIR* move_result_mir = FindMoveResult(bb, mir);
1146 if (move_result_mir == NULL) {
1147 info->result.location = kLocInvalid;
1148 } else {
1149 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001150 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1151 }
1152 info->num_arg_words = mir->ssa_rep->num_uses;
1153 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001154 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001155 for (int i = 0; i < info->num_arg_words; i++) {
1156 info->args[i] = GetRawSrc(mir, i);
1157 }
1158 info->opt_flags = mir->optimization_flags;
1159 info->type = type;
1160 info->is_range = is_range;
1161 info->index = mir->dalvikInsn.vB;
1162 info->offset = mir->offset;
1163 return info;
1164}
1165
buzbee862a7602013-04-05 10:58:54 -07001166// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001167BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001168 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1169 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001170 bb->block_type = block_type;
1171 bb->id = block_id;
1172 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001173 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001174 (block_type == kExitBlock) ? 2048 : 2,
1175 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001176 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001177 block_id_map_.Put(block_id, block_id);
1178 return bb;
1179}
buzbee1fd33462013-03-25 13:40:45 -07001180
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001181} // namespace art