blob: 5741b0b8ff3d30d8301fdeb05f577e9cdf9cbd21 [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 Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070029#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010030#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000031
buzbee311ca162013-02-28 15:56:43 -080032namespace art {
33
34#define MAX_PATTERN_LEN 5
35
buzbee1fd33462013-03-25 13:40:45 -070036const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
37 "Phi",
38 "Copy",
39 "FusedCmplFloat",
40 "FusedCmpgFloat",
41 "FusedCmplDouble",
42 "FusedCmpgDouble",
43 "FusedCmpLong",
44 "Nop",
45 "OpNullCheck",
46 "OpRangeCheck",
47 "OpDivZeroCheck",
48 "Check1",
49 "Check2",
50 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040051 "ConstVector",
52 "MoveVector",
53 "PackedMultiply",
54 "PackedAddition",
55 "PackedSubtract",
56 "PackedShiftLeft",
57 "PackedSignedShiftRight",
58 "PackedUnsignedShiftRight",
59 "PackedAnd",
60 "PackedOr",
61 "PackedXor",
62 "PackedAddReduce",
63 "PackedReduce",
64 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070065 "ReserveVectorRegisters",
66 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070067};
68
buzbee862a7602013-04-05 10:58:54 -070069MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070070 : reg_location_(NULL),
71 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080072 ssa_base_vregs_(NULL),
73 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080074 vreg_to_ssa_map_(NULL),
75 ssa_last_defs_(NULL),
76 is_constant_v_(NULL),
77 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070078 use_counts_(arena, 256, kGrowableArrayMisc),
79 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080080 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070081 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070082 dfs_order_(NULL),
83 dfs_post_order_(NULL),
84 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070085 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080086 i_dom_list_(NULL),
87 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000088 temp_scoped_alloc_(),
89 temp_insn_data_(nullptr),
90 temp_bit_vector_size_(0u),
91 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070092 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080093 try_block_addr_(NULL),
94 entry_block_(NULL),
95 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080096 num_blocks_(0),
97 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070098 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080099 current_method_(kInvalidEntry),
100 current_offset_(kInvalidEntry),
101 def_count_(0),
102 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700103 num_ssa_regs_(0),
104 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700105 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
106 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700107 arena_(arena),
108 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800109 forward_branches_(0),
110 compiler_temps_(arena, 6, kGrowableArrayMisc),
111 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800112 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000113 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000114 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000115 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000116 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700117 method_lowering_infos_(arena, 0u),
118 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700119 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800120 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
121 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800122}
123
Ian Rogers6282dc12013-04-18 15:54:02 -0700124MIRGraph::~MIRGraph() {
125 STLDeleteElements(&m_units_);
126}
127
buzbee311ca162013-02-28 15:56:43 -0800128/*
129 * Parse an instruction, return the length of the instruction
130 */
Ian Rogers29a26482014-05-02 15:27:29 -0700131int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
132 const Instruction* inst = Instruction::At(code_ptr);
133 decoded_instruction->opcode = inst->Opcode();
134 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
135 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
136 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
137 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
138 if (inst->HasVarArgs()) {
139 inst->GetVarArgs(decoded_instruction->arg);
140 }
141 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800142}
143
144
145/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700146BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700147 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700148 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800149 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700150 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800151 while (insn) {
152 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700153 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800154 insn = insn->next;
155 }
156 if (insn == NULL) {
157 LOG(FATAL) << "Break split failed";
158 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700159 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700160 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800161
162 bottom_block->start_offset = code_offset;
163 bottom_block->first_mir_insn = insn;
164 bottom_block->last_mir_insn = orig_block->last_mir_insn;
165
166 /* If this block was terminated by a return, the flag needs to go with the bottom block */
167 bottom_block->terminated_by_return = orig_block->terminated_by_return;
168 orig_block->terminated_by_return = false;
169
buzbee311ca162013-02-28 15:56:43 -0800170 /* Handle the taken path */
171 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700172 if (bottom_block->taken != NullBasicBlockId) {
173 orig_block->taken = NullBasicBlockId;
174 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
175 bb_taken->predecessors->Delete(orig_block->id);
176 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800177 }
178
179 /* Handle the fallthrough path */
180 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700181 orig_block->fall_through = bottom_block->id;
182 bottom_block->predecessors->Insert(orig_block->id);
183 if (bottom_block->fall_through != NullBasicBlockId) {
184 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
185 bb_fall_through->predecessors->Delete(orig_block->id);
186 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800187 }
188
189 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700190 if (orig_block->successor_block_list_type != kNotUsed) {
191 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
192 bottom_block->successor_blocks = orig_block->successor_blocks;
193 orig_block->successor_block_list_type = kNotUsed;
194 orig_block->successor_blocks = NULL;
195 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800196 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700197 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800198 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700199 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700200 bb->predecessors->Delete(orig_block->id);
201 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800202 }
203 }
204
buzbee0d829482013-10-11 15:24:55 -0700205 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700206 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800207
buzbee311ca162013-02-28 15:56:43 -0800208 /*
209 * Update the immediate predecessor block pointer so that outgoing edges
210 * can be applied to the proper block.
211 */
212 if (immed_pred_block_p) {
213 DCHECK_EQ(*immed_pred_block_p, orig_block);
214 *immed_pred_block_p = bottom_block;
215 }
buzbeeb48819d2013-09-14 16:15:25 -0700216
217 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000218 DCHECK(insn != nullptr);
219 DCHECK(insn != orig_block->first_mir_insn);
220 DCHECK(insn == bottom_block->first_mir_insn);
221 DCHECK_EQ(insn->offset, bottom_block->start_offset);
222 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
223 !IsPseudoMirOp(insn->dalvikInsn.opcode));
224 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
225 MIR* p = insn;
226 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
227 while (p != bottom_block->last_mir_insn) {
228 p = p->next;
229 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700230 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700231 int opcode = p->dalvikInsn.opcode;
232 /*
233 * Some messiness here to ensure that we only enter real opcodes and only the
234 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000235 * CHECK and work portions. Since the 2nd half of a split operation is always
236 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700237 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000238 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
239 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700240 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
241 }
buzbeeb48819d2013-09-14 16:15:25 -0700242 }
243
buzbee311ca162013-02-28 15:56:43 -0800244 return bottom_block;
245}
246
247/*
248 * Given a code offset, find out the block that starts with it. If the offset
249 * is in the middle of an existing block, split it into two. If immed_pred_block_p
250 * is not non-null and is the block being split, update *immed_pred_block_p to
251 * point to the bottom block so that outgoing edges can be set up properly
252 * (by the caller)
253 * Utilizes a map for fast lookup of the typical cases.
254 */
buzbee0d829482013-10-11 15:24:55 -0700255BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700256 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700257 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800258 return NULL;
259 }
buzbeeb48819d2013-09-14 16:15:25 -0700260
261 int block_id = dex_pc_to_block_map_.Get(code_offset);
262 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
263
264 if ((bb != NULL) && (bb->start_offset == code_offset)) {
265 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700266 return bb;
267 }
buzbee311ca162013-02-28 15:56:43 -0800268
buzbeeb48819d2013-09-14 16:15:25 -0700269 // No direct hit.
270 if (!create) {
271 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800272 }
273
buzbeeb48819d2013-09-14 16:15:25 -0700274 if (bb != NULL) {
275 // The target exists somewhere in an existing block.
276 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
277 }
278
279 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700280 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
281 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800282 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700283 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800284 return bb;
285}
286
buzbeeb48819d2013-09-14 16:15:25 -0700287
buzbee311ca162013-02-28 15:56:43 -0800288/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700289void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800290 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700291 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800292
293 if (tries_size == 0) {
294 return;
295 }
296
297 for (int i = 0; i < tries_size; i++) {
298 const DexFile::TryItem* pTry =
299 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700300 DexOffset start_offset = pTry->start_addr_;
301 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800302 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700303 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800304 }
305 }
306
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700307 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800308 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
309 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
310 for (uint32_t idx = 0; idx < handlers_size; idx++) {
311 CatchHandlerIterator iterator(handlers_ptr);
312 for (; iterator.HasNext(); iterator.Next()) {
313 uint32_t address = iterator.GetHandlerAddress();
314 FindBlock(address, false /* split */, true /*create*/,
315 /* immed_pred_block_p */ NULL);
316 }
317 handlers_ptr = iterator.EndDataPointer();
318 }
319}
320
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100321bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
322 NarrowDexOffset catch_offset) {
323 // Catches for monitor-exit during stack unwinding have the pattern
324 // move-exception (move)* (goto)? monitor-exit throw
325 // In the currently generated dex bytecode we see these catching a bytecode range including
326 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
327 // it's the case for a given monitor-exit and catch block so that we can ignore it.
328 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
329 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
330 // even though a throwing monitor-exit certainly indicates a bytecode error.)
331 const Instruction* monitor_exit = Instruction::At(cu_->code_item->insns_ + monitor_exit_offset);
332 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
333 int monitor_reg = monitor_exit->VRegA_11x();
334 const Instruction* check_insn = Instruction::At(cu_->code_item->insns_ + catch_offset);
335 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
336 if (check_insn->VRegA_11x() == monitor_reg) {
337 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
338 return false;
339 }
340 check_insn = check_insn->Next();
341 while (true) {
342 int dest = -1;
343 bool wide = false;
344 switch (check_insn->Opcode()) {
345 case Instruction::MOVE_WIDE:
346 wide = true;
347 // Intentional fall-through.
348 case Instruction::MOVE_OBJECT:
349 case Instruction::MOVE:
350 dest = check_insn->VRegA_12x();
351 break;
352
353 case Instruction::MOVE_WIDE_FROM16:
354 wide = true;
355 // Intentional fall-through.
356 case Instruction::MOVE_OBJECT_FROM16:
357 case Instruction::MOVE_FROM16:
358 dest = check_insn->VRegA_22x();
359 break;
360
361 case Instruction::MOVE_WIDE_16:
362 wide = true;
363 // Intentional fall-through.
364 case Instruction::MOVE_OBJECT_16:
365 case Instruction::MOVE_16:
366 dest = check_insn->VRegA_32x();
367 break;
368
369 case Instruction::GOTO:
370 case Instruction::GOTO_16:
371 case Instruction::GOTO_32:
372 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
373 // Intentional fall-through.
374 default:
375 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
376 check_insn->VRegA_11x() == monitor_reg;
377 }
378
379 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
380 return false;
381 }
382
383 check_insn = check_insn->Next();
384 }
385}
386
buzbee311ca162013-02-28 15:56:43 -0800387/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700388BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
389 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700390 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700391 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800392 switch (insn->dalvikInsn.opcode) {
393 case Instruction::GOTO:
394 case Instruction::GOTO_16:
395 case Instruction::GOTO_32:
396 target += insn->dalvikInsn.vA;
397 break;
398 case Instruction::IF_EQ:
399 case Instruction::IF_NE:
400 case Instruction::IF_LT:
401 case Instruction::IF_GE:
402 case Instruction::IF_GT:
403 case Instruction::IF_LE:
404 cur_block->conditional_branch = true;
405 target += insn->dalvikInsn.vC;
406 break;
407 case Instruction::IF_EQZ:
408 case Instruction::IF_NEZ:
409 case Instruction::IF_LTZ:
410 case Instruction::IF_GEZ:
411 case Instruction::IF_GTZ:
412 case Instruction::IF_LEZ:
413 cur_block->conditional_branch = true;
414 target += insn->dalvikInsn.vB;
415 break;
416 default:
417 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
418 }
buzbeeb48819d2013-09-14 16:15:25 -0700419 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700420 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800421 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700422 cur_block->taken = taken_block->id;
423 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800424
425 /* Always terminate the current block for conditional branches */
426 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700427 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800428 /*
429 * If the method is processed
430 * in sequential order from the
431 * beginning, we don't need to
432 * specify split for continue
433 * blocks. However, this
434 * routine can be called by
435 * compileLoop, which starts
436 * parsing the method from an
437 * arbitrary address in the
438 * method body.
439 */
440 true,
441 /* create */
442 true,
443 /* immed_pred_block_p */
444 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700445 cur_block->fall_through = fallthrough_block->id;
446 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800447 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700448 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800449 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800450 }
451 return cur_block;
452}
453
454/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800455BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
456 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800457 const uint16_t* switch_data =
458 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
459 int size;
460 const int* keyTable;
461 const int* target_table;
462 int i;
463 int first_key;
464
465 /*
466 * Packed switch data format:
467 * ushort ident = 0x0100 magic value
468 * ushort size number of entries in the table
469 * int first_key first (and lowest) switch case value
470 * int targets[size] branch targets, relative to switch opcode
471 *
472 * Total size is (4+size*2) 16-bit code units.
473 */
474 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
475 DCHECK_EQ(static_cast<int>(switch_data[0]),
476 static_cast<int>(Instruction::kPackedSwitchSignature));
477 size = switch_data[1];
478 first_key = switch_data[2] | (switch_data[3] << 16);
479 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700480 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800481 /*
482 * Sparse switch data format:
483 * ushort ident = 0x0200 magic value
484 * ushort size number of entries in the table; > 0
485 * int keys[size] keys, sorted low-to-high; 32-bit aligned
486 * int targets[size] branch targets, relative to switch opcode
487 *
488 * Total size is (2+size*4) 16-bit code units.
489 */
490 } else {
491 DCHECK_EQ(static_cast<int>(switch_data[0]),
492 static_cast<int>(Instruction::kSparseSwitchSignature));
493 size = switch_data[1];
494 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
495 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700496 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800497 }
498
buzbee0d829482013-10-11 15:24:55 -0700499 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800500 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700501 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800502 }
buzbee0d829482013-10-11 15:24:55 -0700503 cur_block->successor_block_list_type =
504 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
505 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700506 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800507
508 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700509 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800510 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700511 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700512 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000513 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700514 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800515 successor_block_info->key =
516 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
517 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700518 cur_block->successor_blocks->Insert(successor_block_info);
519 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800520 }
521
522 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700523 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
524 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700525 cur_block->fall_through = fallthrough_block->id;
526 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800527 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800528}
529
530/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700531BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
532 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700533 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700534 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800535 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
536 bool build_all_edges =
537 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800538
539 /* In try block */
540 if (in_try_block) {
541 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
542
buzbee0d829482013-10-11 15:24:55 -0700543 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800544 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
545 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700546 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800547 }
548
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700549 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700550 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800551 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100552 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
553 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
554 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
555 continue;
556 }
557 if (cur_block->successor_block_list_type == kNotUsed) {
558 cur_block->successor_block_list_type = kCatch;
559 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
560 arena_, 2, kGrowableArraySuccessorBlocks);
561 }
buzbee311ca162013-02-28 15:56:43 -0800562 catch_block->catch_entry = true;
563 if (kIsDebugBuild) {
564 catches_.insert(catch_block->start_offset);
565 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700566 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000567 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700568 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800569 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700570 cur_block->successor_blocks->Insert(successor_block_info);
571 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800572 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100573 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
574 }
575 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700576 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700577 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700578 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800579 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700580 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800581 }
582
buzbee17189ac2013-11-08 11:07:02 -0800583 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800584 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700585 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700586 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800587 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
588 /* immed_pred_block_p */ NULL);
589 }
590 if (!in_try_block) {
591 // Don't split a THROW that can't rethrow - we're done.
592 return cur_block;
593 }
594 }
595
buzbee17189ac2013-11-08 11:07:02 -0800596 if (!build_all_edges) {
597 /*
598 * Even though there is an exception edge here, control cannot return to this
599 * method. Thus, for the purposes of dataflow analysis and optimization, we can
600 * ignore the edge. Doing this reduces compile time, and increases the scope
601 * of the basic-block level optimization pass.
602 */
603 return cur_block;
604 }
605
buzbee311ca162013-02-28 15:56:43 -0800606 /*
607 * Split the potentially-throwing instruction into two parts.
608 * The first half will be a pseudo-op that captures the exception
609 * edges and terminates the basic block. It always falls through.
610 * Then, create a new basic block that begins with the throwing instruction
611 * (minus exceptions). Note: this new basic block must NOT be entered into
612 * the block_map. If the potentially-throwing instruction is the target of a
613 * future branch, we need to find the check psuedo half. The new
614 * basic block containing the work portion of the instruction should
615 * only be entered via fallthrough from the block containing the
616 * pseudo exception edge MIR. Note also that this new block is
617 * not automatically terminated after the work portion, and may
618 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700619 *
620 * Note also that the dex_pc_to_block_map_ entry for the potentially
621 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800622 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700623 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700624 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800625 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700626 cur_block->fall_through = new_block->id;
627 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700628 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800629 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700630 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700631 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800632 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700633 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800634 return new_block;
635}
636
637/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
638void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700639 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700640 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800641 current_code_item_ = code_item;
642 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
643 current_method_ = m_units_.size();
644 current_offset_ = 0;
645 // TODO: will need to snapshot stack image and use that as the mir context identification.
646 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000647 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
648 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800649 const uint16_t* code_ptr = current_code_item_->insns_;
650 const uint16_t* code_end =
651 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
652
653 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700654 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700655 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700656 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 -0700657
buzbee311ca162013-02-28 15:56:43 -0800658 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700659 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
660 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800661
662 // If this is the first method, set up default entry and exit blocks.
663 if (current_method_ == 0) {
664 DCHECK(entry_block_ == NULL);
665 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700666 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700667 // Use id 0 to represent a null block.
668 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
669 DCHECK_EQ(null_block->id, NullBasicBlockId);
670 null_block->hidden = true;
671 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700672 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700673 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700674 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700675 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800676 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
677 cu_->dex_file = &dex_file;
678 cu_->class_def_idx = class_def_idx;
679 cu_->method_idx = method_idx;
680 cu_->access_flags = access_flags;
681 cu_->invoke_type = invoke_type;
682 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
683 cu_->num_ins = current_code_item_->ins_size_;
684 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
685 cu_->num_outs = current_code_item_->outs_size_;
686 cu_->num_dalvik_registers = current_code_item_->registers_size_;
687 cu_->insns = current_code_item_->insns_;
688 cu_->code_item = current_code_item_;
689 } else {
690 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
691 /*
692 * Will need to manage storage for ins & outs, push prevous state and update
693 * insert point.
694 */
695 }
696
697 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700698 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700699 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800700 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700701 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700702 // TODO: for inlining support, insert at the insert point rather than entry block.
703 entry_block_->fall_through = cur_block->id;
704 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800705
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000706 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800707 ProcessTryCatchBlocks();
708
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000709 uint64_t merged_df_flags = 0u;
710
buzbee311ca162013-02-28 15:56:43 -0800711 /* Parse all instructions and put them into containing basic blocks */
712 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700713 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800714 insn->offset = current_offset_;
715 insn->m_unit_index = current_method_;
716 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800717 Instruction::Code opcode = insn->dalvikInsn.opcode;
718 if (opcode_count_ != NULL) {
719 opcode_count_[static_cast<int>(opcode)]++;
720 }
721
buzbee311ca162013-02-28 15:56:43 -0800722 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800723 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800724
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700725 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000726 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800727
728 if (df_flags & DF_HAS_DEFS) {
729 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
730 }
731
buzbee1da1e2f2013-11-15 13:37:01 -0800732 if (df_flags & DF_LVN) {
733 cur_block->use_lvn = true; // Run local value numbering on this basic block.
734 }
735
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700736 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700737 if (opcode == Instruction::NOP) {
738 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
739 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
740 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
741 uint16_t following_raw_instruction = code_ptr[1];
742 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
743 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
744 (following_raw_instruction == Instruction::kArrayDataSignature)) {
745 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
746 }
747 }
748 if (width == 1) {
749 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700750 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700751 } else {
buzbee0d829482013-10-11 15:24:55 -0700752 DCHECK(cur_block->fall_through == NullBasicBlockId);
753 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700754 // Unreachable instruction, mark for no continuation.
755 flags &= ~Instruction::kContinue;
756 }
757 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700758 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700759 }
760
buzbeeb48819d2013-09-14 16:15:25 -0700761 // Associate the starting dex_pc for this opcode with its containing basic block.
762 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
763
buzbee27247762013-07-28 12:03:58 -0700764 code_ptr += width;
765
buzbee311ca162013-02-28 15:56:43 -0800766 if (flags & Instruction::kBranch) {
767 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
768 width, flags, code_ptr, code_end);
769 } else if (flags & Instruction::kReturn) {
770 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700771 cur_block->fall_through = exit_block_->id;
772 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800773 /*
774 * Terminate the current block if there are instructions
775 * afterwards.
776 */
777 if (code_ptr < code_end) {
778 /*
779 * Create a fallthrough block for real instructions
780 * (incl. NOP).
781 */
buzbee27247762013-07-28 12:03:58 -0700782 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
783 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800784 }
785 } else if (flags & Instruction::kThrow) {
786 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
787 code_ptr, code_end);
788 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800789 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800790 }
buzbeeb1f1d642014-02-27 12:55:32 -0800791 if (verify_flags & Instruction::kVerifyVarArgRange) {
792 /*
793 * The Quick backend's runtime model includes a gap between a method's
794 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
795 * which spans the gap is somewhat complicated, and should not happen
796 * in normal usage of dx. Punt to the interpreter.
797 */
798 int first_reg_in_range = insn->dalvikInsn.vC;
799 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
800 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
801 punt_to_interpreter_ = true;
802 }
803 }
buzbee311ca162013-02-28 15:56:43 -0800804 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700805 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800806 false, /* immed_pred_block_p */ NULL);
807 if (next_block) {
808 /*
809 * The next instruction could be the target of a previously parsed
810 * forward branch so a block is already created. If the current
811 * instruction is not an unconditional branch, connect them through
812 * the fall-through link.
813 */
buzbee0d829482013-10-11 15:24:55 -0700814 DCHECK(cur_block->fall_through == NullBasicBlockId ||
815 GetBasicBlock(cur_block->fall_through) == next_block ||
816 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800817
buzbee0d829482013-10-11 15:24:55 -0700818 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
819 cur_block->fall_through = next_block->id;
820 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800821 }
822 cur_block = next_block;
823 }
824 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000825 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000826
buzbee311ca162013-02-28 15:56:43 -0800827 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
828 DumpCFG("/sdcard/1_post_parse_cfg/", true);
829 }
830
831 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700832 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800833 }
834}
835
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700836void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800837 DCHECK(opcode_count_ != NULL);
838 LOG(INFO) << "Opcode Count";
839 for (int i = 0; i < kNumPackedOpcodes; i++) {
840 if (opcode_count_[i] != 0) {
841 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
842 << " " << opcode_count_[i];
843 }
844 }
845}
846
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700847uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
848 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
849 return oat_data_flow_attributes_[opcode];
850}
851
852uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
853 DCHECK(mir != nullptr);
854 Instruction::Code opcode = mir->dalvikInsn.opcode;
855 return GetDataFlowAttributes(opcode);
856}
857
buzbee311ca162013-02-28 15:56:43 -0800858// TODO: use a configurable base prefix, and adjust callers to supply pass name.
859/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800860void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800861 FILE* file;
862 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
863 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800864 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
865 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
866 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800867 file = fopen(fname.c_str(), "w");
868 if (file == NULL) {
869 return;
870 }
871 fprintf(file, "digraph G {\n");
872
873 fprintf(file, " rankdir=TB\n");
874
875 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
876 int idx;
877
878 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700879 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700880 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700881 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800882 if (bb->block_type == kDead) continue;
883 if (bb->block_type == kEntryBlock) {
884 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
885 } else if (bb->block_type == kExitBlock) {
886 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
887 } else if (bb->block_type == kDalvikByteCode) {
888 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
889 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700890 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800891 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
892 bb->first_mir_insn ? " | " : " ");
893 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
894 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400895 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
896 if (opcode == kMirOpConstVector) {
897 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
898 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
899 mir->dalvikInsn.vA,
900 mir->dalvikInsn.vB,
901 mir->dalvikInsn.arg[0],
902 mir->dalvikInsn.arg[1],
903 mir->dalvikInsn.arg[2],
904 mir->dalvikInsn.arg[3],
905 mir->next ? " | " : " ");
906 } else {
907 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
908 extended_mir_op_names_[opcode - kMirOpFirst],
909 mir->dalvikInsn.vA,
910 mir->dalvikInsn.vB,
911 mir->dalvikInsn.vC,
912 mir->next ? " | " : " ");
913 }
914 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700915 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400916 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700917 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400918 extended_mir_op_names_[opcode - kMirOpFirst],
919 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
920 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700921 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400922 mir->next ? " | " : " ");
923 }
buzbee311ca162013-02-28 15:56:43 -0800924 }
925 fprintf(file, " }\"];\n\n");
926 } else if (bb->block_type == kExceptionHandling) {
927 char block_name[BLOCK_NAME_LEN];
928
929 GetBlockName(bb, block_name);
930 fprintf(file, " %s [shape=invhouse];\n", block_name);
931 }
932
933 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
934
buzbee0d829482013-10-11 15:24:55 -0700935 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800936 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700937 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800938 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
939 block_name1, block_name2);
940 }
buzbee0d829482013-10-11 15:24:55 -0700941 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800942 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700943 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800944 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
945 }
946
buzbee0d829482013-10-11 15:24:55 -0700947 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800948 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
949 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700950 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
951 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700952 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800953
954 int succ_id = 0;
955 while (true) {
956 if (successor_block_info == NULL) break;
957
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700958 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700959 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800960
961 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
962 succ_id++,
963 successor_block_info->key,
964 dest_block->start_offset,
965 (next_successor_block_info != NULL) ? " | " : " ");
966
967 successor_block_info = next_successor_block_info;
968 }
969 fprintf(file, " }\"];\n\n");
970
971 GetBlockName(bb, block_name1);
972 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
973 block_name1, bb->start_offset, bb->id);
974
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700975 // Link the successor pseudo-block with all of its potential targets.
976 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800977
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700978 succ_id = 0;
979 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700980 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700981 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800982
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800984
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 GetBlockName(dest_block, block_name2);
986 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
987 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800988 }
989 }
990 fprintf(file, "\n");
991
992 if (cu_->verbose) {
993 /* Display the dominator tree */
994 GetBlockName(bb, block_name1);
995 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
996 block_name1, block_name1);
997 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700998 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800999 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1000 }
1001 }
1002 }
1003 fprintf(file, "}\n");
1004 fclose(file);
1005}
1006
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001007/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001008void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001009 // Insert it after the last MIR.
1010 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001011}
1012
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001013void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1014 // Insert it after the last MIR.
1015 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1016}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001017
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001018void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1019 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1020 MIR* new_mir = *it;
1021
1022 // Add a copy of each MIR.
1023 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1024 }
buzbee1fd33462013-03-25 13:40:45 -07001025}
1026
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001027/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001028void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001029 InsertMIRListAfter(current_mir, new_mir, new_mir);
1030}
buzbee1fd33462013-03-25 13:40:45 -07001031
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001032void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1033 // If no MIR, we are done.
1034 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1035 return;
buzbee1fd33462013-03-25 13:40:45 -07001036 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001037
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001038 // If insert_after is null, assume BB is empty.
1039 if (insert_after == nullptr) {
1040 first_mir_insn = first_list_mir;
1041 last_mir_insn = last_list_mir;
1042 last_list_mir->next = nullptr;
1043 } else {
1044 MIR* after_list = insert_after->next;
1045 insert_after->next = first_list_mir;
1046 last_list_mir->next = after_list;
1047 if (after_list == nullptr) {
1048 last_mir_insn = last_list_mir;
1049 }
1050 }
1051
1052 // Set this BB to be the basic block of the MIRs.
1053 MIR* last = last_list_mir->next;
1054 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1055 mir->bb = id;
1056 }
1057}
1058
1059/* Insert an MIR instruction to the head of a basic block. */
1060void BasicBlock::PrependMIR(MIR* mir) {
1061 InsertMIRListBefore(first_mir_insn, mir, mir);
1062}
1063
1064void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1065 // Insert it before the first MIR.
1066 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1067}
1068
1069void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1070 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1071 MIR* mir = *it;
1072
1073 InsertMIRListBefore(first_mir_insn, mir, mir);
1074 }
1075}
1076
1077/* Insert a MIR instruction before the specified MIR. */
1078void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1079 // Insert as a single element list.
1080 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001081}
1082
1083MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1084 MIR* current = first_mir_insn;
1085
1086 while (current != nullptr) {
1087 MIR* next = current->next;
1088
1089 if (next == mir) {
1090 return current;
1091 }
1092
1093 current = next;
1094 }
1095
1096 return nullptr;
1097}
1098
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001099void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1100 // If no MIR, we are done.
1101 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1102 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001103 }
1104
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001105 // If insert_before is null, assume BB is empty.
1106 if (insert_before == nullptr) {
1107 first_mir_insn = first_list_mir;
1108 last_mir_insn = last_list_mir;
1109 last_list_mir->next = nullptr;
1110 } else {
1111 if (first_mir_insn == insert_before) {
1112 last_list_mir->next = first_mir_insn;
1113 first_mir_insn = first_list_mir;
1114 } else {
1115 // Find the preceding MIR.
1116 MIR* before_list = FindPreviousMIR(insert_before);
1117 DCHECK(before_list != nullptr);
1118 before_list->next = first_list_mir;
1119 last_list_mir->next = insert_before;
1120 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001121 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001122
1123 // Set this BB to be the basic block of the MIRs.
1124 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1125 mir->bb = id;
1126 }
1127}
1128
1129bool BasicBlock::RemoveMIR(MIR* mir) {
1130 // Remove as a single element list.
1131 return RemoveMIRList(mir, mir);
1132}
1133
1134bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1135 if (first_list_mir == nullptr) {
1136 return false;
1137 }
1138
1139 // Try to find the MIR.
1140 MIR* before_list = nullptr;
1141 MIR* after_list = nullptr;
1142
1143 // If we are removing from the beginning of the MIR list.
1144 if (first_mir_insn == first_list_mir) {
1145 before_list = nullptr;
1146 } else {
1147 before_list = FindPreviousMIR(first_list_mir);
1148 if (before_list == nullptr) {
1149 // We did not find the mir.
1150 return false;
1151 }
1152 }
1153
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001154 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001155 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1156 mir->bb = NullBasicBlockId;
1157 }
1158
1159 after_list = last_list_mir->next;
1160
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001161 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001162 if (before_list == nullptr) {
1163 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001164 } else {
1165 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001166 }
1167
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001168 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001169 if (after_list == nullptr) {
1170 last_mir_insn = before_list;
1171 }
1172
1173 return true;
buzbee1fd33462013-03-25 13:40:45 -07001174}
1175
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001176MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001177 MIR* next_mir = nullptr;
1178
1179 if (current != nullptr) {
1180 next_mir = current->next;
1181 }
1182
1183 if (next_mir == nullptr) {
1184 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001185 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1186 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001187 }
1188 }
1189
1190 return next_mir;
1191}
1192
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001193char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001194 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001195 std::string str;
1196 int flags = 0;
1197 int opcode = insn.opcode;
1198 char* ret;
1199 bool nop = false;
1200 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001201 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001202 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1203 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1204
1205 // Handle special cases.
1206 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1207 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1208 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001209 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001210 insn = mir->meta.throw_insn->dalvikInsn;
1211 ssa_rep = mir->meta.throw_insn->ssa_rep;
1212 defs = ssa_rep->num_defs;
1213 uses = ssa_rep->num_uses;
1214 opcode = insn.opcode;
1215 } else if (opcode == kMirOpNop) {
1216 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001217 // Recover original opcode.
1218 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1219 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001220 nop = true;
1221 }
1222
buzbee35ba7f32014-05-31 08:59:01 -07001223 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001224 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1225 } else {
1226 dalvik_format = Instruction::FormatOf(insn.opcode);
1227 flags = Instruction::FlagsOf(insn.opcode);
1228 str.append(Instruction::Name(insn.opcode));
1229 }
1230
1231 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001232 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001233 str.append(StringPrintf(" %s = (%s",
1234 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1235 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001236 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001237 int i;
1238 for (i = 1; i < uses; i++) {
1239 str.append(StringPrintf(", %s:%d",
1240 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1241 incoming[i]));
1242 }
1243 str.append(")");
1244 } else if ((flags & Instruction::kBranch) != 0) {
1245 // For branches, decode the instructions to print out the branch targets.
1246 int offset = 0;
1247 switch (dalvik_format) {
1248 case Instruction::k21t:
1249 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1250 offset = insn.vB;
1251 break;
1252 case Instruction::k22t:
1253 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1254 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1255 offset = insn.vC;
1256 break;
1257 case Instruction::k10t:
1258 case Instruction::k20t:
1259 case Instruction::k30t:
1260 offset = insn.vA;
1261 break;
1262 default:
1263 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1264 }
1265 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1266 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1267 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001268 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001269 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1270 (dalvik_format == Instruction::k3rc));
1271 if (defs != 0) {
1272 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1273 if (uses != 0) {
1274 str.append(", ");
1275 }
1276 }
1277 for (int i = 0; i < uses; i++) {
1278 str.append(
1279 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1280 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1281 // For the listing, skip the high sreg.
1282 i++;
1283 }
1284 if (i != (uses -1)) {
1285 str.append(",");
1286 }
1287 }
1288 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001289 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001290 case Instruction::k21s:
1291 case Instruction::k31i:
1292 case Instruction::k21h:
1293 str.append(StringPrintf(", #%d", insn.vB));
1294 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001295 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001296 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001297 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001298 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001299 case Instruction::k31c:
1300 str.append(StringPrintf(", index #%d", insn.vB));
1301 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001302 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001303 str.append(StringPrintf(", index #%d", insn.vC));
1304 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001305 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001306 case Instruction::k22b:
1307 str.append(StringPrintf(", #%d", insn.vC));
1308 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001309 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001310 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001311 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001312 }
buzbee1fd33462013-03-25 13:40:45 -07001313 }
1314 if (nop) {
1315 str.append("]--optimized away");
1316 }
1317 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001318 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001319 strncpy(ret, str.c_str(), length);
1320 return ret;
1321}
1322
1323/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001324void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001325 static const struct { const char before; const char after; } match[] = {
1326 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1327 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1328 };
buzbee1fd33462013-03-25 13:40:45 -07001329 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1330 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1331 }
1332}
1333
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001334std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001335 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1336 // the arena. We should be smarter and just place straight into the arena, or compute the
1337 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001338 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1339}
1340
1341// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001342std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001343 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001344 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001345 return GetSSAName(ssa_reg);
1346 }
1347 if (IsConst(reg_location_[ssa_reg])) {
1348 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001349 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001350 ConstantValueWide(reg_location_[ssa_reg]));
1351 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001352 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001353 ConstantValue(reg_location_[ssa_reg]));
1354 }
1355 } else {
1356 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1357 }
1358}
1359
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001360void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001361 switch (bb->block_type) {
1362 case kEntryBlock:
1363 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1364 break;
1365 case kExitBlock:
1366 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1367 break;
1368 case kDalvikByteCode:
1369 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1370 break;
1371 case kExceptionHandling:
1372 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1373 bb->id);
1374 break;
1375 default:
1376 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1377 break;
1378 }
1379}
1380
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001381const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001382 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001383 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1384 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1385}
1386
1387/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001388void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001389 BasicBlock* bb;
1390 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001391 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001392 "Entry Block",
1393 "Code Block",
1394 "Exit Block",
1395 "Exception Handling",
1396 "Catch Block"
1397 };
1398
1399 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1400 LOG(INFO) << cu_->insns << " insns";
1401 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001402 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001403
1404 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001405 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001406 if (bb == NULL) break;
1407 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1408 bb->id,
1409 block_type_names[bb->block_type],
1410 bb->start_offset,
1411 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1412 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001413 if (bb->taken != NullBasicBlockId) {
1414 LOG(INFO) << " Taken branch: block " << bb->taken
1415 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001416 }
buzbee0d829482013-10-11 15:24:55 -07001417 if (bb->fall_through != NullBasicBlockId) {
1418 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1419 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001420 }
1421 }
1422}
1423
1424/*
1425 * Build an array of location records for the incoming arguments.
1426 * Note: one location record per word of arguments, with dummy
1427 * high-word loc for wide arguments. Also pull up any following
1428 * MOVE_RESULT and incorporate it into the invoke.
1429 */
1430CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001431 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001432 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001433 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001434 MIR* move_result_mir = FindMoveResult(bb, mir);
1435 if (move_result_mir == NULL) {
1436 info->result.location = kLocInvalid;
1437 } else {
1438 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001439 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1440 }
1441 info->num_arg_words = mir->ssa_rep->num_uses;
1442 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001443 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001444 for (int i = 0; i < info->num_arg_words; i++) {
1445 info->args[i] = GetRawSrc(mir, i);
1446 }
1447 info->opt_flags = mir->optimization_flags;
1448 info->type = type;
1449 info->is_range = is_range;
1450 info->index = mir->dalvikInsn.vB;
1451 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001452 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001453 return info;
1454}
1455
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001456// Allocate a new MIR.
1457MIR* MIRGraph::NewMIR() {
1458 MIR* mir = new (arena_) MIR();
1459 return mir;
1460}
1461
buzbee862a7602013-04-05 10:58:54 -07001462// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001463BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001464 BasicBlock* bb = new (arena_) BasicBlock();
1465
buzbee862a7602013-04-05 10:58:54 -07001466 bb->block_type = block_type;
1467 bb->id = block_id;
1468 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001469 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001470 (block_type == kExitBlock) ? 2048 : 2,
1471 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001472 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001473 block_id_map_.Put(block_id, block_id);
1474 return bb;
1475}
buzbee1fd33462013-03-25 13:40:45 -07001476
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001477void MIRGraph::InitializeConstantPropagation() {
1478 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001479 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001480}
1481
1482void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001483 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001484 int num_ssa_regs = GetNumSSARegs();
1485 use_counts_.Resize(num_ssa_regs + 32);
1486 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001487 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001488 for (int i = 0; i < num_ssa_regs; i++) {
1489 use_counts_.Insert(0);
1490 raw_use_counts_.Insert(0);
1491 }
1492}
1493
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001494void MIRGraph::SSATransformationStart() {
1495 DCHECK(temp_scoped_alloc_.get() == nullptr);
1496 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1497 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1498 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1499 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1500
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001501 // Update the maximum number of reachable blocks.
1502 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001503}
1504
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001505void MIRGraph::SSATransformationEnd() {
1506 // Verify the dataflow information after the pass.
1507 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1508 VerifyDataflow();
1509 }
1510
1511 temp_bit_vector_size_ = 0u;
1512 temp_bit_vector_ = nullptr;
1513 DCHECK(temp_scoped_alloc_.get() != nullptr);
1514 temp_scoped_alloc_.reset();
1515}
1516
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001517void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001518 // Clear the nodes.
1519 ClearAllVisitedFlags();
1520
1521 // Create the topological order if need be.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001522 if (topological_order_ == nullptr) {
1523 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, GetNumBlocks());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001524 }
1525 topological_order_->Reset();
1526
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001527 ScopedArenaAllocator allocator(&cu_->arena_stack);
1528 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1529 ScopedArenaVector<size_t> visited_cnt_values(GetNumBlocks(), 0u, allocator.Adapter());
1530
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001531 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1532 // also fill initial queue.
1533 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1534
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001535 size_t num_blocks = 0u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001536 while (true) {
1537 BasicBlock* bb = iterator.Next();
1538
1539 if (bb == nullptr) {
1540 break;
1541 }
1542
1543 if (bb->hidden == true) {
1544 continue;
1545 }
1546
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001547 num_blocks += 1u;
1548 size_t unvisited_predecessor_count = bb->predecessors->Size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001549
1550 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1551 // To process loops we should not wait for dominators.
1552 while (true) {
1553 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1554
1555 if (pred_bb == nullptr) {
1556 break;
1557 }
1558
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001559 // Skip the backward branch or hidden predecessor.
1560 if (pred_bb->hidden ||
1561 (pred_bb->dominators != nullptr && pred_bb->dominators->IsBitSet(bb->id))) {
1562 unvisited_predecessor_count -= 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001563 }
1564 }
1565
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001566 visited_cnt_values[bb->id] = unvisited_predecessor_count;
1567
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001568 // Add entry block to queue.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001569 if (unvisited_predecessor_count == 0) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001570 q.push(bb);
1571 }
1572 }
1573
Vladimir Markoe8ae8142014-07-08 18:06:45 +01001574 // We can get a cycle where none of the blocks dominates the other. Therefore don't
1575 // stop when the queue is empty, continue until we've processed all the blocks.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001576 AllNodesIterator candidate_iter(this); // For the empty queue case.
1577 while (num_blocks != 0u) {
1578 num_blocks -= 1u;
1579 BasicBlock* bb = nullptr;
1580 if (!q.empty()) {
1581 // Get top.
1582 bb = q.front();
1583 q.pop();
1584 } else {
1585 // Find some block we didn't visit yet that has at least one visited predecessor.
1586 while (bb == nullptr) {
1587 BasicBlock* candidate = candidate_iter.Next();
1588 DCHECK(candidate != nullptr);
1589 if (candidate->visited || candidate->hidden) {
1590 continue;
1591 }
1592 GrowableArray<BasicBlockId>::Iterator iter(candidate->predecessors);
1593 for (BasicBlock* pred_bb = GetBasicBlock(iter.Next()); pred_bb != nullptr;
1594 pred_bb = GetBasicBlock(iter.Next())) {
1595 if (!pred_bb->hidden && pred_bb->visited) {
1596 bb = candidate;
1597 break;
1598 }
1599 }
1600 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001601 }
1602
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001603 DCHECK_EQ(bb->hidden, false);
1604 DCHECK_EQ(bb->visited, false);
1605
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001606 // We've visited all the predecessors. So, we can visit bb.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001607 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001608
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001609 // Now add the basic block.
1610 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001611
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001612 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1613 ChildBlockIterator succIter(bb, this);
1614 BasicBlock* successor = succIter.Next();
1615 for ( ; successor != nullptr; successor = succIter.Next()) {
1616 if (successor->visited || successor->hidden) {
1617 continue;
1618 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001619
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001620 // one more predecessor was visited.
1621 DCHECK_NE(visited_cnt_values[successor->id], 0u);
1622 visited_cnt_values[successor->id] -= 1u;
1623 if (visited_cnt_values[successor->id] == 0u) {
1624 q.push(successor);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001625 }
1626 }
1627 }
1628}
1629
1630bool BasicBlock::IsExceptionBlock() const {
1631 if (block_type == kExceptionHandling) {
1632 return true;
1633 }
1634 return false;
1635}
1636
Wei Jin04f4d8a2014-05-29 18:04:29 -07001637bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1638 BasicBlock* target = GetBasicBlock(target_id);
1639
1640 if (source == nullptr || target == nullptr)
1641 return false;
1642
1643 int idx;
1644 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1645 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1646 if (bb == source)
1647 return true; // The block has been inserted by a suspend check before.
1648 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1649 return true;
1650 }
1651
1652 return false;
1653}
1654
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001655ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1656 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1657 visited_taken_(false), have_successors_(false) {
1658 // Check if we actually do have successors.
1659 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1660 have_successors_ = true;
1661 successor_iter_.Reset(basic_block_->successor_blocks);
1662 }
1663}
1664
1665BasicBlock* ChildBlockIterator::Next() {
1666 // We check if we have a basic block. If we don't we cannot get next child.
1667 if (basic_block_ == nullptr) {
1668 return nullptr;
1669 }
1670
1671 // If we haven't visited fallthrough, return that.
1672 if (visited_fallthrough_ == false) {
1673 visited_fallthrough_ = true;
1674
1675 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1676 if (result != nullptr) {
1677 return result;
1678 }
1679 }
1680
1681 // If we haven't visited taken, return that.
1682 if (visited_taken_ == false) {
1683 visited_taken_ = true;
1684
1685 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1686 if (result != nullptr) {
1687 return result;
1688 }
1689 }
1690
1691 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1692 if (have_successors_ == true) {
1693 // Get information about next successor block.
1694 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1695
1696 // If we don't have anymore successors, return nullptr.
1697 if (successor_block_info != nullptr) {
1698 return mir_graph_->GetBasicBlock(successor_block_info->block);
1699 }
1700 }
1701
1702 // We do not have anything.
1703 return nullptr;
1704}
1705
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001706BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1707 MIRGraph* mir_graph = c_unit->mir_graph.get();
1708 return Copy(mir_graph);
1709}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001710
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001711BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1712 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001713
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001714 // We don't do a memcpy style copy here because it would lead to a lot of things
1715 // to clean up. Let us do it by hand instead.
1716 // Copy in taken and fallthrough.
1717 result_bb->fall_through = fall_through;
1718 result_bb->taken = taken;
1719
1720 // Copy successor links if needed.
1721 ArenaAllocator* arena = mir_graph->GetArena();
1722
1723 result_bb->successor_block_list_type = successor_block_list_type;
1724 if (result_bb->successor_block_list_type != kNotUsed) {
1725 size_t size = successor_blocks->Size();
1726 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1727 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1728 while (true) {
1729 SuccessorBlockInfo* sbi_old = iterator.Next();
1730 if (sbi_old == nullptr) {
1731 break;
1732 }
1733 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1734 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1735 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001736 }
1737 }
1738
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001739 // Copy offset, method.
1740 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001741
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001742 // Now copy instructions.
1743 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1744 // Get a copy first.
1745 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001746
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001747 // Append it.
1748 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001749 }
1750
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001751 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001752}
1753
1754MIR* MIR::Copy(MIRGraph* mir_graph) {
1755 MIR* res = mir_graph->NewMIR();
1756 *res = *this;
1757
1758 // Remove links
1759 res->next = nullptr;
1760 res->bb = NullBasicBlockId;
1761 res->ssa_rep = nullptr;
1762
1763 return res;
1764}
1765
1766MIR* MIR::Copy(CompilationUnit* c_unit) {
1767 return Copy(c_unit->mir_graph.get());
1768}
1769
1770uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1771 // Default result.
1772 int res = 0;
1773
1774 // We are basically setting the iputs to their igets counterparts.
1775 switch (opcode) {
1776 case Instruction::IPUT:
1777 case Instruction::IPUT_OBJECT:
1778 case Instruction::IPUT_BOOLEAN:
1779 case Instruction::IPUT_BYTE:
1780 case Instruction::IPUT_CHAR:
1781 case Instruction::IPUT_SHORT:
1782 case Instruction::IPUT_QUICK:
1783 case Instruction::IPUT_OBJECT_QUICK:
1784 case Instruction::APUT:
1785 case Instruction::APUT_OBJECT:
1786 case Instruction::APUT_BOOLEAN:
1787 case Instruction::APUT_BYTE:
1788 case Instruction::APUT_CHAR:
1789 case Instruction::APUT_SHORT:
1790 case Instruction::SPUT:
1791 case Instruction::SPUT_OBJECT:
1792 case Instruction::SPUT_BOOLEAN:
1793 case Instruction::SPUT_BYTE:
1794 case Instruction::SPUT_CHAR:
1795 case Instruction::SPUT_SHORT:
1796 // Skip the VR containing what to store.
1797 res = 1;
1798 break;
1799 case Instruction::IPUT_WIDE:
1800 case Instruction::IPUT_WIDE_QUICK:
1801 case Instruction::APUT_WIDE:
1802 case Instruction::SPUT_WIDE:
1803 // Skip the two VRs containing what to store.
1804 res = 2;
1805 break;
1806 default:
1807 // Do nothing in the general case.
1808 break;
1809 }
1810
1811 return res;
1812}
1813
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001814/**
1815 * @brief Given a decoded instruction, it checks whether the instruction
1816 * sets a constant and if it does, more information is provided about the
1817 * constant being set.
1818 * @param ptr_value pointer to a 64-bit holder for the constant.
1819 * @param wide Updated by function whether a wide constant is being set by bytecode.
1820 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1821 */
1822bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1823 bool sets_const = true;
1824 int64_t value = vB;
1825
1826 DCHECK(ptr_value != nullptr);
1827 DCHECK(wide != nullptr);
1828
1829 switch (opcode) {
1830 case Instruction::CONST_4:
1831 case Instruction::CONST_16:
1832 case Instruction::CONST:
1833 *wide = false;
1834 value <<= 32; // In order to get the sign extend.
1835 value >>= 32;
1836 break;
1837 case Instruction::CONST_HIGH16:
1838 *wide = false;
1839 value <<= 48; // In order to get the sign extend.
1840 value >>= 32;
1841 break;
1842 case Instruction::CONST_WIDE_16:
1843 case Instruction::CONST_WIDE_32:
1844 *wide = true;
1845 value <<= 32; // In order to get the sign extend.
1846 value >>= 32;
1847 break;
1848 case Instruction::CONST_WIDE:
1849 *wide = true;
1850 value = vB_wide;
1851 break;
1852 case Instruction::CONST_WIDE_HIGH16:
1853 *wide = true;
1854 value <<= 48; // In order to get the sign extend.
1855 break;
1856 default:
1857 sets_const = false;
1858 break;
1859 }
1860
1861 if (sets_const) {
1862 *ptr_value = value;
1863 }
1864
1865 return sets_const;
1866}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001867
1868void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1869 // Reset flags for all MIRs in bb.
1870 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1871 mir->optimization_flags &= (~reset_flags);
1872 }
1873}
1874
1875void BasicBlock::Hide(CompilationUnit* c_unit) {
1876 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1877 block_type = kDalvikByteCode;
1878
1879 // Mark it as hidden.
1880 hidden = true;
1881
1882 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1883 // are updated to know that they no longer have a parent.
1884 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1885 mir->bb = NullBasicBlockId;
1886 }
1887 first_mir_insn = nullptr;
1888 last_mir_insn = nullptr;
1889
1890 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1891
1892 MIRGraph* mir_graph = c_unit->mir_graph.get();
1893 while (true) {
1894 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1895 if (pred_bb == nullptr) {
1896 break;
1897 }
1898
1899 // Sadly we have to go through the children by hand here.
1900 pred_bb->ReplaceChild(id, NullBasicBlockId);
1901 }
1902
1903 // Iterate through children of bb we are hiding.
1904 ChildBlockIterator successorChildIter(this, mir_graph);
1905
1906 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1907 // Replace child with null child.
1908 childPtr->predecessors->Delete(id);
1909 }
1910}
1911
1912bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1913 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1914 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1915 // then it is not live out of this BB.
1916 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1917
1918 int last_ssa_reg = -1;
1919
1920 // Walk through the MIRs backwards.
1921 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1922 // Get ssa rep.
1923 SSARepresentation *ssa_rep = mir->ssa_rep;
1924
1925 // Go through the defines for this MIR.
1926 for (int i = 0; i < ssa_rep->num_defs; i++) {
1927 DCHECK(ssa_rep->defs != nullptr);
1928
1929 // Get the ssa reg.
1930 int def_ssa_reg = ssa_rep->defs[i];
1931
1932 // Get dalvik reg.
1933 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1934
1935 // Compare dalvik regs.
1936 if (dalvik_reg == def_dalvik_reg) {
1937 // We found a def of the register that we are being asked about.
1938 // Remember it.
1939 last_ssa_reg = def_ssa_reg;
1940 }
1941 }
1942 }
1943
1944 if (last_ssa_reg == -1) {
1945 // If we get to this point we couldn't find a define of register user asked about.
1946 // Let's assume the user knows what he's doing so we can be safe and say that if we
1947 // couldn't find a def, it is live out.
1948 return true;
1949 }
1950
1951 // If it is not -1, we found a match, is it ssa_reg?
1952 return (ssa_reg == last_ssa_reg);
1953}
1954
1955bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1956 // We need to check taken, fall_through, and successor_blocks to replace.
1957 bool found = false;
1958 if (taken == old_bb) {
1959 taken = new_bb;
1960 found = true;
1961 }
1962
1963 if (fall_through == old_bb) {
1964 fall_through = new_bb;
1965 found = true;
1966 }
1967
1968 if (successor_block_list_type != kNotUsed) {
1969 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1970 while (true) {
1971 SuccessorBlockInfo* successor_block_info = iterator.Next();
1972 if (successor_block_info == nullptr) {
1973 break;
1974 }
1975 if (successor_block_info->block == old_bb) {
1976 successor_block_info->block = new_bb;
1977 found = true;
1978 }
1979 }
1980 }
1981
1982 return found;
1983}
1984
1985void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1986 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1987 bool found = false;
1988
1989 while (true) {
1990 BasicBlockId pred_bb_id = iterator.Next();
1991
1992 if (pred_bb_id == NullBasicBlockId) {
1993 break;
1994 }
1995
1996 if (pred_bb_id == old_parent) {
1997 size_t idx = iterator.GetIndex() - 1;
1998 predecessors->Put(idx, new_parent);
1999 found = true;
2000 break;
2001 }
2002 }
2003
2004 // If not found, add it.
2005 if (found == false) {
2006 predecessors->Insert(new_parent);
2007 }
2008}
2009
2010// Create a new basic block with block_id as num_blocks_ that is
2011// post-incremented.
2012BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2013 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2014 block_list_.Insert(res);
2015 return res;
2016}
2017
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002018void MIRGraph::CalculateBasicBlockInformation() {
2019 PassDriverMEPostOpt driver(cu_);
2020 driver.Launch();
2021}
2022
2023void MIRGraph::InitializeBasicBlockData() {
2024 num_blocks_ = block_list_.Size();
2025}
2026
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002027} // namespace art