blob: 11e100dc61a69304ad753047b75a17a8bce5f89c [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),
99 cur_block_(NULL),
100 num_blocks_(0),
101 current_code_item_(NULL),
102 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),
110 arena_(arena)
buzbee1fd33462013-03-25 13:40:45 -0700111 {
buzbee862a7602013-04-05 10:58:54 -0700112 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -0800113}
114
Ian Rogers6282dc12013-04-18 15:54:02 -0700115MIRGraph::~MIRGraph() {
116 STLDeleteElements(&m_units_);
117}
118
buzbee311ca162013-02-28 15:56:43 -0800119bool MIRGraph::ContentIsInsn(const uint16_t* code_ptr) {
120 uint16_t instr = *code_ptr;
121 Instruction::Code opcode = static_cast<Instruction::Code>(instr & 0xff);
122 /*
123 * Since the low 8-bit in metadata may look like NOP, we need to check
124 * both the low and whole sub-word to determine whether it is code or data.
125 */
126 return (opcode != Instruction::NOP || instr == 0);
127}
128
129/*
130 * Parse an instruction, return the length of the instruction
131 */
132int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction)
133{
134 // Don't parse instruction data
135 if (!ContentIsInsn(code_ptr)) {
136 return 0;
137 }
138
139 const Instruction* instruction = Instruction::At(code_ptr);
140 *decoded_instruction = DecodedInstruction(instruction);
141
142 return instruction->SizeInCodeUnits();
143}
144
145
146/* Split an existing block from the specified code offset into two */
147BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
148 BasicBlock* orig_block, BasicBlock** immed_pred_block_p)
149{
150 MIR* insn = orig_block->first_mir_insn;
151 while (insn) {
152 if (insn->offset == code_offset) break;
153 insn = insn->next;
154 }
155 if (insn == NULL) {
156 LOG(FATAL) << "Break split failed";
157 }
buzbee862a7602013-04-05 10:58:54 -0700158 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
159 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800160
161 bottom_block->start_offset = code_offset;
162 bottom_block->first_mir_insn = insn;
163 bottom_block->last_mir_insn = orig_block->last_mir_insn;
164
165 /* If this block was terminated by a return, the flag needs to go with the bottom block */
166 bottom_block->terminated_by_return = orig_block->terminated_by_return;
167 orig_block->terminated_by_return = false;
168
169 /* Add it to the quick lookup cache */
170 block_map_.Put(bottom_block->start_offset, bottom_block);
171
172 /* Handle the taken path */
173 bottom_block->taken = orig_block->taken;
174 if (bottom_block->taken) {
175 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700176 bottom_block->taken->predecessors->Delete(orig_block);
177 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800178 }
179
180 /* Handle the fallthrough path */
181 bottom_block->fall_through = orig_block->fall_through;
182 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700183 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800184 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700185 bottom_block->fall_through->predecessors->Delete(orig_block);
186 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800187 }
188
189 /* Handle the successor list */
190 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
191 bottom_block->successor_block_list = orig_block->successor_block_list;
192 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700193 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800194 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700195 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800196 if (successor_block_info == NULL) break;
197 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700198 bb->predecessors->Delete(orig_block);
199 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800200 }
201 }
202
203 orig_block->last_mir_insn = insn->prev;
204
205 insn->prev->next = NULL;
206 insn->prev = NULL;
207 /*
208 * Update the immediate predecessor block pointer so that outgoing edges
209 * can be applied to the proper block.
210 */
211 if (immed_pred_block_p) {
212 DCHECK_EQ(*immed_pred_block_p, orig_block);
213 *immed_pred_block_p = bottom_block;
214 }
215 return bottom_block;
216}
217
218/*
219 * Given a code offset, find out the block that starts with it. If the offset
220 * is in the middle of an existing block, split it into two. If immed_pred_block_p
221 * is not non-null and is the block being split, update *immed_pred_block_p to
222 * point to the bottom block so that outgoing edges can be set up properly
223 * (by the caller)
224 * Utilizes a map for fast lookup of the typical cases.
225 */
226BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
227 BasicBlock** immed_pred_block_p)
228{
229 BasicBlock* bb;
230 unsigned int i;
231 SafeMap<unsigned int, BasicBlock*>::iterator it;
232
233 it = block_map_.find(code_offset);
234 if (it != block_map_.end()) {
235 return it->second;
236 } else if (!create) {
237 return NULL;
238 }
239
240 if (split) {
buzbee862a7602013-04-05 10:58:54 -0700241 for (i = 0; i < block_list_.Size(); i++) {
242 bb = block_list_.Get(i);
buzbee311ca162013-02-28 15:56:43 -0800243 if (bb->block_type != kDalvikByteCode) continue;
244 /* Check if a branch jumps into the middle of an existing block */
245 if ((code_offset > bb->start_offset) && (bb->last_mir_insn != NULL) &&
246 (code_offset <= bb->last_mir_insn->offset)) {
247 BasicBlock *new_bb = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ?
248 immed_pred_block_p : NULL);
249 return new_bb;
250 }
251 }
252 }
253
254 /* Create a new one */
buzbee862a7602013-04-05 10:58:54 -0700255 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
256 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800257 bb->start_offset = code_offset;
258 block_map_.Put(bb->start_offset, bb);
259 return bb;
260}
261
262/* Identify code range in try blocks and set up the empty catch blocks */
263void MIRGraph::ProcessTryCatchBlocks()
264{
265 int tries_size = current_code_item_->tries_size_;
266 int offset;
267
268 if (tries_size == 0) {
269 return;
270 }
271
272 for (int i = 0; i < tries_size; i++) {
273 const DexFile::TryItem* pTry =
274 DexFile::GetTryItems(*current_code_item_, i);
275 int start_offset = pTry->start_addr_;
276 int end_offset = start_offset + pTry->insn_count_;
277 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700278 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800279 }
280 }
281
282 // Iterate over each of the handlers to enqueue the empty Catch blocks
283 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
284 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
285 for (uint32_t idx = 0; idx < handlers_size; idx++) {
286 CatchHandlerIterator iterator(handlers_ptr);
287 for (; iterator.HasNext(); iterator.Next()) {
288 uint32_t address = iterator.GetHandlerAddress();
289 FindBlock(address, false /* split */, true /*create*/,
290 /* immed_pred_block_p */ NULL);
291 }
292 handlers_ptr = iterator.EndDataPointer();
293 }
294}
295
296/* Process instructions with the kBranch flag */
297BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
298 int flags, const uint16_t* code_ptr,
299 const uint16_t* code_end)
300{
301 int target = cur_offset;
302 switch (insn->dalvikInsn.opcode) {
303 case Instruction::GOTO:
304 case Instruction::GOTO_16:
305 case Instruction::GOTO_32:
306 target += insn->dalvikInsn.vA;
307 break;
308 case Instruction::IF_EQ:
309 case Instruction::IF_NE:
310 case Instruction::IF_LT:
311 case Instruction::IF_GE:
312 case Instruction::IF_GT:
313 case Instruction::IF_LE:
314 cur_block->conditional_branch = true;
315 target += insn->dalvikInsn.vC;
316 break;
317 case Instruction::IF_EQZ:
318 case Instruction::IF_NEZ:
319 case Instruction::IF_LTZ:
320 case Instruction::IF_GEZ:
321 case Instruction::IF_GTZ:
322 case Instruction::IF_LEZ:
323 cur_block->conditional_branch = true;
324 target += insn->dalvikInsn.vB;
325 break;
326 default:
327 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
328 }
329 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
330 /* immed_pred_block_p */ &cur_block);
331 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700332 taken_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800333
334 /* Always terminate the current block for conditional branches */
335 if (flags & Instruction::kContinue) {
336 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
337 /*
338 * If the method is processed
339 * in sequential order from the
340 * beginning, we don't need to
341 * specify split for continue
342 * blocks. However, this
343 * routine can be called by
344 * compileLoop, which starts
345 * parsing the method from an
346 * arbitrary address in the
347 * method body.
348 */
349 true,
350 /* create */
351 true,
352 /* immed_pred_block_p */
353 &cur_block);
354 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700355 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800356 } else if (code_ptr < code_end) {
357 /* Create a fallthrough block for real instructions (incl. NOP) */
358 if (ContentIsInsn(code_ptr)) {
359 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
360 /* immed_pred_block_p */ NULL);
361 }
362 }
363 return cur_block;
364}
365
366/* Process instructions with the kSwitch flag */
367void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
368 int flags)
369{
370 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
412 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
413 LOG(FATAL) << "Successor block list already in use: "
414 << static_cast<int>(cur_block->successor_block_list.block_list_type);
415 }
416 cur_block->successor_block_list.block_list_type =
417 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
418 kPackedSwitch : kSparseSwitch;
buzbee862a7602013-04-05 10:58:54 -0700419 cur_block->successor_block_list.blocks =
420 new (arena_)GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800421
422 for (i = 0; i < size; i++) {
423 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
424 /* create */ true, /* immed_pred_block_p */ &cur_block);
425 SuccessorBlockInfo *successor_block_info =
buzbee862a7602013-04-05 10:58:54 -0700426 static_cast<SuccessorBlockInfo*>(arena_->NewMem(sizeof(SuccessorBlockInfo), false,
427 ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800428 successor_block_info->block = case_block;
429 successor_block_info->key =
430 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
431 first_key + i : keyTable[i];
buzbee862a7602013-04-05 10:58:54 -0700432 cur_block->successor_block_list.blocks->Insert(successor_block_info);
433 case_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800434 }
435
436 /* Fall-through case */
437 BasicBlock* fallthrough_block = FindBlock( cur_offset + width, /* split */ false,
438 /* create */ true, /* immed_pred_block_p */ NULL);
439 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700440 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800441}
442
443/* Process instructions with the kThrow flag */
444BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
445 int flags, ArenaBitVector* try_block_addr,
446 const uint16_t* code_ptr, const uint16_t* code_end)
447{
buzbee862a7602013-04-05 10:58:54 -0700448 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee311ca162013-02-28 15:56:43 -0800449
450 /* In try block */
451 if (in_try_block) {
452 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
453
454 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
455 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
456 LOG(FATAL) << "Successor block list already in use: "
457 << static_cast<int>(cur_block->successor_block_list.block_list_type);
458 }
459
460 cur_block->successor_block_list.block_list_type = kCatch;
buzbee862a7602013-04-05 10:58:54 -0700461 cur_block->successor_block_list.blocks =
462 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800463
464 for (;iterator.HasNext(); iterator.Next()) {
465 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
466 false /* creat */, NULL /* immed_pred_block_p */);
467 catch_block->catch_entry = true;
468 if (kIsDebugBuild) {
469 catches_.insert(catch_block->start_offset);
470 }
471 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
buzbee862a7602013-04-05 10:58:54 -0700472 (arena_->NewMem(sizeof(SuccessorBlockInfo), false, ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800473 successor_block_info->block = catch_block;
474 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee862a7602013-04-05 10:58:54 -0700475 cur_block->successor_block_list.blocks->Insert(successor_block_info);
476 catch_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800477 }
478 } else {
buzbee862a7602013-04-05 10:58:54 -0700479 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800480 cur_block->taken = eh_block;
buzbee862a7602013-04-05 10:58:54 -0700481 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800482 eh_block->start_offset = cur_offset;
buzbee862a7602013-04-05 10:58:54 -0700483 eh_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800484 }
485
486 if (insn->dalvikInsn.opcode == Instruction::THROW){
487 cur_block->explicit_throw = true;
488 if ((code_ptr < code_end) && ContentIsInsn(code_ptr)) {
489 // Force creation of new block following THROW via side-effect
490 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
491 /* immed_pred_block_p */ NULL);
492 }
493 if (!in_try_block) {
494 // Don't split a THROW that can't rethrow - we're done.
495 return cur_block;
496 }
497 }
498
499 /*
500 * Split the potentially-throwing instruction into two parts.
501 * The first half will be a pseudo-op that captures the exception
502 * edges and terminates the basic block. It always falls through.
503 * Then, create a new basic block that begins with the throwing instruction
504 * (minus exceptions). Note: this new basic block must NOT be entered into
505 * the block_map. If the potentially-throwing instruction is the target of a
506 * future branch, we need to find the check psuedo half. The new
507 * basic block containing the work portion of the instruction should
508 * only be entered via fallthrough from the block containing the
509 * pseudo exception edge MIR. Note also that this new block is
510 * not automatically terminated after the work portion, and may
511 * contain following instructions.
512 */
buzbee862a7602013-04-05 10:58:54 -0700513 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
514 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800515 new_block->start_offset = insn->offset;
516 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700517 new_block->predecessors->Insert(cur_block);
518 MIR* new_insn = static_cast<MIR*>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800519 *new_insn = *insn;
520 insn->dalvikInsn.opcode =
521 static_cast<Instruction::Code>(kMirOpCheck);
522 // Associate the two halves
523 insn->meta.throw_insn = new_insn;
524 new_insn->meta.throw_insn = insn;
525 AppendMIR(new_block, new_insn);
526 return new_block;
527}
528
529/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
530void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
531 InvokeType invoke_type, uint32_t class_def_idx,
532 uint32_t method_idx, jobject class_loader, const DexFile& dex_file)
533{
534 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.
buzbee862a7602013-04-05 10:58:54 -0700546 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800547 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700548 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
549 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800550
551 // If this is the first method, set up default entry and exit blocks.
552 if (current_method_ == 0) {
553 DCHECK(entry_block_ == NULL);
554 DCHECK(exit_block_ == NULL);
555 DCHECK(num_blocks_ == 0);
buzbee862a7602013-04-05 10:58:54 -0700556 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
557 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
558 block_list_.Insert(entry_block_);
559 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800560 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
561 cu_->dex_file = &dex_file;
562 cu_->class_def_idx = class_def_idx;
563 cu_->method_idx = method_idx;
564 cu_->access_flags = access_flags;
565 cu_->invoke_type = invoke_type;
566 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
567 cu_->num_ins = current_code_item_->ins_size_;
568 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
569 cu_->num_outs = current_code_item_->outs_size_;
570 cu_->num_dalvik_registers = current_code_item_->registers_size_;
571 cu_->insns = current_code_item_->insns_;
572 cu_->code_item = current_code_item_;
573 } else {
574 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
575 /*
576 * Will need to manage storage for ins & outs, push prevous state and update
577 * insert point.
578 */
579 }
580
581 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700582 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800583 DCHECK_EQ(current_offset_, 0);
584 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700585 block_list_.Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800586 /* Add first block to the fast lookup cache */
587// FIXME: block map needs association with offset/method pair rather than just offset
588 block_map_.Put(cur_block->start_offset, cur_block);
589// FIXME: this needs to insert at the insert point rather than entry block.
590 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700591 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800592
593 /* Identify code range in try blocks and set up the empty catch blocks */
594 ProcessTryCatchBlocks();
595
596 /* Set up for simple method detection */
597 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
598 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
599 bool* dead_pattern =
buzbee862a7602013-04-05 10:58:54 -0700600 static_cast<bool*>(arena_->NewMem(sizeof(bool) * num_patterns, true,
601 ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800602 SpecialCaseHandler special_case = kNoHandler;
603 // FIXME - wire this up
604 (void)special_case;
605 int pattern_pos = 0;
606
607 /* Parse all instructions and put them into containing basic blocks */
608 while (code_ptr < code_end) {
buzbee862a7602013-04-05 10:58:54 -0700609 MIR *insn = static_cast<MIR *>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800610 insn->offset = current_offset_;
611 insn->m_unit_index = current_method_;
612 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
613 insn->width = width;
614 Instruction::Code opcode = insn->dalvikInsn.opcode;
615 if (opcode_count_ != NULL) {
616 opcode_count_[static_cast<int>(opcode)]++;
617 }
618
619 /* Terminate when the data section is seen */
620 if (width == 0)
621 break;
622
623 /* Possible simple method? */
624 if (live_pattern) {
625 live_pattern = false;
626 special_case = kNoHandler;
627 for (int i = 0; i < num_patterns; i++) {
628 if (!dead_pattern[i]) {
629 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
630 live_pattern = true;
631 special_case = special_patterns[i].handler_code;
632 } else {
633 dead_pattern[i] = true;
634 }
635 }
636 }
637 pattern_pos++;
638 }
639
640 AppendMIR(cur_block, insn);
641
642 code_ptr += width;
643 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
644
buzbee1fd33462013-03-25 13:40:45 -0700645 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800646
647 if (df_flags & DF_HAS_DEFS) {
648 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
649 }
650
651 if (flags & Instruction::kBranch) {
652 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
653 width, flags, code_ptr, code_end);
654 } else if (flags & Instruction::kReturn) {
655 cur_block->terminated_by_return = true;
656 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700657 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800658 /*
659 * Terminate the current block if there are instructions
660 * afterwards.
661 */
662 if (code_ptr < code_end) {
663 /*
664 * Create a fallthrough block for real instructions
665 * (incl. NOP).
666 */
667 if (ContentIsInsn(code_ptr)) {
668 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
669 /* immed_pred_block_p */ NULL);
670 }
671 }
672 } else if (flags & Instruction::kThrow) {
673 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
674 code_ptr, code_end);
675 } else if (flags & Instruction::kSwitch) {
676 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
677 }
678 current_offset_ += width;
679 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
680 false, /* immed_pred_block_p */ NULL);
681 if (next_block) {
682 /*
683 * The next instruction could be the target of a previously parsed
684 * forward branch so a block is already created. If the current
685 * instruction is not an unconditional branch, connect them through
686 * the fall-through link.
687 */
688 DCHECK(cur_block->fall_through == NULL ||
689 cur_block->fall_through == next_block ||
690 cur_block->fall_through == exit_block_);
691
692 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
693 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700694 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800695 }
696 cur_block = next_block;
697 }
698 }
699 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
700 DumpCFG("/sdcard/1_post_parse_cfg/", true);
701 }
702
703 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700704 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800705 }
706}
707
708void MIRGraph::ShowOpcodeStats()
709{
710 DCHECK(opcode_count_ != NULL);
711 LOG(INFO) << "Opcode Count";
712 for (int i = 0; i < kNumPackedOpcodes; i++) {
713 if (opcode_count_[i] != 0) {
714 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
715 << " " << opcode_count_[i];
716 }
717 }
718}
719
720// TODO: use a configurable base prefix, and adjust callers to supply pass name.
721/* Dump the CFG into a DOT graph */
722void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks)
723{
724 FILE* file;
725 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
726 ReplaceSpecialChars(fname);
727 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
728 GetEntryBlock()->fall_through->start_offset);
729 file = fopen(fname.c_str(), "w");
730 if (file == NULL) {
731 return;
732 }
733 fprintf(file, "digraph G {\n");
734
735 fprintf(file, " rankdir=TB\n");
736
737 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
738 int idx;
739
740 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700741 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800742 BasicBlock *bb = GetBasicBlock(block_idx);
743 if (bb == NULL) break;
744 if (bb->block_type == kDead) continue;
745 if (bb->block_type == kEntryBlock) {
746 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
747 } else if (bb->block_type == kExitBlock) {
748 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
749 } else if (bb->block_type == kDalvikByteCode) {
750 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
751 bb->start_offset, bb->id);
752 const MIR *mir;
753 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
754 bb->first_mir_insn ? " | " : " ");
755 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
756 int opcode = mir->dalvikInsn.opcode;
757 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700758 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800759 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700760 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800761 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
762 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
763 mir->next ? " | " : " ");
764 }
765 fprintf(file, " }\"];\n\n");
766 } else if (bb->block_type == kExceptionHandling) {
767 char block_name[BLOCK_NAME_LEN];
768
769 GetBlockName(bb, block_name);
770 fprintf(file, " %s [shape=invhouse];\n", block_name);
771 }
772
773 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
774
775 if (bb->taken) {
776 GetBlockName(bb, block_name1);
777 GetBlockName(bb->taken, block_name2);
778 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
779 block_name1, block_name2);
780 }
781 if (bb->fall_through) {
782 GetBlockName(bb, block_name1);
783 GetBlockName(bb->fall_through, block_name2);
784 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
785 }
786
787 if (bb->successor_block_list.block_list_type != kNotUsed) {
788 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
789 bb->start_offset, bb->id,
790 (bb->successor_block_list.block_list_type == kCatch) ?
791 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700792 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
793 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800794
795 int succ_id = 0;
796 while (true) {
797 if (successor_block_info == NULL) break;
798
799 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700800 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800801
802 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
803 succ_id++,
804 successor_block_info->key,
805 dest_block->start_offset,
806 (next_successor_block_info != NULL) ? " | " : " ");
807
808 successor_block_info = next_successor_block_info;
809 }
810 fprintf(file, " }\"];\n\n");
811
812 GetBlockName(bb, block_name1);
813 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
814 block_name1, bb->start_offset, bb->id);
815
816 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
817 bb->successor_block_list.block_list_type == kSparseSwitch) {
818
buzbee862a7602013-04-05 10:58:54 -0700819 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800820
821 succ_id = 0;
822 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700823 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800824 if (successor_block_info == NULL) break;
825
826 BasicBlock *dest_block = successor_block_info->block;
827
828 GetBlockName(dest_block, block_name2);
829 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
830 bb->id, succ_id++, block_name2);
831 }
832 }
833 }
834 fprintf(file, "\n");
835
836 if (cu_->verbose) {
837 /* Display the dominator tree */
838 GetBlockName(bb, block_name1);
839 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
840 block_name1, block_name1);
841 if (bb->i_dom) {
842 GetBlockName(bb->i_dom, block_name2);
843 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
844 }
845 }
846 }
847 fprintf(file, "}\n");
848 fclose(file);
849}
850
buzbee1fd33462013-03-25 13:40:45 -0700851/* Insert an MIR instruction to the end of a basic block */
852void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir)
853{
854 if (bb->first_mir_insn == NULL) {
855 DCHECK(bb->last_mir_insn == NULL);
856 bb->last_mir_insn = bb->first_mir_insn = mir;
857 mir->prev = mir->next = NULL;
858 } else {
859 bb->last_mir_insn->next = mir;
860 mir->prev = bb->last_mir_insn;
861 mir->next = NULL;
862 bb->last_mir_insn = mir;
863 }
864}
865
866/* Insert an MIR instruction to the head of a basic block */
867void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir)
868{
869 if (bb->first_mir_insn == NULL) {
870 DCHECK(bb->last_mir_insn == NULL);
871 bb->last_mir_insn = bb->first_mir_insn = mir;
872 mir->prev = mir->next = NULL;
873 } else {
874 bb->first_mir_insn->prev = mir;
875 mir->next = bb->first_mir_insn;
876 mir->prev = NULL;
877 bb->first_mir_insn = mir;
878 }
879}
880
881/* Insert a MIR instruction after the specified MIR */
882void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir)
883{
884 new_mir->prev = current_mir;
885 new_mir->next = current_mir->next;
886 current_mir->next = new_mir;
887
888 if (new_mir->next) {
889 /* Is not the last MIR in the block */
890 new_mir->next->prev = new_mir;
891 } else {
892 /* Is the last MIR in the block */
893 bb->last_mir_insn = new_mir;
894 }
895}
896
897char* MIRGraph::GetDalvikDisassembly(const MIR* mir)
898{
899 DecodedInstruction insn = mir->dalvikInsn;
900 std::string str;
901 int flags = 0;
902 int opcode = insn.opcode;
903 char* ret;
904 bool nop = false;
905 SSARepresentation* ssa_rep = mir->ssa_rep;
906 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
907 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
908 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
909
910 // Handle special cases.
911 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
912 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
913 str.append(": ");
914 // Recover the original Dex instruction
915 insn = mir->meta.throw_insn->dalvikInsn;
916 ssa_rep = mir->meta.throw_insn->ssa_rep;
917 defs = ssa_rep->num_defs;
918 uses = ssa_rep->num_uses;
919 opcode = insn.opcode;
920 } else if (opcode == kMirOpNop) {
921 str.append("[");
922 insn.opcode = mir->meta.original_opcode;
923 opcode = mir->meta.original_opcode;
924 nop = true;
925 }
926
927 if (opcode >= kMirOpFirst) {
928 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
929 } else {
930 dalvik_format = Instruction::FormatOf(insn.opcode);
931 flags = Instruction::FlagsOf(insn.opcode);
932 str.append(Instruction::Name(insn.opcode));
933 }
934
935 if (opcode == kMirOpPhi) {
936 int* incoming = reinterpret_cast<int*>(insn.vB);
937 str.append(StringPrintf(" %s = (%s",
938 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
939 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
940 str.append(StringPrintf(":%d",incoming[0]));
941 int i;
942 for (i = 1; i < uses; i++) {
943 str.append(StringPrintf(", %s:%d",
944 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
945 incoming[i]));
946 }
947 str.append(")");
948 } else if ((flags & Instruction::kBranch) != 0) {
949 // For branches, decode the instructions to print out the branch targets.
950 int offset = 0;
951 switch (dalvik_format) {
952 case Instruction::k21t:
953 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
954 offset = insn.vB;
955 break;
956 case Instruction::k22t:
957 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
958 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
959 offset = insn.vC;
960 break;
961 case Instruction::k10t:
962 case Instruction::k20t:
963 case Instruction::k30t:
964 offset = insn.vA;
965 break;
966 default:
967 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
968 }
969 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
970 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
971 } else {
972 // For invokes-style formats, treat wide regs as a pair of singles
973 bool show_singles = ((dalvik_format == Instruction::k35c) ||
974 (dalvik_format == Instruction::k3rc));
975 if (defs != 0) {
976 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
977 if (uses != 0) {
978 str.append(", ");
979 }
980 }
981 for (int i = 0; i < uses; i++) {
982 str.append(
983 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
984 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
985 // For the listing, skip the high sreg.
986 i++;
987 }
988 if (i != (uses -1)) {
989 str.append(",");
990 }
991 }
992 switch (dalvik_format) {
993 case Instruction::k11n: // Add one immediate from vB
994 case Instruction::k21s:
995 case Instruction::k31i:
996 case Instruction::k21h:
997 str.append(StringPrintf(", #%d", insn.vB));
998 break;
999 case Instruction::k51l: // Add one wide immediate
1000 str.append(StringPrintf(", #%lld", insn.vB_wide));
1001 break;
1002 case Instruction::k21c: // One register, one string/type/method index
1003 case Instruction::k31c:
1004 str.append(StringPrintf(", index #%d", insn.vB));
1005 break;
1006 case Instruction::k22c: // Two registers, one string/type/method index
1007 str.append(StringPrintf(", index #%d", insn.vC));
1008 break;
1009 case Instruction::k22s: // Add one immediate from vC
1010 case Instruction::k22b:
1011 str.append(StringPrintf(", #%d", insn.vC));
1012 break;
1013 default:
1014 ; // Nothing left to print
1015 }
1016 }
1017 if (nop) {
1018 str.append("]--optimized away");
1019 }
1020 int length = str.length() + 1;
buzbee862a7602013-04-05 10:58:54 -07001021 ret = static_cast<char*>(arena_->NewMem(length, false, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001022 strncpy(ret, str.c_str(), length);
1023 return ret;
1024}
1025
1026/* Turn method name into a legal Linux file name */
1027void MIRGraph::ReplaceSpecialChars(std::string& str)
1028{
1029 static const struct { const char before; const char after; } match[] =
1030 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
1031 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
1032 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1033 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1034 }
1035}
1036
1037std::string MIRGraph::GetSSAName(int ssa_reg)
1038{
Ian Rogers39ebcb82013-05-30 16:57:23 -07001039 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1040 // the arena. We should be smarter and just place straight into the arena, or compute the
1041 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001042 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1043}
1044
1045// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
1046std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only)
1047{
1048 if (reg_location_ == NULL) {
1049 // Pre-SSA - just use the standard name
1050 return GetSSAName(ssa_reg);
1051 }
1052 if (IsConst(reg_location_[ssa_reg])) {
1053 if (!singles_only && reg_location_[ssa_reg].wide) {
1054 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1055 ConstantValueWide(reg_location_[ssa_reg]));
1056 } else {
1057 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg),GetSSASubscript(ssa_reg),
1058 ConstantValue(reg_location_[ssa_reg]));
1059 }
1060 } else {
1061 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1062 }
1063}
1064
1065void MIRGraph::GetBlockName(BasicBlock* bb, char* name)
1066{
1067 switch (bb->block_type) {
1068 case kEntryBlock:
1069 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1070 break;
1071 case kExitBlock:
1072 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1073 break;
1074 case kDalvikByteCode:
1075 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1076 break;
1077 case kExceptionHandling:
1078 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1079 bb->id);
1080 break;
1081 default:
1082 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1083 break;
1084 }
1085}
1086
1087const char* MIRGraph::GetShortyFromTargetIdx(int target_idx)
1088{
1089 // FIXME: use current code unit for inline support.
1090 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1091 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1092}
1093
1094/* Debug Utility - dump a compilation unit */
1095void MIRGraph::DumpMIRGraph()
1096{
1097 BasicBlock* bb;
1098 const char* block_type_names[] = {
1099 "Entry Block",
1100 "Code Block",
1101 "Exit Block",
1102 "Exception Handling",
1103 "Catch Block"
1104 };
1105
1106 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1107 LOG(INFO) << cu_->insns << " insns";
1108 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001109 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001110
1111 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001112 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001113 if (bb == NULL) break;
1114 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1115 bb->id,
1116 block_type_names[bb->block_type],
1117 bb->start_offset,
1118 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1119 bb->last_mir_insn ? "" : " empty");
1120 if (bb->taken) {
1121 LOG(INFO) << " Taken branch: block " << bb->taken->id
1122 << "(0x" << std::hex << bb->taken->start_offset << ")";
1123 }
1124 if (bb->fall_through) {
1125 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1126 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1127 }
1128 }
1129}
1130
1131/*
1132 * Build an array of location records for the incoming arguments.
1133 * Note: one location record per word of arguments, with dummy
1134 * high-word loc for wide arguments. Also pull up any following
1135 * MOVE_RESULT and incorporate it into the invoke.
1136 */
1137CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
1138 bool is_range)
1139{
buzbee862a7602013-04-05 10:58:54 -07001140 CallInfo* info = static_cast<CallInfo*>(arena_->NewMem(sizeof(CallInfo), true,
1141 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001142 MIR* move_result_mir = FindMoveResult(bb, mir);
1143 if (move_result_mir == NULL) {
1144 info->result.location = kLocInvalid;
1145 } else {
1146 info->result = GetRawDest(move_result_mir);
1147 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1148 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1149 }
1150 info->num_arg_words = mir->ssa_rep->num_uses;
1151 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
buzbee862a7602013-04-05 10:58:54 -07001152 (arena_->NewMem(sizeof(RegLocation) * info->num_arg_words, false,
1153 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001154 for (int i = 0; i < info->num_arg_words; i++) {
1155 info->args[i] = GetRawSrc(mir, i);
1156 }
1157 info->opt_flags = mir->optimization_flags;
1158 info->type = type;
1159 info->is_range = is_range;
1160 info->index = mir->dalvikInsn.vB;
1161 info->offset = mir->offset;
1162 return info;
1163}
1164
buzbee862a7602013-04-05 10:58:54 -07001165// Allocate a new basic block.
1166BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id)
1167{
1168 BasicBlock* bb = static_cast<BasicBlock*>(arena_->NewMem(sizeof(BasicBlock), true,
1169 ArenaAllocator::kAllocBB));
1170 bb->block_type = block_type;
1171 bb->id = block_id;
1172 // TUNING: better estimate of the exit block predecessors?
1173 bb->predecessors = new (arena_)
1174 GrowableArray<BasicBlock*>(arena_, (block_type == kExitBlock) ? 2048 : 2, kGrowableArrayPredecessors);
1175 bb->successor_block_list.block_list_type = kNotUsed;
1176 block_id_map_.Put(block_id, block_id);
1177 return bb;
1178}
buzbee1fd33462013-03-25 13:40:45 -07001179
buzbee311ca162013-02-28 15:56:43 -08001180} // namespace art