blob: a6e9556c4cf83c1576603fb17d9481fb435f27f5 [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
buzbee311ca162013-02-28 15:56:43 -080073MIRGraph::MIRGraph(CompilationUnit* cu)
buzbee1fd33462013-03-25 13:40:45 -070074 : reg_location_(NULL),
75 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080076 ssa_base_vregs_(NULL),
77 ssa_subscripts_(NULL),
78 ssa_strings_(NULL),
79 vreg_to_ssa_map_(NULL),
80 ssa_last_defs_(NULL),
81 is_constant_v_(NULL),
82 constant_values_(NULL),
83 num_reachable_blocks_(0),
84 i_dom_list_(NULL),
85 def_block_matrix_(NULL),
86 temp_block_v_(NULL),
87 temp_dalvik_register_v_(NULL),
88 temp_ssa_register_v_(NULL),
89 try_block_addr_(NULL),
90 entry_block_(NULL),
91 exit_block_(NULL),
92 cur_block_(NULL),
93 num_blocks_(0),
94 current_code_item_(NULL),
95 current_method_(kInvalidEntry),
96 current_offset_(kInvalidEntry),
97 def_count_(0),
98 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070099 num_ssa_regs_(0),
100 method_sreg_(0),
101 attributes_(METHOD_IS_LEAF) // Start with leaf assumption, change on encountering invoke.
102 {
buzbee311ca162013-02-28 15:56:43 -0800103 CompilerInitGrowableList(cu, &block_list_, 0, kListBlockList);
104 try_block_addr_ = AllocBitVector(cu, 0, true /* expandable */);
105}
106
107bool MIRGraph::ContentIsInsn(const uint16_t* code_ptr) {
108 uint16_t instr = *code_ptr;
109 Instruction::Code opcode = static_cast<Instruction::Code>(instr & 0xff);
110 /*
111 * Since the low 8-bit in metadata may look like NOP, we need to check
112 * both the low and whole sub-word to determine whether it is code or data.
113 */
114 return (opcode != Instruction::NOP || instr == 0);
115}
116
117/*
118 * Parse an instruction, return the length of the instruction
119 */
120int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction)
121{
122 // Don't parse instruction data
123 if (!ContentIsInsn(code_ptr)) {
124 return 0;
125 }
126
127 const Instruction* instruction = Instruction::At(code_ptr);
128 *decoded_instruction = DecodedInstruction(instruction);
129
130 return instruction->SizeInCodeUnits();
131}
132
133
134/* Split an existing block from the specified code offset into two */
135BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
136 BasicBlock* orig_block, BasicBlock** immed_pred_block_p)
137{
138 MIR* insn = orig_block->first_mir_insn;
139 while (insn) {
140 if (insn->offset == code_offset) break;
141 insn = insn->next;
142 }
143 if (insn == NULL) {
144 LOG(FATAL) << "Break split failed";
145 }
146 BasicBlock *bottom_block = NewMemBB(cu_, kDalvikByteCode, num_blocks_++);
147 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(bottom_block));
148
149 bottom_block->start_offset = code_offset;
150 bottom_block->first_mir_insn = insn;
151 bottom_block->last_mir_insn = orig_block->last_mir_insn;
152
153 /* If this block was terminated by a return, the flag needs to go with the bottom block */
154 bottom_block->terminated_by_return = orig_block->terminated_by_return;
155 orig_block->terminated_by_return = false;
156
157 /* Add it to the quick lookup cache */
158 block_map_.Put(bottom_block->start_offset, bottom_block);
159
160 /* Handle the taken path */
161 bottom_block->taken = orig_block->taken;
162 if (bottom_block->taken) {
163 orig_block->taken = NULL;
164 DeleteGrowableList(bottom_block->taken->predecessors, reinterpret_cast<uintptr_t>(orig_block));
165 InsertGrowableList(cu_, bottom_block->taken->predecessors,
166 reinterpret_cast<uintptr_t>(bottom_block));
167 }
168
169 /* Handle the fallthrough path */
170 bottom_block->fall_through = orig_block->fall_through;
171 orig_block->fall_through = bottom_block;
172 InsertGrowableList(cu_, bottom_block->predecessors,
173 reinterpret_cast<uintptr_t>(orig_block));
174 if (bottom_block->fall_through) {
175 DeleteGrowableList(bottom_block->fall_through->predecessors,
176 reinterpret_cast<uintptr_t>(orig_block));
177 InsertGrowableList(cu_, bottom_block->fall_through->predecessors,
178 reinterpret_cast<uintptr_t>(bottom_block));
179 }
180
181 /* Handle the successor list */
182 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
183 bottom_block->successor_block_list = orig_block->successor_block_list;
184 orig_block->successor_block_list.block_list_type = kNotUsed;
185 GrowableListIterator iterator;
186
187 GrowableListIteratorInit(&bottom_block->successor_block_list.blocks,
188 &iterator);
189 while (true) {
190 SuccessorBlockInfo *successor_block_info =
191 reinterpret_cast<SuccessorBlockInfo*>(GrowableListIteratorNext(&iterator));
192 if (successor_block_info == NULL) break;
193 BasicBlock *bb = successor_block_info->block;
194 DeleteGrowableList(bb->predecessors, reinterpret_cast<uintptr_t>(orig_block));
195 InsertGrowableList(cu_, bb->predecessors, reinterpret_cast<uintptr_t>(bottom_block));
196 }
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) {
237 for (i = 0; i < block_list_.num_used; i++) {
238 bb = reinterpret_cast<BasicBlock*>(block_list_.elem_list[i]);
239 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 */
251 bb = NewMemBB(cu_, kDalvikByteCode, num_blocks_++);
252 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(bb));
253 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++) {
274 SetBit(cu_, try_block_addr_, offset);
275 }
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;
328 InsertGrowableList(cu_, taken_block->predecessors, reinterpret_cast<uintptr_t>(cur_block));
329
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;
351 InsertGrowableList(cu_, fallthrough_block->predecessors,
352 reinterpret_cast<uintptr_t>(cur_block));
353 } else if (code_ptr < code_end) {
354 /* Create a fallthrough block for real instructions (incl. NOP) */
355 if (ContentIsInsn(code_ptr)) {
356 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
357 /* immed_pred_block_p */ NULL);
358 }
359 }
360 return cur_block;
361}
362
363/* Process instructions with the kSwitch flag */
364void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
365 int flags)
366{
367 const uint16_t* switch_data =
368 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
369 int size;
370 const int* keyTable;
371 const int* target_table;
372 int i;
373 int first_key;
374
375 /*
376 * Packed switch data format:
377 * ushort ident = 0x0100 magic value
378 * ushort size number of entries in the table
379 * int first_key first (and lowest) switch case value
380 * int targets[size] branch targets, relative to switch opcode
381 *
382 * Total size is (4+size*2) 16-bit code units.
383 */
384 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
385 DCHECK_EQ(static_cast<int>(switch_data[0]),
386 static_cast<int>(Instruction::kPackedSwitchSignature));
387 size = switch_data[1];
388 first_key = switch_data[2] | (switch_data[3] << 16);
389 target_table = reinterpret_cast<const int*>(&switch_data[4]);
390 keyTable = NULL; // Make the compiler happy
391 /*
392 * Sparse switch data format:
393 * ushort ident = 0x0200 magic value
394 * ushort size number of entries in the table; > 0
395 * int keys[size] keys, sorted low-to-high; 32-bit aligned
396 * int targets[size] branch targets, relative to switch opcode
397 *
398 * Total size is (2+size*4) 16-bit code units.
399 */
400 } else {
401 DCHECK_EQ(static_cast<int>(switch_data[0]),
402 static_cast<int>(Instruction::kSparseSwitchSignature));
403 size = switch_data[1];
404 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
405 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
406 first_key = 0; // To make the compiler happy
407 }
408
409 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
410 LOG(FATAL) << "Successor block list already in use: "
411 << static_cast<int>(cur_block->successor_block_list.block_list_type);
412 }
413 cur_block->successor_block_list.block_list_type =
414 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
415 kPackedSwitch : kSparseSwitch;
416 CompilerInitGrowableList(cu_, &cur_block->successor_block_list.blocks, size,
417 kListSuccessorBlocks);
418
419 for (i = 0; i < size; i++) {
420 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
421 /* create */ true, /* immed_pred_block_p */ &cur_block);
422 SuccessorBlockInfo *successor_block_info =
423 static_cast<SuccessorBlockInfo*>(NewMem(cu_, sizeof(SuccessorBlockInfo),
424 false, kAllocSuccessor));
425 successor_block_info->block = case_block;
426 successor_block_info->key =
427 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
428 first_key + i : keyTable[i];
429 InsertGrowableList(cu_, &cur_block->successor_block_list.blocks,
430 reinterpret_cast<uintptr_t>(successor_block_info));
431 InsertGrowableList(cu_, case_block->predecessors,
432 reinterpret_cast<uintptr_t>(cur_block));
433 }
434
435 /* Fall-through case */
436 BasicBlock* fallthrough_block = FindBlock( cur_offset + width, /* split */ false,
437 /* create */ true, /* immed_pred_block_p */ NULL);
438 cur_block->fall_through = fallthrough_block;
439 InsertGrowableList(cu_, fallthrough_block->predecessors,
440 reinterpret_cast<uintptr_t>(cur_block));
441}
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{
448 bool in_try_block = IsBitSet(try_block_addr, cur_offset);
449
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;
461 CompilerInitGrowableList(cu_, &cur_block->successor_block_list.blocks, 2,
462 kListSuccessorBlocks);
463
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*>
472 (NewMem(cu_, sizeof(SuccessorBlockInfo), false, kAllocSuccessor));
473 successor_block_info->block = catch_block;
474 successor_block_info->key = iterator.GetHandlerTypeIndex();
475 InsertGrowableList(cu_, &cur_block->successor_block_list.blocks,
476 reinterpret_cast<uintptr_t>(successor_block_info));
477 InsertGrowableList(cu_, catch_block->predecessors,
478 reinterpret_cast<uintptr_t>(cur_block));
479 }
480 } else {
481 BasicBlock *eh_block = NewMemBB(cu_, kExceptionHandling, num_blocks_++);
482 cur_block->taken = eh_block;
483 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(eh_block));
484 eh_block->start_offset = cur_offset;
485 InsertGrowableList(cu_, eh_block->predecessors, reinterpret_cast<uintptr_t>(cur_block));
486 }
487
488 if (insn->dalvikInsn.opcode == Instruction::THROW){
489 cur_block->explicit_throw = true;
490 if ((code_ptr < code_end) && ContentIsInsn(code_ptr)) {
491 // Force creation of new block following THROW via side-effect
492 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
493 /* immed_pred_block_p */ NULL);
494 }
495 if (!in_try_block) {
496 // Don't split a THROW that can't rethrow - we're done.
497 return cur_block;
498 }
499 }
500
501 /*
502 * Split the potentially-throwing instruction into two parts.
503 * The first half will be a pseudo-op that captures the exception
504 * edges and terminates the basic block. It always falls through.
505 * Then, create a new basic block that begins with the throwing instruction
506 * (minus exceptions). Note: this new basic block must NOT be entered into
507 * the block_map. If the potentially-throwing instruction is the target of a
508 * future branch, we need to find the check psuedo half. The new
509 * basic block containing the work portion of the instruction should
510 * only be entered via fallthrough from the block containing the
511 * pseudo exception edge MIR. Note also that this new block is
512 * not automatically terminated after the work portion, and may
513 * contain following instructions.
514 */
515 BasicBlock *new_block = NewMemBB(cu_, kDalvikByteCode, num_blocks_++);
516 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(new_block));
517 new_block->start_offset = insn->offset;
518 cur_block->fall_through = new_block;
519 InsertGrowableList(cu_, new_block->predecessors, reinterpret_cast<uintptr_t>(cur_block));
520 MIR* new_insn = static_cast<MIR*>(NewMem(cu_, sizeof(MIR), true, kAllocMIR));
521 *new_insn = *insn;
522 insn->dalvikInsn.opcode =
523 static_cast<Instruction::Code>(kMirOpCheck);
524 // Associate the two halves
525 insn->meta.throw_insn = new_insn;
526 new_insn->meta.throw_insn = insn;
527 AppendMIR(new_block, new_insn);
528 return new_block;
529}
530
531/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
532void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
533 InvokeType invoke_type, uint32_t class_def_idx,
534 uint32_t method_idx, jobject class_loader, const DexFile& dex_file)
535{
536 current_code_item_ = code_item;
537 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
538 current_method_ = m_units_.size();
539 current_offset_ = 0;
540 // TODO: will need to snapshot stack image and use that as the mir context identification.
541 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
542 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
543 const uint16_t* code_ptr = current_code_item_->insns_;
544 const uint16_t* code_end =
545 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
546
547 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
548 ReallocGrowableList(cu_, &block_list_, block_list_.num_used +
549 current_code_item_->insns_size_in_code_units_);
550 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
551 SetBit(cu_, try_block_addr_, current_code_item_->insns_size_in_code_units_);
552 ClearBit(try_block_addr_, current_code_item_->insns_size_in_code_units_);
553
554 // If this is the first method, set up default entry and exit blocks.
555 if (current_method_ == 0) {
556 DCHECK(entry_block_ == NULL);
557 DCHECK(exit_block_ == NULL);
558 DCHECK(num_blocks_ == 0);
559 entry_block_ = NewMemBB(cu_, kEntryBlock, num_blocks_++);
560 exit_block_ = NewMemBB(cu_, kExitBlock, num_blocks_++);
561 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(entry_block_));
562 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(exit_block_));
563 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
564 cu_->dex_file = &dex_file;
565 cu_->class_def_idx = class_def_idx;
566 cu_->method_idx = method_idx;
567 cu_->access_flags = access_flags;
568 cu_->invoke_type = invoke_type;
569 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
570 cu_->num_ins = current_code_item_->ins_size_;
571 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
572 cu_->num_outs = current_code_item_->outs_size_;
573 cu_->num_dalvik_registers = current_code_item_->registers_size_;
574 cu_->insns = current_code_item_->insns_;
575 cu_->code_item = current_code_item_;
576 } else {
577 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
578 /*
579 * Will need to manage storage for ins & outs, push prevous state and update
580 * insert point.
581 */
582 }
583
584 /* Current block to record parsed instructions */
585 BasicBlock *cur_block = NewMemBB(cu_, kDalvikByteCode, num_blocks_++);
586 DCHECK_EQ(current_offset_, 0);
587 cur_block->start_offset = current_offset_;
588 InsertGrowableList(cu_, &block_list_, reinterpret_cast<uintptr_t>(cur_block));
589 /* Add first block to the fast lookup cache */
590// FIXME: block map needs association with offset/method pair rather than just offset
591 block_map_.Put(cur_block->start_offset, cur_block);
592// FIXME: this needs to insert at the insert point rather than entry block.
593 entry_block_->fall_through = cur_block;
594 InsertGrowableList(cu_, cur_block->predecessors, reinterpret_cast<uintptr_t>(entry_block_));
595
596 /* Identify code range in try blocks and set up the empty catch blocks */
597 ProcessTryCatchBlocks();
598
599 /* Set up for simple method detection */
600 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
601 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
602 bool* dead_pattern =
603 static_cast<bool*>(NewMem(cu_, sizeof(bool) * num_patterns, true, kAllocMisc));
604 SpecialCaseHandler special_case = kNoHandler;
605 // FIXME - wire this up
606 (void)special_case;
607 int pattern_pos = 0;
608
609 /* Parse all instructions and put them into containing basic blocks */
610 while (code_ptr < code_end) {
611 MIR *insn = static_cast<MIR *>(NewMem(cu_, sizeof(MIR), true, kAllocMIR));
612 insn->offset = current_offset_;
613 insn->m_unit_index = current_method_;
614 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
615 insn->width = width;
616 Instruction::Code opcode = insn->dalvikInsn.opcode;
617 if (opcode_count_ != NULL) {
618 opcode_count_[static_cast<int>(opcode)]++;
619 }
620
621 /* Terminate when the data section is seen */
622 if (width == 0)
623 break;
624
625 /* Possible simple method? */
626 if (live_pattern) {
627 live_pattern = false;
628 special_case = kNoHandler;
629 for (int i = 0; i < num_patterns; i++) {
630 if (!dead_pattern[i]) {
631 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
632 live_pattern = true;
633 special_case = special_patterns[i].handler_code;
634 } else {
635 dead_pattern[i] = true;
636 }
637 }
638 }
639 pattern_pos++;
640 }
641
642 AppendMIR(cur_block, insn);
643
644 code_ptr += width;
645 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
646
buzbee1fd33462013-03-25 13:40:45 -0700647 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800648
649 if (df_flags & DF_HAS_DEFS) {
650 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
651 }
652
653 if (flags & Instruction::kBranch) {
654 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
655 width, flags, code_ptr, code_end);
656 } else if (flags & Instruction::kReturn) {
657 cur_block->terminated_by_return = true;
658 cur_block->fall_through = exit_block_;
659 InsertGrowableList(cu_, exit_block_->predecessors,
660 reinterpret_cast<uintptr_t>(cur_block));
661 /*
662 * Terminate the current block if there are instructions
663 * afterwards.
664 */
665 if (code_ptr < code_end) {
666 /*
667 * Create a fallthrough block for real instructions
668 * (incl. NOP).
669 */
670 if (ContentIsInsn(code_ptr)) {
671 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
672 /* immed_pred_block_p */ NULL);
673 }
674 }
675 } else if (flags & Instruction::kThrow) {
676 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
677 code_ptr, code_end);
678 } else if (flags & Instruction::kSwitch) {
679 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
680 }
681 current_offset_ += width;
682 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
683 false, /* immed_pred_block_p */ NULL);
684 if (next_block) {
685 /*
686 * The next instruction could be the target of a previously parsed
687 * forward branch so a block is already created. If the current
688 * instruction is not an unconditional branch, connect them through
689 * the fall-through link.
690 */
691 DCHECK(cur_block->fall_through == NULL ||
692 cur_block->fall_through == next_block ||
693 cur_block->fall_through == exit_block_);
694
695 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
696 cur_block->fall_through = next_block;
697 InsertGrowableList(cu_, next_block->predecessors,
698 reinterpret_cast<uintptr_t>(cur_block));
699 }
700 cur_block = next_block;
701 }
702 }
703 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
704 DumpCFG("/sdcard/1_post_parse_cfg/", true);
705 }
706
707 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700708 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800709 }
710}
711
712void MIRGraph::ShowOpcodeStats()
713{
714 DCHECK(opcode_count_ != NULL);
715 LOG(INFO) << "Opcode Count";
716 for (int i = 0; i < kNumPackedOpcodes; i++) {
717 if (opcode_count_[i] != 0) {
718 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
719 << " " << opcode_count_[i];
720 }
721 }
722}
723
724// TODO: use a configurable base prefix, and adjust callers to supply pass name.
725/* Dump the CFG into a DOT graph */
726void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks)
727{
728 FILE* file;
729 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
730 ReplaceSpecialChars(fname);
731 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
732 GetEntryBlock()->fall_through->start_offset);
733 file = fopen(fname.c_str(), "w");
734 if (file == NULL) {
735 return;
736 }
737 fprintf(file, "digraph G {\n");
738
739 fprintf(file, " rankdir=TB\n");
740
741 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
742 int idx;
743
744 for (idx = 0; idx < num_blocks; idx++) {
745 int block_idx = all_blocks ? idx : dfs_order_.elem_list[idx];
746 BasicBlock *bb = GetBasicBlock(block_idx);
747 if (bb == NULL) break;
748 if (bb->block_type == kDead) continue;
749 if (bb->block_type == kEntryBlock) {
750 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
751 } else if (bb->block_type == kExitBlock) {
752 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
753 } else if (bb->block_type == kDalvikByteCode) {
754 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
755 bb->start_offset, bb->id);
756 const MIR *mir;
757 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
758 bb->first_mir_insn ? " | " : " ");
759 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
760 int opcode = mir->dalvikInsn.opcode;
761 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700762 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800763 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700764 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800765 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
766 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
767 mir->next ? " | " : " ");
768 }
769 fprintf(file, " }\"];\n\n");
770 } else if (bb->block_type == kExceptionHandling) {
771 char block_name[BLOCK_NAME_LEN];
772
773 GetBlockName(bb, block_name);
774 fprintf(file, " %s [shape=invhouse];\n", block_name);
775 }
776
777 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
778
779 if (bb->taken) {
780 GetBlockName(bb, block_name1);
781 GetBlockName(bb->taken, block_name2);
782 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
783 block_name1, block_name2);
784 }
785 if (bb->fall_through) {
786 GetBlockName(bb, block_name1);
787 GetBlockName(bb->fall_through, block_name2);
788 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
789 }
790
791 if (bb->successor_block_list.block_list_type != kNotUsed) {
792 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
793 bb->start_offset, bb->id,
794 (bb->successor_block_list.block_list_type == kCatch) ?
795 "Mrecord" : "record");
796 GrowableListIterator iterator;
797 GrowableListIteratorInit(&bb->successor_block_list.blocks,
798 &iterator);
799 SuccessorBlockInfo *successor_block_info =
800 reinterpret_cast<SuccessorBlockInfo*>(GrowableListIteratorNext(&iterator));
801
802 int succ_id = 0;
803 while (true) {
804 if (successor_block_info == NULL) break;
805
806 BasicBlock *dest_block = successor_block_info->block;
807 SuccessorBlockInfo *next_successor_block_info =
808 reinterpret_cast<SuccessorBlockInfo*>(GrowableListIteratorNext(&iterator));
809
810 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
811 succ_id++,
812 successor_block_info->key,
813 dest_block->start_offset,
814 (next_successor_block_info != NULL) ? " | " : " ");
815
816 successor_block_info = next_successor_block_info;
817 }
818 fprintf(file, " }\"];\n\n");
819
820 GetBlockName(bb, block_name1);
821 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
822 block_name1, bb->start_offset, bb->id);
823
824 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
825 bb->successor_block_list.block_list_type == kSparseSwitch) {
826
827 GrowableListIteratorInit(&bb->successor_block_list.blocks,
828 &iterator);
829
830 succ_id = 0;
831 while (true) {
832 SuccessorBlockInfo *successor_block_info =
833 reinterpret_cast<SuccessorBlockInfo*>( GrowableListIteratorNext(&iterator));
834 if (successor_block_info == NULL) break;
835
836 BasicBlock *dest_block = successor_block_info->block;
837
838 GetBlockName(dest_block, block_name2);
839 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
840 bb->id, succ_id++, block_name2);
841 }
842 }
843 }
844 fprintf(file, "\n");
845
846 if (cu_->verbose) {
847 /* Display the dominator tree */
848 GetBlockName(bb, block_name1);
849 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
850 block_name1, block_name1);
851 if (bb->i_dom) {
852 GetBlockName(bb->i_dom, block_name2);
853 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
854 }
855 }
856 }
857 fprintf(file, "}\n");
858 fclose(file);
859}
860
buzbee1fd33462013-03-25 13:40:45 -0700861/* Insert an MIR instruction to the end of a basic block */
862void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir)
863{
864 if (bb->first_mir_insn == NULL) {
865 DCHECK(bb->last_mir_insn == NULL);
866 bb->last_mir_insn = bb->first_mir_insn = mir;
867 mir->prev = mir->next = NULL;
868 } else {
869 bb->last_mir_insn->next = mir;
870 mir->prev = bb->last_mir_insn;
871 mir->next = NULL;
872 bb->last_mir_insn = mir;
873 }
874}
875
876/* Insert an MIR instruction to the head of a basic block */
877void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir)
878{
879 if (bb->first_mir_insn == NULL) {
880 DCHECK(bb->last_mir_insn == NULL);
881 bb->last_mir_insn = bb->first_mir_insn = mir;
882 mir->prev = mir->next = NULL;
883 } else {
884 bb->first_mir_insn->prev = mir;
885 mir->next = bb->first_mir_insn;
886 mir->prev = NULL;
887 bb->first_mir_insn = mir;
888 }
889}
890
891/* Insert a MIR instruction after the specified MIR */
892void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir)
893{
894 new_mir->prev = current_mir;
895 new_mir->next = current_mir->next;
896 current_mir->next = new_mir;
897
898 if (new_mir->next) {
899 /* Is not the last MIR in the block */
900 new_mir->next->prev = new_mir;
901 } else {
902 /* Is the last MIR in the block */
903 bb->last_mir_insn = new_mir;
904 }
905}
906
907char* MIRGraph::GetDalvikDisassembly(const MIR* mir)
908{
909 DecodedInstruction insn = mir->dalvikInsn;
910 std::string str;
911 int flags = 0;
912 int opcode = insn.opcode;
913 char* ret;
914 bool nop = false;
915 SSARepresentation* ssa_rep = mir->ssa_rep;
916 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
917 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
918 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
919
920 // Handle special cases.
921 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
922 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
923 str.append(": ");
924 // Recover the original Dex instruction
925 insn = mir->meta.throw_insn->dalvikInsn;
926 ssa_rep = mir->meta.throw_insn->ssa_rep;
927 defs = ssa_rep->num_defs;
928 uses = ssa_rep->num_uses;
929 opcode = insn.opcode;
930 } else if (opcode == kMirOpNop) {
931 str.append("[");
932 insn.opcode = mir->meta.original_opcode;
933 opcode = mir->meta.original_opcode;
934 nop = true;
935 }
936
937 if (opcode >= kMirOpFirst) {
938 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
939 } else {
940 dalvik_format = Instruction::FormatOf(insn.opcode);
941 flags = Instruction::FlagsOf(insn.opcode);
942 str.append(Instruction::Name(insn.opcode));
943 }
944
945 if (opcode == kMirOpPhi) {
946 int* incoming = reinterpret_cast<int*>(insn.vB);
947 str.append(StringPrintf(" %s = (%s",
948 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
949 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
950 str.append(StringPrintf(":%d",incoming[0]));
951 int i;
952 for (i = 1; i < uses; i++) {
953 str.append(StringPrintf(", %s:%d",
954 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
955 incoming[i]));
956 }
957 str.append(")");
958 } else if ((flags & Instruction::kBranch) != 0) {
959 // For branches, decode the instructions to print out the branch targets.
960 int offset = 0;
961 switch (dalvik_format) {
962 case Instruction::k21t:
963 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
964 offset = insn.vB;
965 break;
966 case Instruction::k22t:
967 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
968 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
969 offset = insn.vC;
970 break;
971 case Instruction::k10t:
972 case Instruction::k20t:
973 case Instruction::k30t:
974 offset = insn.vA;
975 break;
976 default:
977 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
978 }
979 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
980 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
981 } else {
982 // For invokes-style formats, treat wide regs as a pair of singles
983 bool show_singles = ((dalvik_format == Instruction::k35c) ||
984 (dalvik_format == Instruction::k3rc));
985 if (defs != 0) {
986 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
987 if (uses != 0) {
988 str.append(", ");
989 }
990 }
991 for (int i = 0; i < uses; i++) {
992 str.append(
993 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
994 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
995 // For the listing, skip the high sreg.
996 i++;
997 }
998 if (i != (uses -1)) {
999 str.append(",");
1000 }
1001 }
1002 switch (dalvik_format) {
1003 case Instruction::k11n: // Add one immediate from vB
1004 case Instruction::k21s:
1005 case Instruction::k31i:
1006 case Instruction::k21h:
1007 str.append(StringPrintf(", #%d", insn.vB));
1008 break;
1009 case Instruction::k51l: // Add one wide immediate
1010 str.append(StringPrintf(", #%lld", insn.vB_wide));
1011 break;
1012 case Instruction::k21c: // One register, one string/type/method index
1013 case Instruction::k31c:
1014 str.append(StringPrintf(", index #%d", insn.vB));
1015 break;
1016 case Instruction::k22c: // Two registers, one string/type/method index
1017 str.append(StringPrintf(", index #%d", insn.vC));
1018 break;
1019 case Instruction::k22s: // Add one immediate from vC
1020 case Instruction::k22b:
1021 str.append(StringPrintf(", #%d", insn.vC));
1022 break;
1023 default:
1024 ; // Nothing left to print
1025 }
1026 }
1027 if (nop) {
1028 str.append("]--optimized away");
1029 }
1030 int length = str.length() + 1;
1031 ret = static_cast<char*>(NewMem(cu_, length, false, kAllocDFInfo));
1032 strncpy(ret, str.c_str(), length);
1033 return ret;
1034}
1035
1036/* Turn method name into a legal Linux file name */
1037void MIRGraph::ReplaceSpecialChars(std::string& str)
1038{
1039 static const struct { const char before; const char after; } match[] =
1040 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
1041 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
1042 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1043 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1044 }
1045}
1046
1047std::string MIRGraph::GetSSAName(int ssa_reg)
1048{
1049 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1050}
1051
1052// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
1053std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only)
1054{
1055 if (reg_location_ == NULL) {
1056 // Pre-SSA - just use the standard name
1057 return GetSSAName(ssa_reg);
1058 }
1059 if (IsConst(reg_location_[ssa_reg])) {
1060 if (!singles_only && reg_location_[ssa_reg].wide) {
1061 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1062 ConstantValueWide(reg_location_[ssa_reg]));
1063 } else {
1064 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg),GetSSASubscript(ssa_reg),
1065 ConstantValue(reg_location_[ssa_reg]));
1066 }
1067 } else {
1068 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1069 }
1070}
1071
1072void MIRGraph::GetBlockName(BasicBlock* bb, char* name)
1073{
1074 switch (bb->block_type) {
1075 case kEntryBlock:
1076 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1077 break;
1078 case kExitBlock:
1079 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1080 break;
1081 case kDalvikByteCode:
1082 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1083 break;
1084 case kExceptionHandling:
1085 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1086 bb->id);
1087 break;
1088 default:
1089 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1090 break;
1091 }
1092}
1093
1094const char* MIRGraph::GetShortyFromTargetIdx(int target_idx)
1095{
1096 // FIXME: use current code unit for inline support.
1097 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1098 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1099}
1100
1101/* Debug Utility - dump a compilation unit */
1102void MIRGraph::DumpMIRGraph()
1103{
1104 BasicBlock* bb;
1105 const char* block_type_names[] = {
1106 "Entry Block",
1107 "Code Block",
1108 "Exit Block",
1109 "Exception Handling",
1110 "Catch Block"
1111 };
1112
1113 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1114 LOG(INFO) << cu_->insns << " insns";
1115 LOG(INFO) << GetNumBlocks() << " blocks in total";
1116 GrowableListIterator iterator = GetBasicBlockIterator();
1117
1118 while (true) {
1119 bb = reinterpret_cast<BasicBlock*>(GrowableListIteratorNext(&iterator));
1120 if (bb == NULL) break;
1121 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1122 bb->id,
1123 block_type_names[bb->block_type],
1124 bb->start_offset,
1125 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1126 bb->last_mir_insn ? "" : " empty");
1127 if (bb->taken) {
1128 LOG(INFO) << " Taken branch: block " << bb->taken->id
1129 << "(0x" << std::hex << bb->taken->start_offset << ")";
1130 }
1131 if (bb->fall_through) {
1132 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1133 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1134 }
1135 }
1136}
1137
1138/*
1139 * Build an array of location records for the incoming arguments.
1140 * Note: one location record per word of arguments, with dummy
1141 * high-word loc for wide arguments. Also pull up any following
1142 * MOVE_RESULT and incorporate it into the invoke.
1143 */
1144CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
1145 bool is_range)
1146{
1147 CallInfo* info = static_cast<CallInfo*>(NewMem(cu_, sizeof(CallInfo), true, kAllocMisc));
1148 MIR* move_result_mir = FindMoveResult(bb, mir);
1149 if (move_result_mir == NULL) {
1150 info->result.location = kLocInvalid;
1151 } else {
1152 info->result = GetRawDest(move_result_mir);
1153 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1154 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1155 }
1156 info->num_arg_words = mir->ssa_rep->num_uses;
1157 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
1158 (NewMem(cu_, sizeof(RegLocation) * info->num_arg_words, false, kAllocMisc));
1159 for (int i = 0; i < info->num_arg_words; i++) {
1160 info->args[i] = GetRawSrc(mir, i);
1161 }
1162 info->opt_flags = mir->optimization_flags;
1163 info->type = type;
1164 info->is_range = is_range;
1165 info->index = mir->dalvikInsn.vB;
1166 info->offset = mir->offset;
1167 return info;
1168}
1169
1170
1171
buzbee311ca162013-02-28 15:56:43 -08001172} // namespace art