blob: 37600fc0aedf1c5a4f81810bacf2e18cd413d0f5 [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
17#include "compiler_internals.h"
18#include "mir_graph.h"
19#include "leb128.h"
20#include "dex_file-inl.h"
21
22namespace art {
23
24#define MAX_PATTERN_LEN 5
25
26struct CodePattern {
27 const Instruction::Code opcodes[MAX_PATTERN_LEN];
28 const SpecialCaseHandler handler_code;
29};
30
31static const CodePattern special_patterns[] = {
32 {{Instruction::RETURN_VOID}, kNullMethod},
33 {{Instruction::CONST, Instruction::RETURN}, kConstFunction},
34 {{Instruction::CONST_4, Instruction::RETURN}, kConstFunction},
35 {{Instruction::CONST_4, Instruction::RETURN_OBJECT}, kConstFunction},
36 {{Instruction::CONST_16, Instruction::RETURN}, kConstFunction},
37 {{Instruction::IGET, Instruction:: RETURN}, kIGet},
38 {{Instruction::IGET_BOOLEAN, Instruction::RETURN}, kIGetBoolean},
39 {{Instruction::IGET_OBJECT, Instruction::RETURN_OBJECT}, kIGetObject},
40 {{Instruction::IGET_BYTE, Instruction::RETURN}, kIGetByte},
41 {{Instruction::IGET_CHAR, Instruction::RETURN}, kIGetChar},
42 {{Instruction::IGET_SHORT, Instruction::RETURN}, kIGetShort},
43 {{Instruction::IGET_WIDE, Instruction::RETURN_WIDE}, kIGetWide},
44 {{Instruction::IPUT, Instruction::RETURN_VOID}, kIPut},
45 {{Instruction::IPUT_BOOLEAN, Instruction::RETURN_VOID}, kIPutBoolean},
46 {{Instruction::IPUT_OBJECT, Instruction::RETURN_VOID}, kIPutObject},
47 {{Instruction::IPUT_BYTE, Instruction::RETURN_VOID}, kIPutByte},
48 {{Instruction::IPUT_CHAR, Instruction::RETURN_VOID}, kIPutChar},
49 {{Instruction::IPUT_SHORT, Instruction::RETURN_VOID}, kIPutShort},
50 {{Instruction::IPUT_WIDE, Instruction::RETURN_VOID}, kIPutWide},
51 {{Instruction::RETURN}, kIdentity},
52 {{Instruction::RETURN_OBJECT}, kIdentity},
53 {{Instruction::RETURN_WIDE}, kIdentity},
54};
55
buzbee1fd33462013-03-25 13:40:45 -070056const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
57 "Phi",
58 "Copy",
59 "FusedCmplFloat",
60 "FusedCmpgFloat",
61 "FusedCmplDouble",
62 "FusedCmpgDouble",
63 "FusedCmpLong",
64 "Nop",
65 "OpNullCheck",
66 "OpRangeCheck",
67 "OpDivZeroCheck",
68 "Check1",
69 "Check2",
70 "Select",
71};
72
buzbee862a7602013-04-05 10:58:54 -070073MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070074 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070075 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070076 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080077 ssa_base_vregs_(NULL),
78 ssa_subscripts_(NULL),
79 ssa_strings_(NULL),
80 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
115bool MIRGraph::ContentIsInsn(const uint16_t* code_ptr) {
116 uint16_t instr = *code_ptr;
117 Instruction::Code opcode = static_cast<Instruction::Code>(instr & 0xff);
118 /*
119 * Since the low 8-bit in metadata may look like NOP, we need to check
120 * both the low and whole sub-word to determine whether it is code or data.
121 */
122 return (opcode != Instruction::NOP || instr == 0);
123}
124
125/*
126 * Parse an instruction, return the length of the instruction
127 */
128int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction)
129{
130 // Don't parse instruction data
131 if (!ContentIsInsn(code_ptr)) {
132 return 0;
133 }
134
135 const Instruction* instruction = Instruction::At(code_ptr);
136 *decoded_instruction = DecodedInstruction(instruction);
137
138 return instruction->SizeInCodeUnits();
139}
140
141
142/* Split an existing block from the specified code offset into two */
143BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
144 BasicBlock* orig_block, BasicBlock** immed_pred_block_p)
145{
146 MIR* insn = orig_block->first_mir_insn;
147 while (insn) {
148 if (insn->offset == code_offset) break;
149 insn = insn->next;
150 }
151 if (insn == NULL) {
152 LOG(FATAL) << "Break split failed";
153 }
buzbee862a7602013-04-05 10:58:54 -0700154 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
155 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800156
157 bottom_block->start_offset = code_offset;
158 bottom_block->first_mir_insn = insn;
159 bottom_block->last_mir_insn = orig_block->last_mir_insn;
160
161 /* If this block was terminated by a return, the flag needs to go with the bottom block */
162 bottom_block->terminated_by_return = orig_block->terminated_by_return;
163 orig_block->terminated_by_return = false;
164
165 /* Add it to the quick lookup cache */
166 block_map_.Put(bottom_block->start_offset, bottom_block);
167
168 /* Handle the taken path */
169 bottom_block->taken = orig_block->taken;
170 if (bottom_block->taken) {
171 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700172 bottom_block->taken->predecessors->Delete(orig_block);
173 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800174 }
175
176 /* Handle the fallthrough path */
177 bottom_block->fall_through = orig_block->fall_through;
178 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700179 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800180 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700181 bottom_block->fall_through->predecessors->Delete(orig_block);
182 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800183 }
184
185 /* Handle the successor list */
186 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
187 bottom_block->successor_block_list = orig_block->successor_block_list;
188 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700189 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800190 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700191 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800192 if (successor_block_info == NULL) break;
193 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700194 bb->predecessors->Delete(orig_block);
195 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800196 }
197 }
198
199 orig_block->last_mir_insn = insn->prev;
200
201 insn->prev->next = NULL;
202 insn->prev = NULL;
203 /*
204 * Update the immediate predecessor block pointer so that outgoing edges
205 * can be applied to the proper block.
206 */
207 if (immed_pred_block_p) {
208 DCHECK_EQ(*immed_pred_block_p, orig_block);
209 *immed_pred_block_p = bottom_block;
210 }
211 return bottom_block;
212}
213
214/*
215 * Given a code offset, find out the block that starts with it. If the offset
216 * is in the middle of an existing block, split it into two. If immed_pred_block_p
217 * is not non-null and is the block being split, update *immed_pred_block_p to
218 * point to the bottom block so that outgoing edges can be set up properly
219 * (by the caller)
220 * Utilizes a map for fast lookup of the typical cases.
221 */
222BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
223 BasicBlock** immed_pred_block_p)
224{
225 BasicBlock* bb;
226 unsigned int i;
227 SafeMap<unsigned int, BasicBlock*>::iterator it;
228
229 it = block_map_.find(code_offset);
230 if (it != block_map_.end()) {
231 return it->second;
232 } else if (!create) {
233 return NULL;
234 }
235
236 if (split) {
buzbee862a7602013-04-05 10:58:54 -0700237 for (i = 0; i < block_list_.Size(); i++) {
238 bb = block_list_.Get(i);
buzbee311ca162013-02-28 15:56:43 -0800239 if (bb->block_type != kDalvikByteCode) continue;
240 /* Check if a branch jumps into the middle of an existing block */
241 if ((code_offset > bb->start_offset) && (bb->last_mir_insn != NULL) &&
242 (code_offset <= bb->last_mir_insn->offset)) {
243 BasicBlock *new_bb = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ?
244 immed_pred_block_p : NULL);
245 return new_bb;
246 }
247 }
248 }
249
250 /* Create a new one */
buzbee862a7602013-04-05 10:58:54 -0700251 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
252 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800253 bb->start_offset = code_offset;
254 block_map_.Put(bb->start_offset, bb);
255 return bb;
256}
257
258/* Identify code range in try blocks and set up the empty catch blocks */
259void MIRGraph::ProcessTryCatchBlocks()
260{
261 int tries_size = current_code_item_->tries_size_;
262 int offset;
263
264 if (tries_size == 0) {
265 return;
266 }
267
268 for (int i = 0; i < tries_size; i++) {
269 const DexFile::TryItem* pTry =
270 DexFile::GetTryItems(*current_code_item_, i);
271 int start_offset = pTry->start_addr_;
272 int end_offset = start_offset + pTry->insn_count_;
273 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700274 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800275 }
276 }
277
278 // Iterate over each of the handlers to enqueue the empty Catch blocks
279 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
280 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
281 for (uint32_t idx = 0; idx < handlers_size; idx++) {
282 CatchHandlerIterator iterator(handlers_ptr);
283 for (; iterator.HasNext(); iterator.Next()) {
284 uint32_t address = iterator.GetHandlerAddress();
285 FindBlock(address, false /* split */, true /*create*/,
286 /* immed_pred_block_p */ NULL);
287 }
288 handlers_ptr = iterator.EndDataPointer();
289 }
290}
291
292/* Process instructions with the kBranch flag */
293BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
294 int flags, const uint16_t* code_ptr,
295 const uint16_t* code_end)
296{
297 int target = cur_offset;
298 switch (insn->dalvikInsn.opcode) {
299 case Instruction::GOTO:
300 case Instruction::GOTO_16:
301 case Instruction::GOTO_32:
302 target += insn->dalvikInsn.vA;
303 break;
304 case Instruction::IF_EQ:
305 case Instruction::IF_NE:
306 case Instruction::IF_LT:
307 case Instruction::IF_GE:
308 case Instruction::IF_GT:
309 case Instruction::IF_LE:
310 cur_block->conditional_branch = true;
311 target += insn->dalvikInsn.vC;
312 break;
313 case Instruction::IF_EQZ:
314 case Instruction::IF_NEZ:
315 case Instruction::IF_LTZ:
316 case Instruction::IF_GEZ:
317 case Instruction::IF_GTZ:
318 case Instruction::IF_LEZ:
319 cur_block->conditional_branch = true;
320 target += insn->dalvikInsn.vB;
321 break;
322 default:
323 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
324 }
325 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
326 /* immed_pred_block_p */ &cur_block);
327 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700328 taken_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800329
330 /* Always terminate the current block for conditional branches */
331 if (flags & Instruction::kContinue) {
332 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
333 /*
334 * If the method is processed
335 * in sequential order from the
336 * beginning, we don't need to
337 * specify split for continue
338 * blocks. However, this
339 * routine can be called by
340 * compileLoop, which starts
341 * parsing the method from an
342 * arbitrary address in the
343 * method body.
344 */
345 true,
346 /* create */
347 true,
348 /* immed_pred_block_p */
349 &cur_block);
350 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700351 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800352 } else if (code_ptr < code_end) {
353 /* Create a fallthrough block for real instructions (incl. NOP) */
354 if (ContentIsInsn(code_ptr)) {
355 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
356 /* immed_pred_block_p */ NULL);
357 }
358 }
359 return cur_block;
360}
361
362/* Process instructions with the kSwitch flag */
363void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
364 int flags)
365{
366 const uint16_t* switch_data =
367 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
368 int size;
369 const int* keyTable;
370 const int* target_table;
371 int i;
372 int first_key;
373
374 /*
375 * Packed switch data format:
376 * ushort ident = 0x0100 magic value
377 * ushort size number of entries in the table
378 * int first_key first (and lowest) switch case value
379 * int targets[size] branch targets, relative to switch opcode
380 *
381 * Total size is (4+size*2) 16-bit code units.
382 */
383 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
384 DCHECK_EQ(static_cast<int>(switch_data[0]),
385 static_cast<int>(Instruction::kPackedSwitchSignature));
386 size = switch_data[1];
387 first_key = switch_data[2] | (switch_data[3] << 16);
388 target_table = reinterpret_cast<const int*>(&switch_data[4]);
389 keyTable = NULL; // Make the compiler happy
390 /*
391 * Sparse switch data format:
392 * ushort ident = 0x0200 magic value
393 * ushort size number of entries in the table; > 0
394 * int keys[size] keys, sorted low-to-high; 32-bit aligned
395 * int targets[size] branch targets, relative to switch opcode
396 *
397 * Total size is (2+size*4) 16-bit code units.
398 */
399 } else {
400 DCHECK_EQ(static_cast<int>(switch_data[0]),
401 static_cast<int>(Instruction::kSparseSwitchSignature));
402 size = switch_data[1];
403 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
404 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
405 first_key = 0; // To make the compiler happy
406 }
407
408 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
409 LOG(FATAL) << "Successor block list already in use: "
410 << static_cast<int>(cur_block->successor_block_list.block_list_type);
411 }
412 cur_block->successor_block_list.block_list_type =
413 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
414 kPackedSwitch : kSparseSwitch;
buzbee862a7602013-04-05 10:58:54 -0700415 cur_block->successor_block_list.blocks =
416 new (arena_)GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800417
418 for (i = 0; i < size; i++) {
419 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
420 /* create */ true, /* immed_pred_block_p */ &cur_block);
421 SuccessorBlockInfo *successor_block_info =
buzbee862a7602013-04-05 10:58:54 -0700422 static_cast<SuccessorBlockInfo*>(arena_->NewMem(sizeof(SuccessorBlockInfo), false,
423 ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800424 successor_block_info->block = case_block;
425 successor_block_info->key =
426 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
427 first_key + i : keyTable[i];
buzbee862a7602013-04-05 10:58:54 -0700428 cur_block->successor_block_list.blocks->Insert(successor_block_info);
429 case_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800430 }
431
432 /* Fall-through case */
433 BasicBlock* fallthrough_block = FindBlock( cur_offset + width, /* split */ false,
434 /* create */ true, /* immed_pred_block_p */ NULL);
435 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700436 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800437}
438
439/* Process instructions with the kThrow flag */
440BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
441 int flags, ArenaBitVector* try_block_addr,
442 const uint16_t* code_ptr, const uint16_t* code_end)
443{
buzbee862a7602013-04-05 10:58:54 -0700444 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee311ca162013-02-28 15:56:43 -0800445
446 /* In try block */
447 if (in_try_block) {
448 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
449
450 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
451 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
452 LOG(FATAL) << "Successor block list already in use: "
453 << static_cast<int>(cur_block->successor_block_list.block_list_type);
454 }
455
456 cur_block->successor_block_list.block_list_type = kCatch;
buzbee862a7602013-04-05 10:58:54 -0700457 cur_block->successor_block_list.blocks =
458 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800459
460 for (;iterator.HasNext(); iterator.Next()) {
461 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
462 false /* creat */, NULL /* immed_pred_block_p */);
463 catch_block->catch_entry = true;
464 if (kIsDebugBuild) {
465 catches_.insert(catch_block->start_offset);
466 }
467 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
buzbee862a7602013-04-05 10:58:54 -0700468 (arena_->NewMem(sizeof(SuccessorBlockInfo), false, ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800469 successor_block_info->block = catch_block;
470 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee862a7602013-04-05 10:58:54 -0700471 cur_block->successor_block_list.blocks->Insert(successor_block_info);
472 catch_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800473 }
474 } else {
buzbee862a7602013-04-05 10:58:54 -0700475 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800476 cur_block->taken = eh_block;
buzbee862a7602013-04-05 10:58:54 -0700477 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800478 eh_block->start_offset = cur_offset;
buzbee862a7602013-04-05 10:58:54 -0700479 eh_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800480 }
481
482 if (insn->dalvikInsn.opcode == Instruction::THROW){
483 cur_block->explicit_throw = true;
484 if ((code_ptr < code_end) && ContentIsInsn(code_ptr)) {
485 // Force creation of new block following THROW via side-effect
486 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
487 /* immed_pred_block_p */ NULL);
488 }
489 if (!in_try_block) {
490 // Don't split a THROW that can't rethrow - we're done.
491 return cur_block;
492 }
493 }
494
495 /*
496 * Split the potentially-throwing instruction into two parts.
497 * The first half will be a pseudo-op that captures the exception
498 * edges and terminates the basic block. It always falls through.
499 * Then, create a new basic block that begins with the throwing instruction
500 * (minus exceptions). Note: this new basic block must NOT be entered into
501 * the block_map. If the potentially-throwing instruction is the target of a
502 * future branch, we need to find the check psuedo half. The new
503 * basic block containing the work portion of the instruction should
504 * only be entered via fallthrough from the block containing the
505 * pseudo exception edge MIR. Note also that this new block is
506 * not automatically terminated after the work portion, and may
507 * contain following instructions.
508 */
buzbee862a7602013-04-05 10:58:54 -0700509 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
510 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800511 new_block->start_offset = insn->offset;
512 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700513 new_block->predecessors->Insert(cur_block);
514 MIR* new_insn = static_cast<MIR*>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800515 *new_insn = *insn;
516 insn->dalvikInsn.opcode =
517 static_cast<Instruction::Code>(kMirOpCheck);
518 // Associate the two halves
519 insn->meta.throw_insn = new_insn;
520 new_insn->meta.throw_insn = insn;
521 AppendMIR(new_block, new_insn);
522 return new_block;
523}
524
525/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
526void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
527 InvokeType invoke_type, uint32_t class_def_idx,
528 uint32_t method_idx, jobject class_loader, const DexFile& dex_file)
529{
530 current_code_item_ = code_item;
531 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
532 current_method_ = m_units_.size();
533 current_offset_ = 0;
534 // TODO: will need to snapshot stack image and use that as the mir context identification.
535 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
536 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
537 const uint16_t* code_ptr = current_code_item_->insns_;
538 const uint16_t* code_end =
539 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
540
541 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbee862a7602013-04-05 10:58:54 -0700542 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800543 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700544 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
545 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800546
547 // If this is the first method, set up default entry and exit blocks.
548 if (current_method_ == 0) {
549 DCHECK(entry_block_ == NULL);
550 DCHECK(exit_block_ == NULL);
551 DCHECK(num_blocks_ == 0);
buzbee862a7602013-04-05 10:58:54 -0700552 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
553 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
554 block_list_.Insert(entry_block_);
555 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800556 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
557 cu_->dex_file = &dex_file;
558 cu_->class_def_idx = class_def_idx;
559 cu_->method_idx = method_idx;
560 cu_->access_flags = access_flags;
561 cu_->invoke_type = invoke_type;
562 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
563 cu_->num_ins = current_code_item_->ins_size_;
564 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
565 cu_->num_outs = current_code_item_->outs_size_;
566 cu_->num_dalvik_registers = current_code_item_->registers_size_;
567 cu_->insns = current_code_item_->insns_;
568 cu_->code_item = current_code_item_;
569 } else {
570 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
571 /*
572 * Will need to manage storage for ins & outs, push prevous state and update
573 * insert point.
574 */
575 }
576
577 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700578 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800579 DCHECK_EQ(current_offset_, 0);
580 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700581 block_list_.Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800582 /* Add first block to the fast lookup cache */
583// FIXME: block map needs association with offset/method pair rather than just offset
584 block_map_.Put(cur_block->start_offset, cur_block);
585// FIXME: this needs to insert at the insert point rather than entry block.
586 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700587 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800588
589 /* Identify code range in try blocks and set up the empty catch blocks */
590 ProcessTryCatchBlocks();
591
592 /* Set up for simple method detection */
593 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
594 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
595 bool* dead_pattern =
buzbee862a7602013-04-05 10:58:54 -0700596 static_cast<bool*>(arena_->NewMem(sizeof(bool) * num_patterns, true,
597 ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800598 SpecialCaseHandler special_case = kNoHandler;
599 // FIXME - wire this up
600 (void)special_case;
601 int pattern_pos = 0;
602
603 /* Parse all instructions and put them into containing basic blocks */
604 while (code_ptr < code_end) {
buzbee862a7602013-04-05 10:58:54 -0700605 MIR *insn = static_cast<MIR *>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800606 insn->offset = current_offset_;
607 insn->m_unit_index = current_method_;
608 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
609 insn->width = width;
610 Instruction::Code opcode = insn->dalvikInsn.opcode;
611 if (opcode_count_ != NULL) {
612 opcode_count_[static_cast<int>(opcode)]++;
613 }
614
615 /* Terminate when the data section is seen */
616 if (width == 0)
617 break;
618
619 /* Possible simple method? */
620 if (live_pattern) {
621 live_pattern = false;
622 special_case = kNoHandler;
623 for (int i = 0; i < num_patterns; i++) {
624 if (!dead_pattern[i]) {
625 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
626 live_pattern = true;
627 special_case = special_patterns[i].handler_code;
628 } else {
629 dead_pattern[i] = true;
630 }
631 }
632 }
633 pattern_pos++;
634 }
635
636 AppendMIR(cur_block, insn);
637
638 code_ptr += width;
639 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
640
buzbee1fd33462013-03-25 13:40:45 -0700641 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800642
643 if (df_flags & DF_HAS_DEFS) {
644 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
645 }
646
647 if (flags & Instruction::kBranch) {
648 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
649 width, flags, code_ptr, code_end);
650 } else if (flags & Instruction::kReturn) {
651 cur_block->terminated_by_return = true;
652 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700653 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800654 /*
655 * Terminate the current block if there are instructions
656 * afterwards.
657 */
658 if (code_ptr < code_end) {
659 /*
660 * Create a fallthrough block for real instructions
661 * (incl. NOP).
662 */
663 if (ContentIsInsn(code_ptr)) {
664 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
665 /* immed_pred_block_p */ NULL);
666 }
667 }
668 } else if (flags & Instruction::kThrow) {
669 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
670 code_ptr, code_end);
671 } else if (flags & Instruction::kSwitch) {
672 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
673 }
674 current_offset_ += width;
675 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
676 false, /* immed_pred_block_p */ NULL);
677 if (next_block) {
678 /*
679 * The next instruction could be the target of a previously parsed
680 * forward branch so a block is already created. If the current
681 * instruction is not an unconditional branch, connect them through
682 * the fall-through link.
683 */
684 DCHECK(cur_block->fall_through == NULL ||
685 cur_block->fall_through == next_block ||
686 cur_block->fall_through == exit_block_);
687
688 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
689 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700690 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800691 }
692 cur_block = next_block;
693 }
694 }
695 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
696 DumpCFG("/sdcard/1_post_parse_cfg/", true);
697 }
698
699 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700700 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800701 }
702}
703
704void MIRGraph::ShowOpcodeStats()
705{
706 DCHECK(opcode_count_ != NULL);
707 LOG(INFO) << "Opcode Count";
708 for (int i = 0; i < kNumPackedOpcodes; i++) {
709 if (opcode_count_[i] != 0) {
710 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
711 << " " << opcode_count_[i];
712 }
713 }
714}
715
716// TODO: use a configurable base prefix, and adjust callers to supply pass name.
717/* Dump the CFG into a DOT graph */
718void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks)
719{
720 FILE* file;
721 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
722 ReplaceSpecialChars(fname);
723 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
724 GetEntryBlock()->fall_through->start_offset);
725 file = fopen(fname.c_str(), "w");
726 if (file == NULL) {
727 return;
728 }
729 fprintf(file, "digraph G {\n");
730
731 fprintf(file, " rankdir=TB\n");
732
733 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
734 int idx;
735
736 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700737 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800738 BasicBlock *bb = GetBasicBlock(block_idx);
739 if (bb == NULL) break;
740 if (bb->block_type == kDead) continue;
741 if (bb->block_type == kEntryBlock) {
742 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
743 } else if (bb->block_type == kExitBlock) {
744 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
745 } else if (bb->block_type == kDalvikByteCode) {
746 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
747 bb->start_offset, bb->id);
748 const MIR *mir;
749 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
750 bb->first_mir_insn ? " | " : " ");
751 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
752 int opcode = mir->dalvikInsn.opcode;
753 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700754 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800755 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700756 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800757 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
758 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
759 mir->next ? " | " : " ");
760 }
761 fprintf(file, " }\"];\n\n");
762 } else if (bb->block_type == kExceptionHandling) {
763 char block_name[BLOCK_NAME_LEN];
764
765 GetBlockName(bb, block_name);
766 fprintf(file, " %s [shape=invhouse];\n", block_name);
767 }
768
769 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
770
771 if (bb->taken) {
772 GetBlockName(bb, block_name1);
773 GetBlockName(bb->taken, block_name2);
774 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
775 block_name1, block_name2);
776 }
777 if (bb->fall_through) {
778 GetBlockName(bb, block_name1);
779 GetBlockName(bb->fall_through, block_name2);
780 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
781 }
782
783 if (bb->successor_block_list.block_list_type != kNotUsed) {
784 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
785 bb->start_offset, bb->id,
786 (bb->successor_block_list.block_list_type == kCatch) ?
787 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700788 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
789 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800790
791 int succ_id = 0;
792 while (true) {
793 if (successor_block_info == NULL) break;
794
795 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700796 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800797
798 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
799 succ_id++,
800 successor_block_info->key,
801 dest_block->start_offset,
802 (next_successor_block_info != NULL) ? " | " : " ");
803
804 successor_block_info = next_successor_block_info;
805 }
806 fprintf(file, " }\"];\n\n");
807
808 GetBlockName(bb, block_name1);
809 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
810 block_name1, bb->start_offset, bb->id);
811
812 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
813 bb->successor_block_list.block_list_type == kSparseSwitch) {
814
buzbee862a7602013-04-05 10:58:54 -0700815 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800816
817 succ_id = 0;
818 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700819 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800820 if (successor_block_info == NULL) break;
821
822 BasicBlock *dest_block = successor_block_info->block;
823
824 GetBlockName(dest_block, block_name2);
825 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
826 bb->id, succ_id++, block_name2);
827 }
828 }
829 }
830 fprintf(file, "\n");
831
832 if (cu_->verbose) {
833 /* Display the dominator tree */
834 GetBlockName(bb, block_name1);
835 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
836 block_name1, block_name1);
837 if (bb->i_dom) {
838 GetBlockName(bb->i_dom, block_name2);
839 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
840 }
841 }
842 }
843 fprintf(file, "}\n");
844 fclose(file);
845}
846
buzbee1fd33462013-03-25 13:40:45 -0700847/* Insert an MIR instruction to the end of a basic block */
848void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir)
849{
850 if (bb->first_mir_insn == NULL) {
851 DCHECK(bb->last_mir_insn == NULL);
852 bb->last_mir_insn = bb->first_mir_insn = mir;
853 mir->prev = mir->next = NULL;
854 } else {
855 bb->last_mir_insn->next = mir;
856 mir->prev = bb->last_mir_insn;
857 mir->next = NULL;
858 bb->last_mir_insn = mir;
859 }
860}
861
862/* Insert an MIR instruction to the head of a basic block */
863void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir)
864{
865 if (bb->first_mir_insn == NULL) {
866 DCHECK(bb->last_mir_insn == NULL);
867 bb->last_mir_insn = bb->first_mir_insn = mir;
868 mir->prev = mir->next = NULL;
869 } else {
870 bb->first_mir_insn->prev = mir;
871 mir->next = bb->first_mir_insn;
872 mir->prev = NULL;
873 bb->first_mir_insn = mir;
874 }
875}
876
877/* Insert a MIR instruction after the specified MIR */
878void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir)
879{
880 new_mir->prev = current_mir;
881 new_mir->next = current_mir->next;
882 current_mir->next = new_mir;
883
884 if (new_mir->next) {
885 /* Is not the last MIR in the block */
886 new_mir->next->prev = new_mir;
887 } else {
888 /* Is the last MIR in the block */
889 bb->last_mir_insn = new_mir;
890 }
891}
892
893char* MIRGraph::GetDalvikDisassembly(const MIR* mir)
894{
895 DecodedInstruction insn = mir->dalvikInsn;
896 std::string str;
897 int flags = 0;
898 int opcode = insn.opcode;
899 char* ret;
900 bool nop = false;
901 SSARepresentation* ssa_rep = mir->ssa_rep;
902 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
903 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
904 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
905
906 // Handle special cases.
907 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
908 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
909 str.append(": ");
910 // Recover the original Dex instruction
911 insn = mir->meta.throw_insn->dalvikInsn;
912 ssa_rep = mir->meta.throw_insn->ssa_rep;
913 defs = ssa_rep->num_defs;
914 uses = ssa_rep->num_uses;
915 opcode = insn.opcode;
916 } else if (opcode == kMirOpNop) {
917 str.append("[");
918 insn.opcode = mir->meta.original_opcode;
919 opcode = mir->meta.original_opcode;
920 nop = true;
921 }
922
923 if (opcode >= kMirOpFirst) {
924 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
925 } else {
926 dalvik_format = Instruction::FormatOf(insn.opcode);
927 flags = Instruction::FlagsOf(insn.opcode);
928 str.append(Instruction::Name(insn.opcode));
929 }
930
931 if (opcode == kMirOpPhi) {
932 int* incoming = reinterpret_cast<int*>(insn.vB);
933 str.append(StringPrintf(" %s = (%s",
934 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
935 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
936 str.append(StringPrintf(":%d",incoming[0]));
937 int i;
938 for (i = 1; i < uses; i++) {
939 str.append(StringPrintf(", %s:%d",
940 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
941 incoming[i]));
942 }
943 str.append(")");
944 } else if ((flags & Instruction::kBranch) != 0) {
945 // For branches, decode the instructions to print out the branch targets.
946 int offset = 0;
947 switch (dalvik_format) {
948 case Instruction::k21t:
949 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
950 offset = insn.vB;
951 break;
952 case Instruction::k22t:
953 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
954 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
955 offset = insn.vC;
956 break;
957 case Instruction::k10t:
958 case Instruction::k20t:
959 case Instruction::k30t:
960 offset = insn.vA;
961 break;
962 default:
963 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
964 }
965 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
966 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
967 } else {
968 // For invokes-style formats, treat wide regs as a pair of singles
969 bool show_singles = ((dalvik_format == Instruction::k35c) ||
970 (dalvik_format == Instruction::k3rc));
971 if (defs != 0) {
972 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
973 if (uses != 0) {
974 str.append(", ");
975 }
976 }
977 for (int i = 0; i < uses; i++) {
978 str.append(
979 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
980 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
981 // For the listing, skip the high sreg.
982 i++;
983 }
984 if (i != (uses -1)) {
985 str.append(",");
986 }
987 }
988 switch (dalvik_format) {
989 case Instruction::k11n: // Add one immediate from vB
990 case Instruction::k21s:
991 case Instruction::k31i:
992 case Instruction::k21h:
993 str.append(StringPrintf(", #%d", insn.vB));
994 break;
995 case Instruction::k51l: // Add one wide immediate
996 str.append(StringPrintf(", #%lld", insn.vB_wide));
997 break;
998 case Instruction::k21c: // One register, one string/type/method index
999 case Instruction::k31c:
1000 str.append(StringPrintf(", index #%d", insn.vB));
1001 break;
1002 case Instruction::k22c: // Two registers, one string/type/method index
1003 str.append(StringPrintf(", index #%d", insn.vC));
1004 break;
1005 case Instruction::k22s: // Add one immediate from vC
1006 case Instruction::k22b:
1007 str.append(StringPrintf(", #%d", insn.vC));
1008 break;
1009 default:
1010 ; // Nothing left to print
1011 }
1012 }
1013 if (nop) {
1014 str.append("]--optimized away");
1015 }
1016 int length = str.length() + 1;
buzbee862a7602013-04-05 10:58:54 -07001017 ret = static_cast<char*>(arena_->NewMem(length, false, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001018 strncpy(ret, str.c_str(), length);
1019 return ret;
1020}
1021
1022/* Turn method name into a legal Linux file name */
1023void MIRGraph::ReplaceSpecialChars(std::string& str)
1024{
1025 static const struct { const char before; const char after; } match[] =
1026 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
1027 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
1028 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1029 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1030 }
1031}
1032
1033std::string MIRGraph::GetSSAName(int ssa_reg)
1034{
1035 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1036}
1037
1038// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
1039std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only)
1040{
1041 if (reg_location_ == NULL) {
1042 // Pre-SSA - just use the standard name
1043 return GetSSAName(ssa_reg);
1044 }
1045 if (IsConst(reg_location_[ssa_reg])) {
1046 if (!singles_only && reg_location_[ssa_reg].wide) {
1047 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1048 ConstantValueWide(reg_location_[ssa_reg]));
1049 } else {
1050 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg),GetSSASubscript(ssa_reg),
1051 ConstantValue(reg_location_[ssa_reg]));
1052 }
1053 } else {
1054 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1055 }
1056}
1057
1058void MIRGraph::GetBlockName(BasicBlock* bb, char* name)
1059{
1060 switch (bb->block_type) {
1061 case kEntryBlock:
1062 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1063 break;
1064 case kExitBlock:
1065 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1066 break;
1067 case kDalvikByteCode:
1068 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1069 break;
1070 case kExceptionHandling:
1071 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1072 bb->id);
1073 break;
1074 default:
1075 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1076 break;
1077 }
1078}
1079
1080const char* MIRGraph::GetShortyFromTargetIdx(int target_idx)
1081{
1082 // FIXME: use current code unit for inline support.
1083 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1084 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1085}
1086
1087/* Debug Utility - dump a compilation unit */
1088void MIRGraph::DumpMIRGraph()
1089{
1090 BasicBlock* bb;
1091 const char* block_type_names[] = {
1092 "Entry Block",
1093 "Code Block",
1094 "Exit Block",
1095 "Exception Handling",
1096 "Catch Block"
1097 };
1098
1099 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1100 LOG(INFO) << cu_->insns << " insns";
1101 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001102 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001103
1104 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001105 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001106 if (bb == NULL) break;
1107 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1108 bb->id,
1109 block_type_names[bb->block_type],
1110 bb->start_offset,
1111 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1112 bb->last_mir_insn ? "" : " empty");
1113 if (bb->taken) {
1114 LOG(INFO) << " Taken branch: block " << bb->taken->id
1115 << "(0x" << std::hex << bb->taken->start_offset << ")";
1116 }
1117 if (bb->fall_through) {
1118 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1119 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1120 }
1121 }
1122}
1123
1124/*
1125 * Build an array of location records for the incoming arguments.
1126 * Note: one location record per word of arguments, with dummy
1127 * high-word loc for wide arguments. Also pull up any following
1128 * MOVE_RESULT and incorporate it into the invoke.
1129 */
1130CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
1131 bool is_range)
1132{
buzbee862a7602013-04-05 10:58:54 -07001133 CallInfo* info = static_cast<CallInfo*>(arena_->NewMem(sizeof(CallInfo), true,
1134 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001135 MIR* move_result_mir = FindMoveResult(bb, mir);
1136 if (move_result_mir == NULL) {
1137 info->result.location = kLocInvalid;
1138 } else {
1139 info->result = GetRawDest(move_result_mir);
1140 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1141 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1142 }
1143 info->num_arg_words = mir->ssa_rep->num_uses;
1144 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
buzbee862a7602013-04-05 10:58:54 -07001145 (arena_->NewMem(sizeof(RegLocation) * info->num_arg_words, false,
1146 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001147 for (int i = 0; i < info->num_arg_words; i++) {
1148 info->args[i] = GetRawSrc(mir, i);
1149 }
1150 info->opt_flags = mir->optimization_flags;
1151 info->type = type;
1152 info->is_range = is_range;
1153 info->index = mir->dalvikInsn.vB;
1154 info->offset = mir->offset;
1155 return info;
1156}
1157
buzbee862a7602013-04-05 10:58:54 -07001158// Allocate a new basic block.
1159BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id)
1160{
1161 BasicBlock* bb = static_cast<BasicBlock*>(arena_->NewMem(sizeof(BasicBlock), true,
1162 ArenaAllocator::kAllocBB));
1163 bb->block_type = block_type;
1164 bb->id = block_id;
1165 // TUNING: better estimate of the exit block predecessors?
1166 bb->predecessors = new (arena_)
1167 GrowableArray<BasicBlock*>(arena_, (block_type == kExitBlock) ? 2048 : 2, kGrowableArrayPredecessors);
1168 bb->successor_block_list.block_list_type = kNotUsed;
1169 block_id_map_.Put(block_id, block_id);
1170 return bb;
1171}
buzbee1fd33462013-03-25 13:40:45 -07001172
buzbee311ca162013-02-28 15:56:43 -08001173} // namespace art