blob: 4fbace26e722adcfa858f5d865c1f7521a44d70c [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
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010026#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000027#include "dex/quick/dex_file_to_method_inliner_map.h"
28#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000029#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070030#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010031#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000032
buzbee311ca162013-02-28 15:56:43 -080033namespace art {
34
35#define MAX_PATTERN_LEN 5
36
buzbee1fd33462013-03-25 13:40:45 -070037const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
38 "Phi",
39 "Copy",
40 "FusedCmplFloat",
41 "FusedCmpgFloat",
42 "FusedCmplDouble",
43 "FusedCmpgDouble",
44 "FusedCmpLong",
45 "Nop",
46 "OpNullCheck",
47 "OpRangeCheck",
48 "OpDivZeroCheck",
49 "Check1",
50 "Check2",
51 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040052 "ConstVector",
53 "MoveVector",
54 "PackedMultiply",
55 "PackedAddition",
56 "PackedSubtract",
57 "PackedShiftLeft",
58 "PackedSignedShiftRight",
59 "PackedUnsignedShiftRight",
60 "PackedAnd",
61 "PackedOr",
62 "PackedXor",
63 "PackedAddReduce",
64 "PackedReduce",
65 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070066 "ReserveVectorRegisters",
67 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070068};
69
buzbee862a7602013-04-05 10:58:54 -070070MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070071 : reg_location_(NULL),
72 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080073 ssa_base_vregs_(NULL),
74 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080075 vreg_to_ssa_map_(NULL),
76 ssa_last_defs_(NULL),
77 is_constant_v_(NULL),
78 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070079 use_counts_(arena, 256, kGrowableArrayMisc),
80 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080081 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070082 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070083 dfs_order_(NULL),
84 dfs_post_order_(NULL),
85 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070086 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080087 i_dom_list_(NULL),
88 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000089 temp_scoped_alloc_(),
90 temp_insn_data_(nullptr),
91 temp_bit_vector_size_(0u),
92 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +010093 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -070094 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080095 try_block_addr_(NULL),
96 entry_block_(NULL),
97 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080098 num_blocks_(0),
99 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700100 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -0800101 current_method_(kInvalidEntry),
102 current_offset_(kInvalidEntry),
103 def_count_(0),
104 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700105 num_ssa_regs_(0),
106 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700107 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
108 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700109 arena_(arena),
110 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800111 forward_branches_(0),
112 compiler_temps_(arena, 6, kGrowableArrayMisc),
113 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800114 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000115 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000116 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000117 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000118 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700119 method_lowering_infos_(arena, 0u),
120 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700121 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800122 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
123 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800124}
125
Ian Rogers6282dc12013-04-18 15:54:02 -0700126MIRGraph::~MIRGraph() {
127 STLDeleteElements(&m_units_);
128}
129
buzbee311ca162013-02-28 15:56:43 -0800130/*
131 * Parse an instruction, return the length of the instruction
132 */
Ian Rogers29a26482014-05-02 15:27:29 -0700133int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
134 const Instruction* inst = Instruction::At(code_ptr);
135 decoded_instruction->opcode = inst->Opcode();
136 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
137 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
138 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
139 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
140 if (inst->HasVarArgs()) {
141 inst->GetVarArgs(decoded_instruction->arg);
142 }
143 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800144}
145
146
147/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700148BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700149 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700150 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800151 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700152 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800153 while (insn) {
154 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700155 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800156 insn = insn->next;
157 }
158 if (insn == NULL) {
159 LOG(FATAL) << "Break split failed";
160 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700161 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700162 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800163
164 bottom_block->start_offset = code_offset;
165 bottom_block->first_mir_insn = insn;
166 bottom_block->last_mir_insn = orig_block->last_mir_insn;
167
168 /* If this block was terminated by a return, the flag needs to go with the bottom block */
169 bottom_block->terminated_by_return = orig_block->terminated_by_return;
170 orig_block->terminated_by_return = false;
171
buzbee311ca162013-02-28 15:56:43 -0800172 /* Handle the taken path */
173 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700174 if (bottom_block->taken != NullBasicBlockId) {
175 orig_block->taken = NullBasicBlockId;
176 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
177 bb_taken->predecessors->Delete(orig_block->id);
178 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800179 }
180
181 /* Handle the fallthrough path */
182 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700183 orig_block->fall_through = bottom_block->id;
184 bottom_block->predecessors->Insert(orig_block->id);
185 if (bottom_block->fall_through != NullBasicBlockId) {
186 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
187 bb_fall_through->predecessors->Delete(orig_block->id);
188 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800189 }
190
191 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700192 if (orig_block->successor_block_list_type != kNotUsed) {
193 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
194 bottom_block->successor_blocks = orig_block->successor_blocks;
195 orig_block->successor_block_list_type = kNotUsed;
196 orig_block->successor_blocks = NULL;
197 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800198 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700199 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800200 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700201 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700202 bb->predecessors->Delete(orig_block->id);
203 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800204 }
205 }
206
buzbee0d829482013-10-11 15:24:55 -0700207 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700208 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800209
buzbee311ca162013-02-28 15:56:43 -0800210 /*
211 * Update the immediate predecessor block pointer so that outgoing edges
212 * can be applied to the proper block.
213 */
214 if (immed_pred_block_p) {
215 DCHECK_EQ(*immed_pred_block_p, orig_block);
216 *immed_pred_block_p = bottom_block;
217 }
buzbeeb48819d2013-09-14 16:15:25 -0700218
219 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000220 DCHECK(insn != nullptr);
221 DCHECK(insn != orig_block->first_mir_insn);
222 DCHECK(insn == bottom_block->first_mir_insn);
223 DCHECK_EQ(insn->offset, bottom_block->start_offset);
224 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
225 !IsPseudoMirOp(insn->dalvikInsn.opcode));
226 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
227 MIR* p = insn;
228 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
229 while (p != bottom_block->last_mir_insn) {
230 p = p->next;
231 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700232 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700233 int opcode = p->dalvikInsn.opcode;
234 /*
235 * Some messiness here to ensure that we only enter real opcodes and only the
236 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000237 * CHECK and work portions. Since the 2nd half of a split operation is always
238 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700239 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000240 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
241 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700242 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
243 }
buzbeeb48819d2013-09-14 16:15:25 -0700244 }
245
buzbee311ca162013-02-28 15:56:43 -0800246 return bottom_block;
247}
248
249/*
250 * Given a code offset, find out the block that starts with it. If the offset
251 * is in the middle of an existing block, split it into two. If immed_pred_block_p
252 * is not non-null and is the block being split, update *immed_pred_block_p to
253 * point to the bottom block so that outgoing edges can be set up properly
254 * (by the caller)
255 * Utilizes a map for fast lookup of the typical cases.
256 */
buzbee0d829482013-10-11 15:24:55 -0700257BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700258 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700259 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800260 return NULL;
261 }
buzbeeb48819d2013-09-14 16:15:25 -0700262
263 int block_id = dex_pc_to_block_map_.Get(code_offset);
264 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
265
266 if ((bb != NULL) && (bb->start_offset == code_offset)) {
267 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700268 return bb;
269 }
buzbee311ca162013-02-28 15:56:43 -0800270
buzbeeb48819d2013-09-14 16:15:25 -0700271 // No direct hit.
272 if (!create) {
273 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800274 }
275
buzbeeb48819d2013-09-14 16:15:25 -0700276 if (bb != NULL) {
277 // The target exists somewhere in an existing block.
278 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
279 }
280
281 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700282 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
283 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800284 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700285 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800286 return bb;
287}
288
buzbeeb48819d2013-09-14 16:15:25 -0700289
buzbee311ca162013-02-28 15:56:43 -0800290/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700291void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800292 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700293 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800294
295 if (tries_size == 0) {
296 return;
297 }
298
299 for (int i = 0; i < tries_size; i++) {
300 const DexFile::TryItem* pTry =
301 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700302 DexOffset start_offset = pTry->start_addr_;
303 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800304 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700305 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800306 }
307 }
308
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700309 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800310 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
311 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
312 for (uint32_t idx = 0; idx < handlers_size; idx++) {
313 CatchHandlerIterator iterator(handlers_ptr);
314 for (; iterator.HasNext(); iterator.Next()) {
315 uint32_t address = iterator.GetHandlerAddress();
316 FindBlock(address, false /* split */, true /*create*/,
317 /* immed_pred_block_p */ NULL);
318 }
319 handlers_ptr = iterator.EndDataPointer();
320 }
321}
322
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100323bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
324 NarrowDexOffset catch_offset) {
325 // Catches for monitor-exit during stack unwinding have the pattern
326 // move-exception (move)* (goto)? monitor-exit throw
327 // In the currently generated dex bytecode we see these catching a bytecode range including
328 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
329 // it's the case for a given monitor-exit and catch block so that we can ignore it.
330 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
331 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
332 // even though a throwing monitor-exit certainly indicates a bytecode error.)
333 const Instruction* monitor_exit = Instruction::At(cu_->code_item->insns_ + monitor_exit_offset);
334 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
335 int monitor_reg = monitor_exit->VRegA_11x();
336 const Instruction* check_insn = Instruction::At(cu_->code_item->insns_ + catch_offset);
337 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
338 if (check_insn->VRegA_11x() == monitor_reg) {
339 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
340 return false;
341 }
342 check_insn = check_insn->Next();
343 while (true) {
344 int dest = -1;
345 bool wide = false;
346 switch (check_insn->Opcode()) {
347 case Instruction::MOVE_WIDE:
348 wide = true;
349 // Intentional fall-through.
350 case Instruction::MOVE_OBJECT:
351 case Instruction::MOVE:
352 dest = check_insn->VRegA_12x();
353 break;
354
355 case Instruction::MOVE_WIDE_FROM16:
356 wide = true;
357 // Intentional fall-through.
358 case Instruction::MOVE_OBJECT_FROM16:
359 case Instruction::MOVE_FROM16:
360 dest = check_insn->VRegA_22x();
361 break;
362
363 case Instruction::MOVE_WIDE_16:
364 wide = true;
365 // Intentional fall-through.
366 case Instruction::MOVE_OBJECT_16:
367 case Instruction::MOVE_16:
368 dest = check_insn->VRegA_32x();
369 break;
370
371 case Instruction::GOTO:
372 case Instruction::GOTO_16:
373 case Instruction::GOTO_32:
374 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
375 // Intentional fall-through.
376 default:
377 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
378 check_insn->VRegA_11x() == monitor_reg;
379 }
380
381 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
382 return false;
383 }
384
385 check_insn = check_insn->Next();
386 }
387}
388
buzbee311ca162013-02-28 15:56:43 -0800389/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700390BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
391 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700392 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700393 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800394 switch (insn->dalvikInsn.opcode) {
395 case Instruction::GOTO:
396 case Instruction::GOTO_16:
397 case Instruction::GOTO_32:
398 target += insn->dalvikInsn.vA;
399 break;
400 case Instruction::IF_EQ:
401 case Instruction::IF_NE:
402 case Instruction::IF_LT:
403 case Instruction::IF_GE:
404 case Instruction::IF_GT:
405 case Instruction::IF_LE:
406 cur_block->conditional_branch = true;
407 target += insn->dalvikInsn.vC;
408 break;
409 case Instruction::IF_EQZ:
410 case Instruction::IF_NEZ:
411 case Instruction::IF_LTZ:
412 case Instruction::IF_GEZ:
413 case Instruction::IF_GTZ:
414 case Instruction::IF_LEZ:
415 cur_block->conditional_branch = true;
416 target += insn->dalvikInsn.vB;
417 break;
418 default:
419 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
420 }
buzbeeb48819d2013-09-14 16:15:25 -0700421 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700422 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800423 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700424 cur_block->taken = taken_block->id;
425 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800426
427 /* Always terminate the current block for conditional branches */
428 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700429 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800430 /*
431 * If the method is processed
432 * in sequential order from the
433 * beginning, we don't need to
434 * specify split for continue
435 * blocks. However, this
436 * routine can be called by
437 * compileLoop, which starts
438 * parsing the method from an
439 * arbitrary address in the
440 * method body.
441 */
442 true,
443 /* create */
444 true,
445 /* immed_pred_block_p */
446 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700447 cur_block->fall_through = fallthrough_block->id;
448 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800449 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700450 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800451 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800452 }
453 return cur_block;
454}
455
456/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800457BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
458 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800459 const uint16_t* switch_data =
460 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
461 int size;
462 const int* keyTable;
463 const int* target_table;
464 int i;
465 int first_key;
466
467 /*
468 * Packed switch data format:
469 * ushort ident = 0x0100 magic value
470 * ushort size number of entries in the table
471 * int first_key first (and lowest) switch case value
472 * int targets[size] branch targets, relative to switch opcode
473 *
474 * Total size is (4+size*2) 16-bit code units.
475 */
476 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
477 DCHECK_EQ(static_cast<int>(switch_data[0]),
478 static_cast<int>(Instruction::kPackedSwitchSignature));
479 size = switch_data[1];
480 first_key = switch_data[2] | (switch_data[3] << 16);
481 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700482 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800483 /*
484 * Sparse switch data format:
485 * ushort ident = 0x0200 magic value
486 * ushort size number of entries in the table; > 0
487 * int keys[size] keys, sorted low-to-high; 32-bit aligned
488 * int targets[size] branch targets, relative to switch opcode
489 *
490 * Total size is (2+size*4) 16-bit code units.
491 */
492 } else {
493 DCHECK_EQ(static_cast<int>(switch_data[0]),
494 static_cast<int>(Instruction::kSparseSwitchSignature));
495 size = switch_data[1];
496 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
497 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700498 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800499 }
500
buzbee0d829482013-10-11 15:24:55 -0700501 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800502 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700503 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800504 }
buzbee0d829482013-10-11 15:24:55 -0700505 cur_block->successor_block_list_type =
506 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
507 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700508 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800509
510 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700511 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800512 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700513 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700514 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000515 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700516 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800517 successor_block_info->key =
518 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
519 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700520 cur_block->successor_blocks->Insert(successor_block_info);
521 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800522 }
523
524 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700525 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
526 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700527 cur_block->fall_through = fallthrough_block->id;
528 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800529 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800530}
531
532/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700533BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
534 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700535 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700536 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800537 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
538 bool build_all_edges =
539 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800540
541 /* In try block */
542 if (in_try_block) {
543 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
544
buzbee0d829482013-10-11 15:24:55 -0700545 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800546 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
547 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700548 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800549 }
550
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700551 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700552 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800553 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100554 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
555 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
556 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
557 continue;
558 }
559 if (cur_block->successor_block_list_type == kNotUsed) {
560 cur_block->successor_block_list_type = kCatch;
561 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
562 arena_, 2, kGrowableArraySuccessorBlocks);
563 }
buzbee311ca162013-02-28 15:56:43 -0800564 catch_block->catch_entry = true;
565 if (kIsDebugBuild) {
566 catches_.insert(catch_block->start_offset);
567 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700568 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000569 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700570 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800571 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700572 cur_block->successor_blocks->Insert(successor_block_info);
573 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800574 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100575 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
576 }
577 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700578 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700579 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700580 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800581 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700582 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800583 }
584
buzbee17189ac2013-11-08 11:07:02 -0800585 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800586 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700587 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700588 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800589 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
590 /* immed_pred_block_p */ NULL);
591 }
592 if (!in_try_block) {
593 // Don't split a THROW that can't rethrow - we're done.
594 return cur_block;
595 }
596 }
597
buzbee17189ac2013-11-08 11:07:02 -0800598 if (!build_all_edges) {
599 /*
600 * Even though there is an exception edge here, control cannot return to this
601 * method. Thus, for the purposes of dataflow analysis and optimization, we can
602 * ignore the edge. Doing this reduces compile time, and increases the scope
603 * of the basic-block level optimization pass.
604 */
605 return cur_block;
606 }
607
buzbee311ca162013-02-28 15:56:43 -0800608 /*
609 * Split the potentially-throwing instruction into two parts.
610 * The first half will be a pseudo-op that captures the exception
611 * edges and terminates the basic block. It always falls through.
612 * Then, create a new basic block that begins with the throwing instruction
613 * (minus exceptions). Note: this new basic block must NOT be entered into
614 * the block_map. If the potentially-throwing instruction is the target of a
615 * future branch, we need to find the check psuedo half. The new
616 * basic block containing the work portion of the instruction should
617 * only be entered via fallthrough from the block containing the
618 * pseudo exception edge MIR. Note also that this new block is
619 * not automatically terminated after the work portion, and may
620 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700621 *
622 * Note also that the dex_pc_to_block_map_ entry for the potentially
623 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800624 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700625 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700626 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800627 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700628 cur_block->fall_through = new_block->id;
629 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700630 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800631 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700632 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700633 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800634 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700635 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800636 return new_block;
637}
638
639/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
640void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700641 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700642 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800643 current_code_item_ = code_item;
644 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
645 current_method_ = m_units_.size();
646 current_offset_ = 0;
647 // TODO: will need to snapshot stack image and use that as the mir context identification.
648 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000649 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
650 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800651 const uint16_t* code_ptr = current_code_item_->insns_;
652 const uint16_t* code_end =
653 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
654
655 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700656 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700657 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700658 dex_pc_to_block_map_.SetSize(dex_pc_to_block_map_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700659
buzbee311ca162013-02-28 15:56:43 -0800660 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700661 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
662 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800663
664 // If this is the first method, set up default entry and exit blocks.
665 if (current_method_ == 0) {
666 DCHECK(entry_block_ == NULL);
667 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700668 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700669 // Use id 0 to represent a null block.
670 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
671 DCHECK_EQ(null_block->id, NullBasicBlockId);
672 null_block->hidden = true;
673 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700674 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700675 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700676 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700677 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800678 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
679 cu_->dex_file = &dex_file;
680 cu_->class_def_idx = class_def_idx;
681 cu_->method_idx = method_idx;
682 cu_->access_flags = access_flags;
683 cu_->invoke_type = invoke_type;
684 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
685 cu_->num_ins = current_code_item_->ins_size_;
686 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
687 cu_->num_outs = current_code_item_->outs_size_;
688 cu_->num_dalvik_registers = current_code_item_->registers_size_;
689 cu_->insns = current_code_item_->insns_;
690 cu_->code_item = current_code_item_;
691 } else {
692 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
693 /*
694 * Will need to manage storage for ins & outs, push prevous state and update
695 * insert point.
696 */
697 }
698
699 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700700 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700701 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800702 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700703 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700704 // TODO: for inlining support, insert at the insert point rather than entry block.
705 entry_block_->fall_through = cur_block->id;
706 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800707
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000708 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800709 ProcessTryCatchBlocks();
710
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000711 uint64_t merged_df_flags = 0u;
712
buzbee311ca162013-02-28 15:56:43 -0800713 /* Parse all instructions and put them into containing basic blocks */
714 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700715 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800716 insn->offset = current_offset_;
717 insn->m_unit_index = current_method_;
718 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800719 Instruction::Code opcode = insn->dalvikInsn.opcode;
720 if (opcode_count_ != NULL) {
721 opcode_count_[static_cast<int>(opcode)]++;
722 }
723
buzbee311ca162013-02-28 15:56:43 -0800724 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800725 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800726
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700727 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000728 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800729
730 if (df_flags & DF_HAS_DEFS) {
731 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
732 }
733
buzbee1da1e2f2013-11-15 13:37:01 -0800734 if (df_flags & DF_LVN) {
735 cur_block->use_lvn = true; // Run local value numbering on this basic block.
736 }
737
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700738 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700739 if (opcode == Instruction::NOP) {
740 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
741 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
742 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
743 uint16_t following_raw_instruction = code_ptr[1];
744 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
745 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
746 (following_raw_instruction == Instruction::kArrayDataSignature)) {
747 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
748 }
749 }
750 if (width == 1) {
751 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700752 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700753 } else {
buzbee0d829482013-10-11 15:24:55 -0700754 DCHECK(cur_block->fall_through == NullBasicBlockId);
755 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700756 // Unreachable instruction, mark for no continuation.
757 flags &= ~Instruction::kContinue;
758 }
759 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700760 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700761 }
762
buzbeeb48819d2013-09-14 16:15:25 -0700763 // Associate the starting dex_pc for this opcode with its containing basic block.
764 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
765
buzbee27247762013-07-28 12:03:58 -0700766 code_ptr += width;
767
buzbee311ca162013-02-28 15:56:43 -0800768 if (flags & Instruction::kBranch) {
769 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
770 width, flags, code_ptr, code_end);
771 } else if (flags & Instruction::kReturn) {
772 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700773 cur_block->fall_through = exit_block_->id;
774 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800775 /*
776 * Terminate the current block if there are instructions
777 * afterwards.
778 */
779 if (code_ptr < code_end) {
780 /*
781 * Create a fallthrough block for real instructions
782 * (incl. NOP).
783 */
buzbee27247762013-07-28 12:03:58 -0700784 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
785 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800786 }
787 } else if (flags & Instruction::kThrow) {
788 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
789 code_ptr, code_end);
790 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800791 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800792 }
buzbeeb1f1d642014-02-27 12:55:32 -0800793 if (verify_flags & Instruction::kVerifyVarArgRange) {
794 /*
795 * The Quick backend's runtime model includes a gap between a method's
796 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
797 * which spans the gap is somewhat complicated, and should not happen
798 * in normal usage of dx. Punt to the interpreter.
799 */
800 int first_reg_in_range = insn->dalvikInsn.vC;
801 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
802 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
803 punt_to_interpreter_ = true;
804 }
805 }
buzbee311ca162013-02-28 15:56:43 -0800806 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700807 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800808 false, /* immed_pred_block_p */ NULL);
809 if (next_block) {
810 /*
811 * The next instruction could be the target of a previously parsed
812 * forward branch so a block is already created. If the current
813 * instruction is not an unconditional branch, connect them through
814 * the fall-through link.
815 */
buzbee0d829482013-10-11 15:24:55 -0700816 DCHECK(cur_block->fall_through == NullBasicBlockId ||
817 GetBasicBlock(cur_block->fall_through) == next_block ||
818 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800819
buzbee0d829482013-10-11 15:24:55 -0700820 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
821 cur_block->fall_through = next_block->id;
822 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800823 }
824 cur_block = next_block;
825 }
826 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000827 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000828
buzbee311ca162013-02-28 15:56:43 -0800829 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
830 DumpCFG("/sdcard/1_post_parse_cfg/", true);
831 }
832
833 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700834 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800835 }
836}
837
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700838void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800839 DCHECK(opcode_count_ != NULL);
840 LOG(INFO) << "Opcode Count";
841 for (int i = 0; i < kNumPackedOpcodes; i++) {
842 if (opcode_count_[i] != 0) {
843 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
844 << " " << opcode_count_[i];
845 }
846 }
847}
848
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700849uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
850 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
851 return oat_data_flow_attributes_[opcode];
852}
853
854uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
855 DCHECK(mir != nullptr);
856 Instruction::Code opcode = mir->dalvikInsn.opcode;
857 return GetDataFlowAttributes(opcode);
858}
859
buzbee311ca162013-02-28 15:56:43 -0800860// TODO: use a configurable base prefix, and adjust callers to supply pass name.
861/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800862void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800863 FILE* file;
864 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
865 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800866 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
867 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
868 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800869 file = fopen(fname.c_str(), "w");
870 if (file == NULL) {
871 return;
872 }
873 fprintf(file, "digraph G {\n");
874
875 fprintf(file, " rankdir=TB\n");
876
877 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
878 int idx;
879
880 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700881 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700882 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700883 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800884 if (bb->block_type == kDead) continue;
885 if (bb->block_type == kEntryBlock) {
886 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
887 } else if (bb->block_type == kExitBlock) {
888 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
889 } else if (bb->block_type == kDalvikByteCode) {
890 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
891 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700892 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800893 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
894 bb->first_mir_insn ? " | " : " ");
895 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
896 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400897 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
898 if (opcode == kMirOpConstVector) {
899 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
900 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
901 mir->dalvikInsn.vA,
902 mir->dalvikInsn.vB,
903 mir->dalvikInsn.arg[0],
904 mir->dalvikInsn.arg[1],
905 mir->dalvikInsn.arg[2],
906 mir->dalvikInsn.arg[3],
907 mir->next ? " | " : " ");
908 } else {
909 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
910 extended_mir_op_names_[opcode - kMirOpFirst],
911 mir->dalvikInsn.vA,
912 mir->dalvikInsn.vB,
913 mir->dalvikInsn.vC,
914 mir->next ? " | " : " ");
915 }
916 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700917 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400918 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700919 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400920 extended_mir_op_names_[opcode - kMirOpFirst],
921 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
922 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700923 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400924 mir->next ? " | " : " ");
925 }
buzbee311ca162013-02-28 15:56:43 -0800926 }
927 fprintf(file, " }\"];\n\n");
928 } else if (bb->block_type == kExceptionHandling) {
929 char block_name[BLOCK_NAME_LEN];
930
931 GetBlockName(bb, block_name);
932 fprintf(file, " %s [shape=invhouse];\n", block_name);
933 }
934
935 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
936
buzbee0d829482013-10-11 15:24:55 -0700937 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800938 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700939 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800940 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
941 block_name1, block_name2);
942 }
buzbee0d829482013-10-11 15:24:55 -0700943 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800944 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700945 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800946 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
947 }
948
buzbee0d829482013-10-11 15:24:55 -0700949 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800950 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
951 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700952 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
953 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700954 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800955
956 int succ_id = 0;
957 while (true) {
958 if (successor_block_info == NULL) break;
959
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700960 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700961 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800962
963 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
964 succ_id++,
965 successor_block_info->key,
966 dest_block->start_offset,
967 (next_successor_block_info != NULL) ? " | " : " ");
968
969 successor_block_info = next_successor_block_info;
970 }
971 fprintf(file, " }\"];\n\n");
972
973 GetBlockName(bb, block_name1);
974 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
975 block_name1, bb->start_offset, bb->id);
976
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700977 // Link the successor pseudo-block with all of its potential targets.
978 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800979
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700980 succ_id = 0;
981 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700982 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800984
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800986
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700987 GetBlockName(dest_block, block_name2);
988 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
989 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800990 }
991 }
992 fprintf(file, "\n");
993
994 if (cu_->verbose) {
995 /* Display the dominator tree */
996 GetBlockName(bb, block_name1);
997 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
998 block_name1, block_name1);
999 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001000 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001001 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1002 }
1003 }
1004 }
1005 fprintf(file, "}\n");
1006 fclose(file);
1007}
1008
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001009/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001010void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001011 // Insert it after the last MIR.
1012 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001013}
1014
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001015void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1016 // Insert it after the last MIR.
1017 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1018}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001019
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001020void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1021 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1022 MIR* new_mir = *it;
1023
1024 // Add a copy of each MIR.
1025 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1026 }
buzbee1fd33462013-03-25 13:40:45 -07001027}
1028
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001029/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001030void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001031 InsertMIRListAfter(current_mir, new_mir, new_mir);
1032}
buzbee1fd33462013-03-25 13:40:45 -07001033
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001034void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1035 // If no MIR, we are done.
1036 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1037 return;
buzbee1fd33462013-03-25 13:40:45 -07001038 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001039
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001040 // If insert_after is null, assume BB is empty.
1041 if (insert_after == nullptr) {
1042 first_mir_insn = first_list_mir;
1043 last_mir_insn = last_list_mir;
1044 last_list_mir->next = nullptr;
1045 } else {
1046 MIR* after_list = insert_after->next;
1047 insert_after->next = first_list_mir;
1048 last_list_mir->next = after_list;
1049 if (after_list == nullptr) {
1050 last_mir_insn = last_list_mir;
1051 }
1052 }
1053
1054 // Set this BB to be the basic block of the MIRs.
1055 MIR* last = last_list_mir->next;
1056 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1057 mir->bb = id;
1058 }
1059}
1060
1061/* Insert an MIR instruction to the head of a basic block. */
1062void BasicBlock::PrependMIR(MIR* mir) {
1063 InsertMIRListBefore(first_mir_insn, mir, mir);
1064}
1065
1066void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1067 // Insert it before the first MIR.
1068 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1069}
1070
1071void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1072 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1073 MIR* mir = *it;
1074
1075 InsertMIRListBefore(first_mir_insn, mir, mir);
1076 }
1077}
1078
1079/* Insert a MIR instruction before the specified MIR. */
1080void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1081 // Insert as a single element list.
1082 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001083}
1084
1085MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1086 MIR* current = first_mir_insn;
1087
1088 while (current != nullptr) {
1089 MIR* next = current->next;
1090
1091 if (next == mir) {
1092 return current;
1093 }
1094
1095 current = next;
1096 }
1097
1098 return nullptr;
1099}
1100
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001101void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1102 // If no MIR, we are done.
1103 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1104 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001105 }
1106
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001107 // If insert_before is null, assume BB is empty.
1108 if (insert_before == nullptr) {
1109 first_mir_insn = first_list_mir;
1110 last_mir_insn = last_list_mir;
1111 last_list_mir->next = nullptr;
1112 } else {
1113 if (first_mir_insn == insert_before) {
1114 last_list_mir->next = first_mir_insn;
1115 first_mir_insn = first_list_mir;
1116 } else {
1117 // Find the preceding MIR.
1118 MIR* before_list = FindPreviousMIR(insert_before);
1119 DCHECK(before_list != nullptr);
1120 before_list->next = first_list_mir;
1121 last_list_mir->next = insert_before;
1122 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001123 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001124
1125 // Set this BB to be the basic block of the MIRs.
1126 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1127 mir->bb = id;
1128 }
1129}
1130
1131bool BasicBlock::RemoveMIR(MIR* mir) {
1132 // Remove as a single element list.
1133 return RemoveMIRList(mir, mir);
1134}
1135
1136bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1137 if (first_list_mir == nullptr) {
1138 return false;
1139 }
1140
1141 // Try to find the MIR.
1142 MIR* before_list = nullptr;
1143 MIR* after_list = nullptr;
1144
1145 // If we are removing from the beginning of the MIR list.
1146 if (first_mir_insn == first_list_mir) {
1147 before_list = nullptr;
1148 } else {
1149 before_list = FindPreviousMIR(first_list_mir);
1150 if (before_list == nullptr) {
1151 // We did not find the mir.
1152 return false;
1153 }
1154 }
1155
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001156 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001157 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1158 mir->bb = NullBasicBlockId;
1159 }
1160
1161 after_list = last_list_mir->next;
1162
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001163 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001164 if (before_list == nullptr) {
1165 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001166 } else {
1167 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001168 }
1169
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001170 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001171 if (after_list == nullptr) {
1172 last_mir_insn = before_list;
1173 }
1174
1175 return true;
buzbee1fd33462013-03-25 13:40:45 -07001176}
1177
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001178MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001179 MIR* next_mir = nullptr;
1180
1181 if (current != nullptr) {
1182 next_mir = current->next;
1183 }
1184
1185 if (next_mir == nullptr) {
1186 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001187 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1188 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001189 }
1190 }
1191
1192 return next_mir;
1193}
1194
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001195char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001196 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001197 std::string str;
1198 int flags = 0;
1199 int opcode = insn.opcode;
1200 char* ret;
1201 bool nop = false;
1202 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001203 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001204 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1205 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1206
1207 // Handle special cases.
1208 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1209 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1210 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001211 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001212 insn = mir->meta.throw_insn->dalvikInsn;
1213 ssa_rep = mir->meta.throw_insn->ssa_rep;
1214 defs = ssa_rep->num_defs;
1215 uses = ssa_rep->num_uses;
1216 opcode = insn.opcode;
1217 } else if (opcode == kMirOpNop) {
1218 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001219 // Recover original opcode.
1220 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1221 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001222 nop = true;
1223 }
1224
buzbee35ba7f32014-05-31 08:59:01 -07001225 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001226 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1227 } else {
1228 dalvik_format = Instruction::FormatOf(insn.opcode);
1229 flags = Instruction::FlagsOf(insn.opcode);
1230 str.append(Instruction::Name(insn.opcode));
1231 }
1232
1233 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001234 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001235 str.append(StringPrintf(" %s = (%s",
1236 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1237 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001238 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001239 int i;
1240 for (i = 1; i < uses; i++) {
1241 str.append(StringPrintf(", %s:%d",
1242 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1243 incoming[i]));
1244 }
1245 str.append(")");
1246 } else if ((flags & Instruction::kBranch) != 0) {
1247 // For branches, decode the instructions to print out the branch targets.
1248 int offset = 0;
1249 switch (dalvik_format) {
1250 case Instruction::k21t:
1251 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1252 offset = insn.vB;
1253 break;
1254 case Instruction::k22t:
1255 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1256 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1257 offset = insn.vC;
1258 break;
1259 case Instruction::k10t:
1260 case Instruction::k20t:
1261 case Instruction::k30t:
1262 offset = insn.vA;
1263 break;
1264 default:
1265 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1266 }
1267 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1268 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1269 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001270 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001271 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1272 (dalvik_format == Instruction::k3rc));
1273 if (defs != 0) {
1274 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1275 if (uses != 0) {
1276 str.append(", ");
1277 }
1278 }
1279 for (int i = 0; i < uses; i++) {
1280 str.append(
1281 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1282 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1283 // For the listing, skip the high sreg.
1284 i++;
1285 }
1286 if (i != (uses -1)) {
1287 str.append(",");
1288 }
1289 }
1290 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001291 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001292 case Instruction::k21s:
1293 case Instruction::k31i:
1294 case Instruction::k21h:
1295 str.append(StringPrintf(", #%d", insn.vB));
1296 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001297 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001298 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001299 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001300 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001301 case Instruction::k31c:
1302 str.append(StringPrintf(", index #%d", insn.vB));
1303 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001304 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001305 str.append(StringPrintf(", index #%d", insn.vC));
1306 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001307 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001308 case Instruction::k22b:
1309 str.append(StringPrintf(", #%d", insn.vC));
1310 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001311 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001312 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001313 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001314 }
buzbee1fd33462013-03-25 13:40:45 -07001315 }
1316 if (nop) {
1317 str.append("]--optimized away");
1318 }
1319 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001320 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001321 strncpy(ret, str.c_str(), length);
1322 return ret;
1323}
1324
1325/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001326void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001327 static const struct { const char before; const char after; } match[] = {
1328 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1329 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1330 };
buzbee1fd33462013-03-25 13:40:45 -07001331 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1332 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1333 }
1334}
1335
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001336std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001337 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1338 // the arena. We should be smarter and just place straight into the arena, or compute the
1339 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001340 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1341}
1342
1343// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001344std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001345 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001346 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001347 return GetSSAName(ssa_reg);
1348 }
1349 if (IsConst(reg_location_[ssa_reg])) {
1350 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001351 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001352 ConstantValueWide(reg_location_[ssa_reg]));
1353 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001354 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001355 ConstantValue(reg_location_[ssa_reg]));
1356 }
1357 } else {
1358 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1359 }
1360}
1361
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001362void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001363 switch (bb->block_type) {
1364 case kEntryBlock:
1365 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1366 break;
1367 case kExitBlock:
1368 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1369 break;
1370 case kDalvikByteCode:
1371 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1372 break;
1373 case kExceptionHandling:
1374 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1375 bb->id);
1376 break;
1377 default:
1378 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1379 break;
1380 }
1381}
1382
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001383const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001384 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001385 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1386 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1387}
1388
1389/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001390void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001391 BasicBlock* bb;
1392 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001393 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001394 "Entry Block",
1395 "Code Block",
1396 "Exit Block",
1397 "Exception Handling",
1398 "Catch Block"
1399 };
1400
1401 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1402 LOG(INFO) << cu_->insns << " insns";
1403 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001404 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001405
1406 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001407 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001408 if (bb == NULL) break;
1409 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1410 bb->id,
1411 block_type_names[bb->block_type],
1412 bb->start_offset,
1413 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1414 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001415 if (bb->taken != NullBasicBlockId) {
1416 LOG(INFO) << " Taken branch: block " << bb->taken
1417 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001418 }
buzbee0d829482013-10-11 15:24:55 -07001419 if (bb->fall_through != NullBasicBlockId) {
1420 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1421 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001422 }
1423 }
1424}
1425
1426/*
1427 * Build an array of location records for the incoming arguments.
1428 * Note: one location record per word of arguments, with dummy
1429 * high-word loc for wide arguments. Also pull up any following
1430 * MOVE_RESULT and incorporate it into the invoke.
1431 */
1432CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001433 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001434 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001435 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001436 MIR* move_result_mir = FindMoveResult(bb, mir);
1437 if (move_result_mir == NULL) {
1438 info->result.location = kLocInvalid;
1439 } else {
1440 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001441 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1442 }
1443 info->num_arg_words = mir->ssa_rep->num_uses;
1444 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001445 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001446 for (int i = 0; i < info->num_arg_words; i++) {
1447 info->args[i] = GetRawSrc(mir, i);
1448 }
1449 info->opt_flags = mir->optimization_flags;
1450 info->type = type;
1451 info->is_range = is_range;
1452 info->index = mir->dalvikInsn.vB;
1453 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001454 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001455 return info;
1456}
1457
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001458// Allocate a new MIR.
1459MIR* MIRGraph::NewMIR() {
1460 MIR* mir = new (arena_) MIR();
1461 return mir;
1462}
1463
buzbee862a7602013-04-05 10:58:54 -07001464// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001465BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001466 BasicBlock* bb = new (arena_) BasicBlock();
1467
buzbee862a7602013-04-05 10:58:54 -07001468 bb->block_type = block_type;
1469 bb->id = block_id;
1470 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001471 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001472 (block_type == kExitBlock) ? 2048 : 2,
1473 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001474 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001475 block_id_map_.Put(block_id, block_id);
1476 return bb;
1477}
buzbee1fd33462013-03-25 13:40:45 -07001478
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001479void MIRGraph::InitializeConstantPropagation() {
1480 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001481 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001482}
1483
1484void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001485 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001486 int num_ssa_regs = GetNumSSARegs();
1487 use_counts_.Resize(num_ssa_regs + 32);
1488 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001489 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001490 for (int i = 0; i < num_ssa_regs; i++) {
1491 use_counts_.Insert(0);
1492 raw_use_counts_.Insert(0);
1493 }
1494}
1495
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001496void MIRGraph::SSATransformationStart() {
1497 DCHECK(temp_scoped_alloc_.get() == nullptr);
1498 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1499 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1500 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1501 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1502
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001503 // Update the maximum number of reachable blocks.
1504 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001505}
1506
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001507void MIRGraph::SSATransformationEnd() {
1508 // Verify the dataflow information after the pass.
1509 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1510 VerifyDataflow();
1511 }
1512
1513 temp_bit_vector_size_ = 0u;
1514 temp_bit_vector_ = nullptr;
1515 DCHECK(temp_scoped_alloc_.get() != nullptr);
1516 temp_scoped_alloc_.reset();
1517}
1518
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001519void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001520 // Clear the nodes.
1521 ClearAllVisitedFlags();
1522
1523 // Create the topological order if need be.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001524 if (topological_order_ == nullptr) {
1525 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, GetNumBlocks());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001526 }
1527 topological_order_->Reset();
1528
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001529 ScopedArenaAllocator allocator(&cu_->arena_stack);
1530 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1531 ScopedArenaVector<size_t> visited_cnt_values(GetNumBlocks(), 0u, allocator.Adapter());
1532
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001533 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1534 // also fill initial queue.
1535 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1536
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001537 size_t num_blocks = 0u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001538 while (true) {
1539 BasicBlock* bb = iterator.Next();
1540
1541 if (bb == nullptr) {
1542 break;
1543 }
1544
1545 if (bb->hidden == true) {
1546 continue;
1547 }
1548
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001549 num_blocks += 1u;
1550 size_t unvisited_predecessor_count = bb->predecessors->Size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001551
1552 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1553 // To process loops we should not wait for dominators.
1554 while (true) {
1555 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1556
1557 if (pred_bb == nullptr) {
1558 break;
1559 }
1560
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001561 // Skip the backward branch or hidden predecessor.
1562 if (pred_bb->hidden ||
1563 (pred_bb->dominators != nullptr && pred_bb->dominators->IsBitSet(bb->id))) {
1564 unvisited_predecessor_count -= 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001565 }
1566 }
1567
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001568 visited_cnt_values[bb->id] = unvisited_predecessor_count;
1569
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001570 // Add entry block to queue.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001571 if (unvisited_predecessor_count == 0) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001572 q.push(bb);
1573 }
1574 }
1575
Vladimir Markoe8ae8142014-07-08 18:06:45 +01001576 // We can get a cycle where none of the blocks dominates the other. Therefore don't
1577 // stop when the queue is empty, continue until we've processed all the blocks.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001578 AllNodesIterator candidate_iter(this); // For the empty queue case.
1579 while (num_blocks != 0u) {
1580 num_blocks -= 1u;
1581 BasicBlock* bb = nullptr;
1582 if (!q.empty()) {
1583 // Get top.
1584 bb = q.front();
1585 q.pop();
1586 } else {
1587 // Find some block we didn't visit yet that has at least one visited predecessor.
1588 while (bb == nullptr) {
1589 BasicBlock* candidate = candidate_iter.Next();
1590 DCHECK(candidate != nullptr);
1591 if (candidate->visited || candidate->hidden) {
1592 continue;
1593 }
1594 GrowableArray<BasicBlockId>::Iterator iter(candidate->predecessors);
1595 for (BasicBlock* pred_bb = GetBasicBlock(iter.Next()); pred_bb != nullptr;
1596 pred_bb = GetBasicBlock(iter.Next())) {
1597 if (!pred_bb->hidden && pred_bb->visited) {
1598 bb = candidate;
1599 break;
1600 }
1601 }
1602 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001603 }
1604
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001605 DCHECK_EQ(bb->hidden, false);
1606 DCHECK_EQ(bb->visited, false);
1607
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001608 // We've visited all the predecessors. So, we can visit bb.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001609 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001610
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001611 // Now add the basic block.
1612 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001613
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001614 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1615 ChildBlockIterator succIter(bb, this);
1616 BasicBlock* successor = succIter.Next();
1617 for ( ; successor != nullptr; successor = succIter.Next()) {
1618 if (successor->visited || successor->hidden) {
1619 continue;
1620 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001621
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001622 // one more predecessor was visited.
1623 DCHECK_NE(visited_cnt_values[successor->id], 0u);
1624 visited_cnt_values[successor->id] -= 1u;
1625 if (visited_cnt_values[successor->id] == 0u) {
1626 q.push(successor);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001627 }
1628 }
1629 }
1630}
1631
1632bool BasicBlock::IsExceptionBlock() const {
1633 if (block_type == kExceptionHandling) {
1634 return true;
1635 }
1636 return false;
1637}
1638
Wei Jin04f4d8a2014-05-29 18:04:29 -07001639bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1640 BasicBlock* target = GetBasicBlock(target_id);
1641
1642 if (source == nullptr || target == nullptr)
1643 return false;
1644
1645 int idx;
1646 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1647 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1648 if (bb == source)
1649 return true; // The block has been inserted by a suspend check before.
1650 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1651 return true;
1652 }
1653
1654 return false;
1655}
1656
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001657ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1658 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1659 visited_taken_(false), have_successors_(false) {
1660 // Check if we actually do have successors.
1661 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1662 have_successors_ = true;
1663 successor_iter_.Reset(basic_block_->successor_blocks);
1664 }
1665}
1666
1667BasicBlock* ChildBlockIterator::Next() {
1668 // We check if we have a basic block. If we don't we cannot get next child.
1669 if (basic_block_ == nullptr) {
1670 return nullptr;
1671 }
1672
1673 // If we haven't visited fallthrough, return that.
1674 if (visited_fallthrough_ == false) {
1675 visited_fallthrough_ = true;
1676
1677 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1678 if (result != nullptr) {
1679 return result;
1680 }
1681 }
1682
1683 // If we haven't visited taken, return that.
1684 if (visited_taken_ == false) {
1685 visited_taken_ = true;
1686
1687 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1688 if (result != nullptr) {
1689 return result;
1690 }
1691 }
1692
1693 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1694 if (have_successors_ == true) {
1695 // Get information about next successor block.
1696 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1697
1698 // If we don't have anymore successors, return nullptr.
1699 if (successor_block_info != nullptr) {
1700 return mir_graph_->GetBasicBlock(successor_block_info->block);
1701 }
1702 }
1703
1704 // We do not have anything.
1705 return nullptr;
1706}
1707
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001708BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1709 MIRGraph* mir_graph = c_unit->mir_graph.get();
1710 return Copy(mir_graph);
1711}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001712
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001713BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1714 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001715
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001716 // We don't do a memcpy style copy here because it would lead to a lot of things
1717 // to clean up. Let us do it by hand instead.
1718 // Copy in taken and fallthrough.
1719 result_bb->fall_through = fall_through;
1720 result_bb->taken = taken;
1721
1722 // Copy successor links if needed.
1723 ArenaAllocator* arena = mir_graph->GetArena();
1724
1725 result_bb->successor_block_list_type = successor_block_list_type;
1726 if (result_bb->successor_block_list_type != kNotUsed) {
1727 size_t size = successor_blocks->Size();
1728 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1729 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1730 while (true) {
1731 SuccessorBlockInfo* sbi_old = iterator.Next();
1732 if (sbi_old == nullptr) {
1733 break;
1734 }
1735 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1736 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1737 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001738 }
1739 }
1740
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001741 // Copy offset, method.
1742 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001743
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001744 // Now copy instructions.
1745 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1746 // Get a copy first.
1747 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001748
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001749 // Append it.
1750 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001751 }
1752
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001753 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001754}
1755
1756MIR* MIR::Copy(MIRGraph* mir_graph) {
1757 MIR* res = mir_graph->NewMIR();
1758 *res = *this;
1759
1760 // Remove links
1761 res->next = nullptr;
1762 res->bb = NullBasicBlockId;
1763 res->ssa_rep = nullptr;
1764
1765 return res;
1766}
1767
1768MIR* MIR::Copy(CompilationUnit* c_unit) {
1769 return Copy(c_unit->mir_graph.get());
1770}
1771
1772uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1773 // Default result.
1774 int res = 0;
1775
1776 // We are basically setting the iputs to their igets counterparts.
1777 switch (opcode) {
1778 case Instruction::IPUT:
1779 case Instruction::IPUT_OBJECT:
1780 case Instruction::IPUT_BOOLEAN:
1781 case Instruction::IPUT_BYTE:
1782 case Instruction::IPUT_CHAR:
1783 case Instruction::IPUT_SHORT:
1784 case Instruction::IPUT_QUICK:
1785 case Instruction::IPUT_OBJECT_QUICK:
1786 case Instruction::APUT:
1787 case Instruction::APUT_OBJECT:
1788 case Instruction::APUT_BOOLEAN:
1789 case Instruction::APUT_BYTE:
1790 case Instruction::APUT_CHAR:
1791 case Instruction::APUT_SHORT:
1792 case Instruction::SPUT:
1793 case Instruction::SPUT_OBJECT:
1794 case Instruction::SPUT_BOOLEAN:
1795 case Instruction::SPUT_BYTE:
1796 case Instruction::SPUT_CHAR:
1797 case Instruction::SPUT_SHORT:
1798 // Skip the VR containing what to store.
1799 res = 1;
1800 break;
1801 case Instruction::IPUT_WIDE:
1802 case Instruction::IPUT_WIDE_QUICK:
1803 case Instruction::APUT_WIDE:
1804 case Instruction::SPUT_WIDE:
1805 // Skip the two VRs containing what to store.
1806 res = 2;
1807 break;
1808 default:
1809 // Do nothing in the general case.
1810 break;
1811 }
1812
1813 return res;
1814}
1815
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001816/**
1817 * @brief Given a decoded instruction, it checks whether the instruction
1818 * sets a constant and if it does, more information is provided about the
1819 * constant being set.
1820 * @param ptr_value pointer to a 64-bit holder for the constant.
1821 * @param wide Updated by function whether a wide constant is being set by bytecode.
1822 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1823 */
1824bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1825 bool sets_const = true;
1826 int64_t value = vB;
1827
1828 DCHECK(ptr_value != nullptr);
1829 DCHECK(wide != nullptr);
1830
1831 switch (opcode) {
1832 case Instruction::CONST_4:
1833 case Instruction::CONST_16:
1834 case Instruction::CONST:
1835 *wide = false;
1836 value <<= 32; // In order to get the sign extend.
1837 value >>= 32;
1838 break;
1839 case Instruction::CONST_HIGH16:
1840 *wide = false;
1841 value <<= 48; // In order to get the sign extend.
1842 value >>= 32;
1843 break;
1844 case Instruction::CONST_WIDE_16:
1845 case Instruction::CONST_WIDE_32:
1846 *wide = true;
1847 value <<= 32; // In order to get the sign extend.
1848 value >>= 32;
1849 break;
1850 case Instruction::CONST_WIDE:
1851 *wide = true;
1852 value = vB_wide;
1853 break;
1854 case Instruction::CONST_WIDE_HIGH16:
1855 *wide = true;
1856 value <<= 48; // In order to get the sign extend.
1857 break;
1858 default:
1859 sets_const = false;
1860 break;
1861 }
1862
1863 if (sets_const) {
1864 *ptr_value = value;
1865 }
1866
1867 return sets_const;
1868}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001869
1870void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1871 // Reset flags for all MIRs in bb.
1872 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1873 mir->optimization_flags &= (~reset_flags);
1874 }
1875}
1876
1877void BasicBlock::Hide(CompilationUnit* c_unit) {
1878 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1879 block_type = kDalvikByteCode;
1880
1881 // Mark it as hidden.
1882 hidden = true;
1883
1884 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1885 // are updated to know that they no longer have a parent.
1886 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1887 mir->bb = NullBasicBlockId;
1888 }
1889 first_mir_insn = nullptr;
1890 last_mir_insn = nullptr;
1891
1892 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1893
1894 MIRGraph* mir_graph = c_unit->mir_graph.get();
1895 while (true) {
1896 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1897 if (pred_bb == nullptr) {
1898 break;
1899 }
1900
1901 // Sadly we have to go through the children by hand here.
1902 pred_bb->ReplaceChild(id, NullBasicBlockId);
1903 }
1904
1905 // Iterate through children of bb we are hiding.
1906 ChildBlockIterator successorChildIter(this, mir_graph);
1907
1908 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1909 // Replace child with null child.
1910 childPtr->predecessors->Delete(id);
1911 }
1912}
1913
1914bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1915 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1916 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1917 // then it is not live out of this BB.
1918 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1919
1920 int last_ssa_reg = -1;
1921
1922 // Walk through the MIRs backwards.
1923 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1924 // Get ssa rep.
1925 SSARepresentation *ssa_rep = mir->ssa_rep;
1926
1927 // Go through the defines for this MIR.
1928 for (int i = 0; i < ssa_rep->num_defs; i++) {
1929 DCHECK(ssa_rep->defs != nullptr);
1930
1931 // Get the ssa reg.
1932 int def_ssa_reg = ssa_rep->defs[i];
1933
1934 // Get dalvik reg.
1935 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1936
1937 // Compare dalvik regs.
1938 if (dalvik_reg == def_dalvik_reg) {
1939 // We found a def of the register that we are being asked about.
1940 // Remember it.
1941 last_ssa_reg = def_ssa_reg;
1942 }
1943 }
1944 }
1945
1946 if (last_ssa_reg == -1) {
1947 // If we get to this point we couldn't find a define of register user asked about.
1948 // Let's assume the user knows what he's doing so we can be safe and say that if we
1949 // couldn't find a def, it is live out.
1950 return true;
1951 }
1952
1953 // If it is not -1, we found a match, is it ssa_reg?
1954 return (ssa_reg == last_ssa_reg);
1955}
1956
1957bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1958 // We need to check taken, fall_through, and successor_blocks to replace.
1959 bool found = false;
1960 if (taken == old_bb) {
1961 taken = new_bb;
1962 found = true;
1963 }
1964
1965 if (fall_through == old_bb) {
1966 fall_through = new_bb;
1967 found = true;
1968 }
1969
1970 if (successor_block_list_type != kNotUsed) {
1971 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1972 while (true) {
1973 SuccessorBlockInfo* successor_block_info = iterator.Next();
1974 if (successor_block_info == nullptr) {
1975 break;
1976 }
1977 if (successor_block_info->block == old_bb) {
1978 successor_block_info->block = new_bb;
1979 found = true;
1980 }
1981 }
1982 }
1983
1984 return found;
1985}
1986
1987void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1988 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1989 bool found = false;
1990
1991 while (true) {
1992 BasicBlockId pred_bb_id = iterator.Next();
1993
1994 if (pred_bb_id == NullBasicBlockId) {
1995 break;
1996 }
1997
1998 if (pred_bb_id == old_parent) {
1999 size_t idx = iterator.GetIndex() - 1;
2000 predecessors->Put(idx, new_parent);
2001 found = true;
2002 break;
2003 }
2004 }
2005
2006 // If not found, add it.
2007 if (found == false) {
2008 predecessors->Insert(new_parent);
2009 }
2010}
2011
2012// Create a new basic block with block_id as num_blocks_ that is
2013// post-incremented.
2014BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2015 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2016 block_list_.Insert(res);
2017 return res;
2018}
2019
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002020void MIRGraph::CalculateBasicBlockInformation() {
2021 PassDriverMEPostOpt driver(cu_);
2022 driver.Launch();
2023}
2024
2025void MIRGraph::InitializeBasicBlockData() {
2026 num_blocks_ = block_list_.Size();
2027}
2028
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002029} // namespace art