blob: 574b6ea66fffab91b5dc0b736b601f0e27ca9405 [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 Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070023#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070026#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010027#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000030#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070031#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010032#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000033
buzbee311ca162013-02-28 15:56:43 -080034namespace art {
35
36#define MAX_PATTERN_LEN 5
37
buzbee1fd33462013-03-25 13:40:45 -070038const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
39 "Phi",
40 "Copy",
41 "FusedCmplFloat",
42 "FusedCmpgFloat",
43 "FusedCmplDouble",
44 "FusedCmpgDouble",
45 "FusedCmpLong",
46 "Nop",
47 "OpNullCheck",
48 "OpRangeCheck",
49 "OpDivZeroCheck",
50 "Check1",
51 "Check2",
52 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040053 "ConstVector",
54 "MoveVector",
55 "PackedMultiply",
56 "PackedAddition",
57 "PackedSubtract",
58 "PackedShiftLeft",
59 "PackedSignedShiftRight",
60 "PackedUnsignedShiftRight",
61 "PackedAnd",
62 "PackedOr",
63 "PackedXor",
64 "PackedAddReduce",
65 "PackedReduce",
66 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070067 "ReserveVectorRegisters",
68 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070069};
70
buzbee862a7602013-04-05 10:58:54 -070071MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070072 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010073 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070074 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080075 ssa_base_vregs_(NULL),
76 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080077 vreg_to_ssa_map_(NULL),
78 ssa_last_defs_(NULL),
79 is_constant_v_(NULL),
80 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070081 use_counts_(arena, 256, kGrowableArrayMisc),
82 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080083 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070084 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070085 dfs_order_(NULL),
86 dfs_post_order_(NULL),
87 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070088 topological_order_(nullptr),
Vladimir Marko55fff042014-07-10 12:42:52 +010089 topological_order_loop_ends_(nullptr),
90 topological_order_indexes_(nullptr),
91 topological_order_loop_head_stack_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080092 i_dom_list_(NULL),
93 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000094 temp_scoped_alloc_(),
95 temp_insn_data_(nullptr),
96 temp_bit_vector_size_(0u),
97 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +010098 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -070099 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -0800100 try_block_addr_(NULL),
101 entry_block_(NULL),
102 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800103 num_blocks_(0),
104 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700105 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100106 m_units_(arena->Adapter()),
107 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800108 current_method_(kInvalidEntry),
109 current_offset_(kInvalidEntry),
110 def_count_(0),
111 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700112 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100113 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700114 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700115 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
116 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700117 arena_(arena),
118 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800119 forward_branches_(0),
120 compiler_temps_(arena, 6, kGrowableArrayMisc),
121 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800122 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000123 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000124 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000125 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000126 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700127 method_lowering_infos_(arena, 0u),
128 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700129 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800130 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
131 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800132}
133
Ian Rogers6282dc12013-04-18 15:54:02 -0700134MIRGraph::~MIRGraph() {
135 STLDeleteElements(&m_units_);
136}
137
buzbee311ca162013-02-28 15:56:43 -0800138/*
139 * Parse an instruction, return the length of the instruction
140 */
Ian Rogers29a26482014-05-02 15:27:29 -0700141int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
142 const Instruction* inst = Instruction::At(code_ptr);
143 decoded_instruction->opcode = inst->Opcode();
144 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
145 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
146 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
147 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
148 if (inst->HasVarArgs()) {
149 inst->GetVarArgs(decoded_instruction->arg);
150 }
151 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800152}
153
154
155/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700156BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700157 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700158 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800159 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700160 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800161 while (insn) {
162 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700163 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800164 insn = insn->next;
165 }
166 if (insn == NULL) {
167 LOG(FATAL) << "Break split failed";
168 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700169 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700170 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800171
172 bottom_block->start_offset = code_offset;
173 bottom_block->first_mir_insn = insn;
174 bottom_block->last_mir_insn = orig_block->last_mir_insn;
175
Junmo Park90223cc2014-08-04 18:51:21 +0900176 /* If this block was terminated by a return, conditional branch or throw,
177 * the flag needs to go with the bottom block
178 */
buzbee311ca162013-02-28 15:56:43 -0800179 bottom_block->terminated_by_return = orig_block->terminated_by_return;
180 orig_block->terminated_by_return = false;
181
Junmo Park90223cc2014-08-04 18:51:21 +0900182 bottom_block->conditional_branch = orig_block->conditional_branch;
183 orig_block->conditional_branch = false;
184
185 bottom_block->explicit_throw = orig_block->explicit_throw;
186 orig_block->explicit_throw = false;
187
buzbee311ca162013-02-28 15:56:43 -0800188 /* Handle the taken path */
189 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700190 if (bottom_block->taken != NullBasicBlockId) {
191 orig_block->taken = NullBasicBlockId;
192 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
193 bb_taken->predecessors->Delete(orig_block->id);
194 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800195 }
196
197 /* Handle the fallthrough path */
198 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700199 orig_block->fall_through = bottom_block->id;
200 bottom_block->predecessors->Insert(orig_block->id);
201 if (bottom_block->fall_through != NullBasicBlockId) {
202 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
203 bb_fall_through->predecessors->Delete(orig_block->id);
204 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800205 }
206
207 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700208 if (orig_block->successor_block_list_type != kNotUsed) {
209 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
210 bottom_block->successor_blocks = orig_block->successor_blocks;
211 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700212 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700213 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800214 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700215 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700216 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700217 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700218 if (bb != nullptr) {
219 bb->predecessors->Delete(orig_block->id);
220 bb->predecessors->Insert(bottom_block->id);
221 }
buzbee311ca162013-02-28 15:56:43 -0800222 }
223 }
224
buzbee0d829482013-10-11 15:24:55 -0700225 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700226 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800227
buzbee311ca162013-02-28 15:56:43 -0800228 /*
229 * Update the immediate predecessor block pointer so that outgoing edges
230 * can be applied to the proper block.
231 */
232 if (immed_pred_block_p) {
233 DCHECK_EQ(*immed_pred_block_p, orig_block);
234 *immed_pred_block_p = bottom_block;
235 }
buzbeeb48819d2013-09-14 16:15:25 -0700236
237 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000238 DCHECK(insn != nullptr);
239 DCHECK(insn != orig_block->first_mir_insn);
240 DCHECK(insn == bottom_block->first_mir_insn);
241 DCHECK_EQ(insn->offset, bottom_block->start_offset);
242 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700243 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000244 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
245 MIR* p = insn;
246 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
247 while (p != bottom_block->last_mir_insn) {
248 p = p->next;
249 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700250 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700251 int opcode = p->dalvikInsn.opcode;
252 /*
253 * Some messiness here to ensure that we only enter real opcodes and only the
254 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000255 * CHECK and work portions. Since the 2nd half of a split operation is always
256 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700257 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700258 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000259 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700260 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
261 }
buzbeeb48819d2013-09-14 16:15:25 -0700262 }
263
buzbee311ca162013-02-28 15:56:43 -0800264 return bottom_block;
265}
266
267/*
268 * Given a code offset, find out the block that starts with it. If the offset
269 * is in the middle of an existing block, split it into two. If immed_pred_block_p
270 * is not non-null and is the block being split, update *immed_pred_block_p to
271 * point to the bottom block so that outgoing edges can be set up properly
272 * (by the caller)
273 * Utilizes a map for fast lookup of the typical cases.
274 */
buzbee0d829482013-10-11 15:24:55 -0700275BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700276 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700277 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800278 return NULL;
279 }
buzbeeb48819d2013-09-14 16:15:25 -0700280
281 int block_id = dex_pc_to_block_map_.Get(code_offset);
282 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
283
284 if ((bb != NULL) && (bb->start_offset == code_offset)) {
285 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700286 return bb;
287 }
buzbee311ca162013-02-28 15:56:43 -0800288
buzbeeb48819d2013-09-14 16:15:25 -0700289 // No direct hit.
290 if (!create) {
291 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800292 }
293
buzbeeb48819d2013-09-14 16:15:25 -0700294 if (bb != NULL) {
295 // The target exists somewhere in an existing block.
296 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
297 }
298
299 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700300 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
301 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800302 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700303 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800304 return bb;
305}
306
buzbeeb48819d2013-09-14 16:15:25 -0700307
buzbee311ca162013-02-28 15:56:43 -0800308/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700309void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800310 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700311 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800312
313 if (tries_size == 0) {
314 return;
315 }
316
317 for (int i = 0; i < tries_size; i++) {
318 const DexFile::TryItem* pTry =
319 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700320 DexOffset start_offset = pTry->start_addr_;
321 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800322 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700323 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800324 }
325 }
326
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700327 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800328 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
329 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
330 for (uint32_t idx = 0; idx < handlers_size; idx++) {
331 CatchHandlerIterator iterator(handlers_ptr);
332 for (; iterator.HasNext(); iterator.Next()) {
333 uint32_t address = iterator.GetHandlerAddress();
334 FindBlock(address, false /* split */, true /*create*/,
335 /* immed_pred_block_p */ NULL);
336 }
337 handlers_ptr = iterator.EndDataPointer();
338 }
339}
340
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100341bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
342 NarrowDexOffset catch_offset) {
343 // Catches for monitor-exit during stack unwinding have the pattern
344 // move-exception (move)* (goto)? monitor-exit throw
345 // In the currently generated dex bytecode we see these catching a bytecode range including
346 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
347 // it's the case for a given monitor-exit and catch block so that we can ignore it.
348 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
349 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
350 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700351 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100352 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
353 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700354 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100355 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
356 if (check_insn->VRegA_11x() == monitor_reg) {
357 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
358 return false;
359 }
360 check_insn = check_insn->Next();
361 while (true) {
362 int dest = -1;
363 bool wide = false;
364 switch (check_insn->Opcode()) {
365 case Instruction::MOVE_WIDE:
366 wide = true;
367 // Intentional fall-through.
368 case Instruction::MOVE_OBJECT:
369 case Instruction::MOVE:
370 dest = check_insn->VRegA_12x();
371 break;
372
373 case Instruction::MOVE_WIDE_FROM16:
374 wide = true;
375 // Intentional fall-through.
376 case Instruction::MOVE_OBJECT_FROM16:
377 case Instruction::MOVE_FROM16:
378 dest = check_insn->VRegA_22x();
379 break;
380
381 case Instruction::MOVE_WIDE_16:
382 wide = true;
383 // Intentional fall-through.
384 case Instruction::MOVE_OBJECT_16:
385 case Instruction::MOVE_16:
386 dest = check_insn->VRegA_32x();
387 break;
388
389 case Instruction::GOTO:
390 case Instruction::GOTO_16:
391 case Instruction::GOTO_32:
392 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
393 // Intentional fall-through.
394 default:
395 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
396 check_insn->VRegA_11x() == monitor_reg;
397 }
398
399 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
400 return false;
401 }
402
403 check_insn = check_insn->Next();
404 }
405}
406
buzbee311ca162013-02-28 15:56:43 -0800407/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700408BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
409 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700410 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700411 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800412 switch (insn->dalvikInsn.opcode) {
413 case Instruction::GOTO:
414 case Instruction::GOTO_16:
415 case Instruction::GOTO_32:
416 target += insn->dalvikInsn.vA;
417 break;
418 case Instruction::IF_EQ:
419 case Instruction::IF_NE:
420 case Instruction::IF_LT:
421 case Instruction::IF_GE:
422 case Instruction::IF_GT:
423 case Instruction::IF_LE:
424 cur_block->conditional_branch = true;
425 target += insn->dalvikInsn.vC;
426 break;
427 case Instruction::IF_EQZ:
428 case Instruction::IF_NEZ:
429 case Instruction::IF_LTZ:
430 case Instruction::IF_GEZ:
431 case Instruction::IF_GTZ:
432 case Instruction::IF_LEZ:
433 cur_block->conditional_branch = true;
434 target += insn->dalvikInsn.vB;
435 break;
436 default:
437 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
438 }
buzbeeb48819d2013-09-14 16:15:25 -0700439 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700440 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800441 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700442 cur_block->taken = taken_block->id;
443 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800444
445 /* Always terminate the current block for conditional branches */
446 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700447 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800448 /*
449 * If the method is processed
450 * in sequential order from the
451 * beginning, we don't need to
452 * specify split for continue
453 * blocks. However, this
454 * routine can be called by
455 * compileLoop, which starts
456 * parsing the method from an
457 * arbitrary address in the
458 * method body.
459 */
460 true,
461 /* create */
462 true,
463 /* immed_pred_block_p */
464 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700465 cur_block->fall_through = fallthrough_block->id;
466 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800467 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700468 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800469 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800470 }
471 return cur_block;
472}
473
474/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800475BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
476 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800477 const uint16_t* switch_data =
478 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
479 int size;
480 const int* keyTable;
481 const int* target_table;
482 int i;
483 int first_key;
484
485 /*
486 * Packed switch data format:
487 * ushort ident = 0x0100 magic value
488 * ushort size number of entries in the table
489 * int first_key first (and lowest) switch case value
490 * int targets[size] branch targets, relative to switch opcode
491 *
492 * Total size is (4+size*2) 16-bit code units.
493 */
494 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
495 DCHECK_EQ(static_cast<int>(switch_data[0]),
496 static_cast<int>(Instruction::kPackedSwitchSignature));
497 size = switch_data[1];
498 first_key = switch_data[2] | (switch_data[3] << 16);
499 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700500 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800501 /*
502 * Sparse switch data format:
503 * ushort ident = 0x0200 magic value
504 * ushort size number of entries in the table; > 0
505 * int keys[size] keys, sorted low-to-high; 32-bit aligned
506 * int targets[size] branch targets, relative to switch opcode
507 *
508 * Total size is (2+size*4) 16-bit code units.
509 */
510 } else {
511 DCHECK_EQ(static_cast<int>(switch_data[0]),
512 static_cast<int>(Instruction::kSparseSwitchSignature));
513 size = switch_data[1];
514 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
515 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700516 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800517 }
518
buzbee0d829482013-10-11 15:24:55 -0700519 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800520 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700521 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800522 }
buzbee0d829482013-10-11 15:24:55 -0700523 cur_block->successor_block_list_type =
524 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
525 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700526 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800527
528 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700529 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800530 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700531 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700532 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000533 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700534 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800535 successor_block_info->key =
536 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
537 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700538 cur_block->successor_blocks->Insert(successor_block_info);
539 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800540 }
541
542 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700543 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
544 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700545 cur_block->fall_through = fallthrough_block->id;
546 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800547 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800548}
549
550/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700551BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
552 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700553 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700554 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800555 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
556 bool build_all_edges =
557 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800558
559 /* In try block */
560 if (in_try_block) {
561 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
562
buzbee0d829482013-10-11 15:24:55 -0700563 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800564 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
565 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700566 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800567 }
568
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700569 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700570 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800571 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100572 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
573 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
574 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
575 continue;
576 }
577 if (cur_block->successor_block_list_type == kNotUsed) {
578 cur_block->successor_block_list_type = kCatch;
579 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
580 arena_, 2, kGrowableArraySuccessorBlocks);
581 }
buzbee311ca162013-02-28 15:56:43 -0800582 catch_block->catch_entry = true;
583 if (kIsDebugBuild) {
584 catches_.insert(catch_block->start_offset);
585 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700586 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000587 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700588 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800589 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700590 cur_block->successor_blocks->Insert(successor_block_info);
591 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800592 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100593 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
594 }
595 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700596 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700597 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700598 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800599 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700600 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800601 }
602
buzbee17189ac2013-11-08 11:07:02 -0800603 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800604 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700605 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700606 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800607 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
608 /* immed_pred_block_p */ NULL);
609 }
610 if (!in_try_block) {
611 // Don't split a THROW that can't rethrow - we're done.
612 return cur_block;
613 }
614 }
615
buzbee17189ac2013-11-08 11:07:02 -0800616 if (!build_all_edges) {
617 /*
618 * Even though there is an exception edge here, control cannot return to this
619 * method. Thus, for the purposes of dataflow analysis and optimization, we can
620 * ignore the edge. Doing this reduces compile time, and increases the scope
621 * of the basic-block level optimization pass.
622 */
623 return cur_block;
624 }
625
buzbee311ca162013-02-28 15:56:43 -0800626 /*
627 * Split the potentially-throwing instruction into two parts.
628 * The first half will be a pseudo-op that captures the exception
629 * edges and terminates the basic block. It always falls through.
630 * Then, create a new basic block that begins with the throwing instruction
631 * (minus exceptions). Note: this new basic block must NOT be entered into
632 * the block_map. If the potentially-throwing instruction is the target of a
633 * future branch, we need to find the check psuedo half. The new
634 * basic block containing the work portion of the instruction should
635 * only be entered via fallthrough from the block containing the
636 * pseudo exception edge MIR. Note also that this new block is
637 * not automatically terminated after the work portion, and may
638 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700639 *
640 * Note also that the dex_pc_to_block_map_ entry for the potentially
641 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800642 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700643 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700644 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800645 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700646 cur_block->fall_through = new_block->id;
647 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700648 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800649 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700650 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700651 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800652 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700653 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800654 return new_block;
655}
656
657/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
658void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700659 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700660 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800661 current_code_item_ = code_item;
662 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
663 current_method_ = m_units_.size();
664 current_offset_ = 0;
665 // TODO: will need to snapshot stack image and use that as the mir context identification.
666 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000667 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
668 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800669 const uint16_t* code_ptr = current_code_item_->insns_;
670 const uint16_t* code_end =
671 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
672
673 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700674 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700675 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700676 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 -0700677
buzbee311ca162013-02-28 15:56:43 -0800678 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700679 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
680 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800681
682 // If this is the first method, set up default entry and exit blocks.
683 if (current_method_ == 0) {
684 DCHECK(entry_block_ == NULL);
685 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700686 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700687 // Use id 0 to represent a null block.
688 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
689 DCHECK_EQ(null_block->id, NullBasicBlockId);
690 null_block->hidden = true;
691 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700692 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700693 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700694 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700695 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800696 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
697 cu_->dex_file = &dex_file;
698 cu_->class_def_idx = class_def_idx;
699 cu_->method_idx = method_idx;
700 cu_->access_flags = access_flags;
701 cu_->invoke_type = invoke_type;
702 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
703 cu_->num_ins = current_code_item_->ins_size_;
704 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
705 cu_->num_outs = current_code_item_->outs_size_;
706 cu_->num_dalvik_registers = current_code_item_->registers_size_;
707 cu_->insns = current_code_item_->insns_;
708 cu_->code_item = current_code_item_;
709 } else {
710 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
711 /*
712 * Will need to manage storage for ins & outs, push prevous state and update
713 * insert point.
714 */
715 }
716
717 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700718 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700719 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800720 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700721 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700722 // TODO: for inlining support, insert at the insert point rather than entry block.
723 entry_block_->fall_through = cur_block->id;
724 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800725
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000726 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800727 ProcessTryCatchBlocks();
728
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000729 uint64_t merged_df_flags = 0u;
730
buzbee311ca162013-02-28 15:56:43 -0800731 /* Parse all instructions and put them into containing basic blocks */
732 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700733 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800734 insn->offset = current_offset_;
735 insn->m_unit_index = current_method_;
736 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800737 Instruction::Code opcode = insn->dalvikInsn.opcode;
738 if (opcode_count_ != NULL) {
739 opcode_count_[static_cast<int>(opcode)]++;
740 }
741
buzbee311ca162013-02-28 15:56:43 -0800742 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800743 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800744
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700745 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000746 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800747
748 if (df_flags & DF_HAS_DEFS) {
749 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
750 }
751
buzbee1da1e2f2013-11-15 13:37:01 -0800752 if (df_flags & DF_LVN) {
753 cur_block->use_lvn = true; // Run local value numbering on this basic block.
754 }
755
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700756 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700757 if (opcode == Instruction::NOP) {
758 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
759 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
760 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
761 uint16_t following_raw_instruction = code_ptr[1];
762 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
763 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
764 (following_raw_instruction == Instruction::kArrayDataSignature)) {
765 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
766 }
767 }
768 if (width == 1) {
769 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700770 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700771 } else {
buzbee0d829482013-10-11 15:24:55 -0700772 DCHECK(cur_block->fall_through == NullBasicBlockId);
773 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700774 // Unreachable instruction, mark for no continuation.
775 flags &= ~Instruction::kContinue;
776 }
777 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700778 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700779 }
780
buzbeeb48819d2013-09-14 16:15:25 -0700781 // Associate the starting dex_pc for this opcode with its containing basic block.
782 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
783
buzbee27247762013-07-28 12:03:58 -0700784 code_ptr += width;
785
buzbee311ca162013-02-28 15:56:43 -0800786 if (flags & Instruction::kBranch) {
787 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
788 width, flags, code_ptr, code_end);
789 } else if (flags & Instruction::kReturn) {
790 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700791 cur_block->fall_through = exit_block_->id;
792 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800793 /*
794 * Terminate the current block if there are instructions
795 * afterwards.
796 */
797 if (code_ptr < code_end) {
798 /*
799 * Create a fallthrough block for real instructions
800 * (incl. NOP).
801 */
buzbee27247762013-07-28 12:03:58 -0700802 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
803 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800804 }
805 } else if (flags & Instruction::kThrow) {
806 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
807 code_ptr, code_end);
808 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800809 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800810 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700811 if (verify_flags & Instruction::kVerifyVarArgRange ||
812 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800813 /*
814 * The Quick backend's runtime model includes a gap between a method's
815 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
816 * which spans the gap is somewhat complicated, and should not happen
817 * in normal usage of dx. Punt to the interpreter.
818 */
819 int first_reg_in_range = insn->dalvikInsn.vC;
820 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
821 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
822 punt_to_interpreter_ = true;
823 }
824 }
buzbee311ca162013-02-28 15:56:43 -0800825 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700826 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800827 false, /* immed_pred_block_p */ NULL);
828 if (next_block) {
829 /*
830 * The next instruction could be the target of a previously parsed
831 * forward branch so a block is already created. If the current
832 * instruction is not an unconditional branch, connect them through
833 * the fall-through link.
834 */
buzbee0d829482013-10-11 15:24:55 -0700835 DCHECK(cur_block->fall_through == NullBasicBlockId ||
836 GetBasicBlock(cur_block->fall_through) == next_block ||
837 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800838
buzbee0d829482013-10-11 15:24:55 -0700839 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
840 cur_block->fall_through = next_block->id;
841 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800842 }
843 cur_block = next_block;
844 }
845 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000846 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000847
buzbee311ca162013-02-28 15:56:43 -0800848 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
849 DumpCFG("/sdcard/1_post_parse_cfg/", true);
850 }
851
852 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700853 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800854 }
855}
856
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700857void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800858 DCHECK(opcode_count_ != NULL);
859 LOG(INFO) << "Opcode Count";
860 for (int i = 0; i < kNumPackedOpcodes; i++) {
861 if (opcode_count_[i] != 0) {
862 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
863 << " " << opcode_count_[i];
864 }
865 }
866}
867
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700868uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
869 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
870 return oat_data_flow_attributes_[opcode];
871}
872
873uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
874 DCHECK(mir != nullptr);
875 Instruction::Code opcode = mir->dalvikInsn.opcode;
876 return GetDataFlowAttributes(opcode);
877}
878
buzbee311ca162013-02-28 15:56:43 -0800879// TODO: use a configurable base prefix, and adjust callers to supply pass name.
880/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800881void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800882 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700883 static AtomicInteger cnt(0);
884
885 // Increment counter to get a unique file number.
886 cnt++;
887
buzbee311ca162013-02-28 15:56:43 -0800888 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
889 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700890 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800891 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700892 suffix == nullptr ? "" : suffix,
893 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800894 file = fopen(fname.c_str(), "w");
895 if (file == NULL) {
896 return;
897 }
898 fprintf(file, "digraph G {\n");
899
900 fprintf(file, " rankdir=TB\n");
901
902 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
903 int idx;
904
905 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700906 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700907 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700908 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800909 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700910 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800911 if (bb->block_type == kEntryBlock) {
912 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
913 } else if (bb->block_type == kExitBlock) {
914 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
915 } else if (bb->block_type == kDalvikByteCode) {
916 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
917 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700918 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800919 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
920 bb->first_mir_insn ? " | " : " ");
921 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
922 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400923 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
924 if (opcode == kMirOpConstVector) {
925 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
926 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
927 mir->dalvikInsn.vA,
928 mir->dalvikInsn.vB,
929 mir->dalvikInsn.arg[0],
930 mir->dalvikInsn.arg[1],
931 mir->dalvikInsn.arg[2],
932 mir->dalvikInsn.arg[3],
933 mir->next ? " | " : " ");
934 } else {
935 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
936 extended_mir_op_names_[opcode - kMirOpFirst],
937 mir->dalvikInsn.vA,
938 mir->dalvikInsn.vB,
939 mir->dalvikInsn.vC,
940 mir->next ? " | " : " ");
941 }
942 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700943 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400944 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700945 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
946 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400947 extended_mir_op_names_[opcode - kMirOpFirst],
948 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
949 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700950 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400951 mir->next ? " | " : " ");
952 }
buzbee311ca162013-02-28 15:56:43 -0800953 }
954 fprintf(file, " }\"];\n\n");
955 } else if (bb->block_type == kExceptionHandling) {
956 char block_name[BLOCK_NAME_LEN];
957
958 GetBlockName(bb, block_name);
959 fprintf(file, " %s [shape=invhouse];\n", block_name);
960 }
961
962 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
963
buzbee0d829482013-10-11 15:24:55 -0700964 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800965 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700966 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800967 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
968 block_name1, block_name2);
969 }
buzbee0d829482013-10-11 15:24:55 -0700970 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800971 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700972 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800973 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
974 }
975
buzbee0d829482013-10-11 15:24:55 -0700976 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800977 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
978 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700979 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
980 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700981 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800982
983 int succ_id = 0;
984 while (true) {
985 if (successor_block_info == NULL) break;
986
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700987 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700988 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800989
990 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
991 succ_id++,
992 successor_block_info->key,
993 dest_block->start_offset,
994 (next_successor_block_info != NULL) ? " | " : " ");
995
996 successor_block_info = next_successor_block_info;
997 }
998 fprintf(file, " }\"];\n\n");
999
1000 GetBlockName(bb, block_name1);
1001 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1002 block_name1, bb->start_offset, bb->id);
1003
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001004 // Link the successor pseudo-block with all of its potential targets.
1005 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001006
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001007 succ_id = 0;
1008 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001009 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001010 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001011
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001012 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001013
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001014 GetBlockName(dest_block, block_name2);
1015 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1016 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001017 }
1018 }
1019 fprintf(file, "\n");
1020
1021 if (cu_->verbose) {
1022 /* Display the dominator tree */
1023 GetBlockName(bb, block_name1);
1024 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1025 block_name1, block_name1);
1026 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001027 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001028 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1029 }
1030 }
1031 }
1032 fprintf(file, "}\n");
1033 fclose(file);
1034}
1035
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001036/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001037void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001038 // Insert it after the last MIR.
1039 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001040}
1041
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001042void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1043 // Insert it after the last MIR.
1044 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1045}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001046
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001047void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1048 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1049 MIR* new_mir = *it;
1050
1051 // Add a copy of each MIR.
1052 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1053 }
buzbee1fd33462013-03-25 13:40:45 -07001054}
1055
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001056/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001057void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001058 InsertMIRListAfter(current_mir, new_mir, new_mir);
1059}
buzbee1fd33462013-03-25 13:40:45 -07001060
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001061void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1062 // If no MIR, we are done.
1063 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1064 return;
buzbee1fd33462013-03-25 13:40:45 -07001065 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001066
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001067 // If insert_after is null, assume BB is empty.
1068 if (insert_after == nullptr) {
1069 first_mir_insn = first_list_mir;
1070 last_mir_insn = last_list_mir;
1071 last_list_mir->next = nullptr;
1072 } else {
1073 MIR* after_list = insert_after->next;
1074 insert_after->next = first_list_mir;
1075 last_list_mir->next = after_list;
1076 if (after_list == nullptr) {
1077 last_mir_insn = last_list_mir;
1078 }
1079 }
1080
1081 // Set this BB to be the basic block of the MIRs.
1082 MIR* last = last_list_mir->next;
1083 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1084 mir->bb = id;
1085 }
1086}
1087
1088/* Insert an MIR instruction to the head of a basic block. */
1089void BasicBlock::PrependMIR(MIR* mir) {
1090 InsertMIRListBefore(first_mir_insn, mir, mir);
1091}
1092
1093void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1094 // Insert it before the first MIR.
1095 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1096}
1097
1098void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1099 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1100 MIR* mir = *it;
1101
1102 InsertMIRListBefore(first_mir_insn, mir, mir);
1103 }
1104}
1105
1106/* Insert a MIR instruction before the specified MIR. */
1107void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1108 // Insert as a single element list.
1109 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001110}
1111
1112MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1113 MIR* current = first_mir_insn;
1114
1115 while (current != nullptr) {
1116 MIR* next = current->next;
1117
1118 if (next == mir) {
1119 return current;
1120 }
1121
1122 current = next;
1123 }
1124
1125 return nullptr;
1126}
1127
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001128void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1129 // If no MIR, we are done.
1130 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1131 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001132 }
1133
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001134 // If insert_before is null, assume BB is empty.
1135 if (insert_before == nullptr) {
1136 first_mir_insn = first_list_mir;
1137 last_mir_insn = last_list_mir;
1138 last_list_mir->next = nullptr;
1139 } else {
1140 if (first_mir_insn == insert_before) {
1141 last_list_mir->next = first_mir_insn;
1142 first_mir_insn = first_list_mir;
1143 } else {
1144 // Find the preceding MIR.
1145 MIR* before_list = FindPreviousMIR(insert_before);
1146 DCHECK(before_list != nullptr);
1147 before_list->next = first_list_mir;
1148 last_list_mir->next = insert_before;
1149 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001150 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001151
1152 // Set this BB to be the basic block of the MIRs.
1153 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1154 mir->bb = id;
1155 }
1156}
1157
1158bool BasicBlock::RemoveMIR(MIR* mir) {
1159 // Remove as a single element list.
1160 return RemoveMIRList(mir, mir);
1161}
1162
1163bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1164 if (first_list_mir == nullptr) {
1165 return false;
1166 }
1167
1168 // Try to find the MIR.
1169 MIR* before_list = nullptr;
1170 MIR* after_list = nullptr;
1171
1172 // If we are removing from the beginning of the MIR list.
1173 if (first_mir_insn == first_list_mir) {
1174 before_list = nullptr;
1175 } else {
1176 before_list = FindPreviousMIR(first_list_mir);
1177 if (before_list == nullptr) {
1178 // We did not find the mir.
1179 return false;
1180 }
1181 }
1182
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001183 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001184 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1185 mir->bb = NullBasicBlockId;
1186 }
1187
1188 after_list = last_list_mir->next;
1189
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001190 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001191 if (before_list == nullptr) {
1192 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001193 } else {
1194 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001195 }
1196
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001197 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001198 if (after_list == nullptr) {
1199 last_mir_insn = before_list;
1200 }
1201
1202 return true;
buzbee1fd33462013-03-25 13:40:45 -07001203}
1204
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001205MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001206 MIR* next_mir = nullptr;
1207
1208 if (current != nullptr) {
1209 next_mir = current->next;
1210 }
1211
1212 if (next_mir == nullptr) {
1213 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001214 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1215 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001216 }
1217 }
1218
1219 return next_mir;
1220}
1221
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001222char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001223 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001224 std::string str;
1225 int flags = 0;
1226 int opcode = insn.opcode;
1227 char* ret;
1228 bool nop = false;
1229 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001230 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001231
1232 // Handle special cases.
1233 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1234 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1235 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001236 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001237 insn = mir->meta.throw_insn->dalvikInsn;
1238 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001239 opcode = insn.opcode;
1240 } else if (opcode == kMirOpNop) {
1241 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001242 // Recover original opcode.
1243 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1244 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001245 nop = true;
1246 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001247 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1248 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001249
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001250 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001251 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1252 } else {
1253 dalvik_format = Instruction::FormatOf(insn.opcode);
1254 flags = Instruction::FlagsOf(insn.opcode);
1255 str.append(Instruction::Name(insn.opcode));
1256 }
1257
1258 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001259 BasicBlockId* incoming = mir->meta.phi_incoming;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001260 if (defs > 0 && uses > 0) {
1261 str.append(StringPrintf(" %s = (%s",
1262 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1263 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1264 str.append(StringPrintf(":%d", incoming[0]));
1265 int i;
1266 for (i = 1; i < uses; i++) {
1267 str.append(StringPrintf(", %s:%d",
1268 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1269 incoming[i]));
1270 }
1271 str.append(")");
1272 } else {
1273 str.append(StringPrintf(" v%d", mir->dalvikInsn.vA));
buzbee1fd33462013-03-25 13:40:45 -07001274 }
buzbee1fd33462013-03-25 13:40:45 -07001275 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001276 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001277 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1278 (dalvik_format == Instruction::k3rc));
1279 if (defs != 0) {
1280 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1281 if (uses != 0) {
1282 str.append(", ");
1283 }
1284 }
1285 for (int i = 0; i < uses; i++) {
1286 str.append(
1287 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1288 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1289 // For the listing, skip the high sreg.
1290 i++;
1291 }
1292 if (i != (uses -1)) {
1293 str.append(",");
1294 }
1295 }
1296 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001297 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001298 case Instruction::k21s:
1299 case Instruction::k31i:
1300 case Instruction::k21h:
1301 str.append(StringPrintf(", #%d", insn.vB));
1302 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001303 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001304 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001305 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001306 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001307 case Instruction::k31c:
1308 str.append(StringPrintf(", index #%d", insn.vB));
1309 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001310 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001311 str.append(StringPrintf(", index #%d", insn.vC));
1312 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001313 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001314 case Instruction::k22b:
1315 str.append(StringPrintf(", #%d", insn.vC));
1316 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001317 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001318 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001319 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001320 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001321 if ((flags & Instruction::kBranch) != 0) {
1322 // For branches, decode the instructions to print out the branch targets.
1323 int offset = 0;
1324 switch (dalvik_format) {
1325 case Instruction::k21t:
1326 offset = insn.vB;
1327 break;
1328 case Instruction::k22t:
1329 offset = insn.vC;
1330 break;
1331 case Instruction::k10t:
1332 case Instruction::k20t:
1333 case Instruction::k30t:
1334 offset = insn.vA;
1335 break;
1336 default:
1337 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1338 }
1339 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1340 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1341 }
buzbee1fd33462013-03-25 13:40:45 -07001342 }
1343 if (nop) {
1344 str.append("]--optimized away");
1345 }
1346 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001347 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001348 strncpy(ret, str.c_str(), length);
1349 return ret;
1350}
1351
1352/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001353void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001354 static const struct { const char before; const char after; } match[] = {
1355 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1356 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1357 };
buzbee1fd33462013-03-25 13:40:45 -07001358 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1359 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1360 }
1361}
1362
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001363std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001364 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1365 // the arena. We should be smarter and just place straight into the arena, or compute the
1366 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001367 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1368}
1369
1370// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001371std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001372 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001373 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001374 return GetSSAName(ssa_reg);
1375 }
1376 if (IsConst(reg_location_[ssa_reg])) {
1377 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001378 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001379 ConstantValueWide(reg_location_[ssa_reg]));
1380 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001381 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001382 ConstantValue(reg_location_[ssa_reg]));
1383 }
1384 } else {
1385 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1386 }
1387}
1388
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001389void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001390 switch (bb->block_type) {
1391 case kEntryBlock:
1392 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1393 break;
1394 case kExitBlock:
1395 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1396 break;
1397 case kDalvikByteCode:
1398 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1399 break;
1400 case kExceptionHandling:
1401 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1402 bb->id);
1403 break;
1404 default:
1405 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1406 break;
1407 }
1408}
1409
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001410const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001411 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001412 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1413 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1414}
1415
1416/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001417void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001418 BasicBlock* bb;
1419 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001420 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001421 "Entry Block",
1422 "Code Block",
1423 "Exit Block",
1424 "Exception Handling",
1425 "Catch Block"
1426 };
1427
1428 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1429 LOG(INFO) << cu_->insns << " insns";
1430 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001431 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001432
1433 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001434 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001435 if (bb == NULL) break;
1436 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1437 bb->id,
1438 block_type_names[bb->block_type],
1439 bb->start_offset,
1440 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1441 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001442 if (bb->taken != NullBasicBlockId) {
1443 LOG(INFO) << " Taken branch: block " << bb->taken
1444 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001445 }
buzbee0d829482013-10-11 15:24:55 -07001446 if (bb->fall_through != NullBasicBlockId) {
1447 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1448 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001449 }
1450 }
1451}
1452
1453/*
1454 * Build an array of location records for the incoming arguments.
1455 * Note: one location record per word of arguments, with dummy
1456 * high-word loc for wide arguments. Also pull up any following
1457 * MOVE_RESULT and incorporate it into the invoke.
1458 */
1459CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001460 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001461 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001462 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001463 MIR* move_result_mir = FindMoveResult(bb, mir);
1464 if (move_result_mir == NULL) {
1465 info->result.location = kLocInvalid;
1466 } else {
1467 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001468 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1469 }
1470 info->num_arg_words = mir->ssa_rep->num_uses;
1471 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001472 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001473 for (int i = 0; i < info->num_arg_words; i++) {
1474 info->args[i] = GetRawSrc(mir, i);
1475 }
1476 info->opt_flags = mir->optimization_flags;
1477 info->type = type;
1478 info->is_range = is_range;
1479 info->index = mir->dalvikInsn.vB;
1480 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001481 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001482 return info;
1483}
1484
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001485// Allocate a new MIR.
1486MIR* MIRGraph::NewMIR() {
1487 MIR* mir = new (arena_) MIR();
1488 return mir;
1489}
1490
buzbee862a7602013-04-05 10:58:54 -07001491// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001492BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001493 BasicBlock* bb = new (arena_) BasicBlock();
1494
buzbee862a7602013-04-05 10:58:54 -07001495 bb->block_type = block_type;
1496 bb->id = block_id;
1497 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001498 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001499 (block_type == kExitBlock) ? 2048 : 2,
1500 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001501 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001502 block_id_map_.Put(block_id, block_id);
1503 return bb;
1504}
buzbee1fd33462013-03-25 13:40:45 -07001505
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001506void MIRGraph::InitializeConstantPropagation() {
1507 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001508 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001509}
1510
1511void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001512 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001513 int num_ssa_regs = GetNumSSARegs();
1514 use_counts_.Resize(num_ssa_regs + 32);
1515 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001516 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001517 for (int i = 0; i < num_ssa_regs; i++) {
1518 use_counts_.Insert(0);
1519 raw_use_counts_.Insert(0);
1520 }
1521}
1522
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001523void MIRGraph::SSATransformationStart() {
1524 DCHECK(temp_scoped_alloc_.get() == nullptr);
1525 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1526 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1527 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1528 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1529
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001530 // Update the maximum number of reachable blocks.
1531 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001532}
1533
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001534void MIRGraph::SSATransformationEnd() {
1535 // Verify the dataflow information after the pass.
1536 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1537 VerifyDataflow();
1538 }
1539
1540 temp_bit_vector_size_ = 0u;
1541 temp_bit_vector_ = nullptr;
1542 DCHECK(temp_scoped_alloc_.get() != nullptr);
1543 temp_scoped_alloc_.reset();
1544}
1545
Vladimir Marko55fff042014-07-10 12:42:52 +01001546static BasicBlock* SelectTopologicalSortOrderFallBack(
1547 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1548 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1549 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1550 // No true loop head has been found but there may be true loop heads after the mess we need
1551 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1552 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1553 BasicBlock* fall_back = nullptr;
1554 size_t fall_back_num_reachable = 0u;
1555 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1556 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1557 AllNodesIterator iter(mir_graph);
1558 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1559 if (candidate->hidden || // Hidden, or
1560 candidate->visited || // already processed, or
1561 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1562 (current_loop != nullptr && // outside current loop.
1563 !current_loop->IsBitSet(candidate->id))) {
1564 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001565 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001566 DCHECK(tmp_stack->empty());
1567 tmp_stack->push_back(candidate->id);
1568 candidate_reachable.ClearAllBits();
1569 size_t num_reachable = 0u;
1570 while (!tmp_stack->empty()) {
1571 BasicBlockId current_id = tmp_stack->back();
1572 tmp_stack->pop_back();
1573 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1574 DCHECK(current_bb != nullptr);
1575 ChildBlockIterator child_iter(current_bb, mir_graph);
1576 BasicBlock* child_bb = child_iter.Next();
1577 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1578 DCHECK(!child_bb->hidden);
1579 if (child_bb->visited || // Already processed, or
1580 (current_loop != nullptr && // outside current loop.
1581 !current_loop->IsBitSet(child_bb->id))) {
1582 continue;
1583 }
1584 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1585 candidate_reachable.SetBit(child_bb->id);
1586 tmp_stack->push_back(child_bb->id);
1587 num_reachable += 1u;
1588 }
1589 }
1590 }
1591 if (fall_back_num_reachable < num_reachable) {
1592 fall_back_num_reachable = num_reachable;
1593 fall_back = candidate;
1594 }
1595 }
1596 return fall_back;
1597}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001598
Vladimir Marko55fff042014-07-10 12:42:52 +01001599// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1600static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1601 ArenaBitVector* reachable,
1602 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1603 // NOTE: Loop heads indicated by the "visited" flag.
1604 DCHECK(tmp_stack->empty());
1605 reachable->ClearAllBits();
1606 tmp_stack->push_back(bb_id);
1607 while (!tmp_stack->empty()) {
1608 BasicBlockId current_id = tmp_stack->back();
1609 tmp_stack->pop_back();
1610 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1611 DCHECK(current_bb != nullptr);
1612 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1613 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1614 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1615 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1616 reachable->SetBit(pred_bb->id);
1617 tmp_stack->push_back(pred_bb->id);
1618 }
1619 }
1620 }
1621}
1622
1623void MIRGraph::ComputeTopologicalSortOrder() {
1624 ScopedArenaAllocator allocator(&cu_->arena_stack);
1625 unsigned int num_blocks = GetNumBlocks();
1626
1627 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1628 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1629 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1630 size_t max_nested_loops = 0u;
1631 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1632 loop_exit_blocks.ClearAllBits();
1633
1634 // Count the number of blocks to process and add the entry block(s).
1635 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1636 unsigned int num_blocks_to_process = 0u;
1637 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001638 if (bb->hidden == true) {
1639 continue;
1640 }
1641
Vladimir Marko55fff042014-07-10 12:42:52 +01001642 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001643
Vladimir Marko55fff042014-07-10 12:42:52 +01001644 if (bb->predecessors->Size() == 0u) {
1645 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001646 q.push(bb);
1647 }
1648 }
1649
Vladimir Marko55fff042014-07-10 12:42:52 +01001650 // Create the topological order if need be.
1651 if (topological_order_ == nullptr) {
1652 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1653 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1654 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1655 }
1656 topological_order_->Reset();
1657 topological_order_loop_ends_->Reset();
1658 topological_order_indexes_->Reset();
1659 topological_order_loop_ends_->Resize(num_blocks);
1660 topological_order_indexes_->Resize(num_blocks);
1661 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1662 topological_order_loop_ends_->Insert(0u);
1663 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1664 }
1665
1666 // Mark all blocks as unvisited.
1667 ClearAllVisitedFlags();
1668
1669 // For loop heads, keep track from which blocks they are reachable not going through other
1670 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1671 // in this set go into the loop body, the other children are jumping over the loop.
1672 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1673 loop_head_reachable_from.resize(num_blocks, nullptr);
1674 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1675 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1676
1677 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001678 BasicBlock* bb = nullptr;
1679 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001680 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001681 // Get top.
1682 bb = q.front();
1683 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001684 if (bb->visited) {
1685 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1686 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1687 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1688 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1689 DCHECK_EQ(loop_head_stack.back(), bb->id);
1690 loop_head_stack.pop_back();
1691 ArenaBitVector* reachable =
1692 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1693 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1694 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1695 q.push(GetBasicBlock(candidate_id));
1696 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1697 // so clearing the bit has no effect on the iterator.
1698 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001699 }
1700 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001701 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001702 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001703 } else {
1704 // Find the new loop head.
1705 AllNodesIterator iter(this);
1706 while (true) {
1707 BasicBlock* candidate = iter.Next();
1708 if (candidate == nullptr) {
1709 // We did not find a true loop head, fall back to a reachable block in any loop.
1710 ArenaBitVector* current_loop =
1711 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1712 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1713 &allocator, &tmp_stack);
1714 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1715 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1716 LOG(INFO) << "Topological sort order: Using fall-back in "
1717 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1718 << " @0x" << std::hex << bb->start_offset
1719 << ", num_blocks = " << std::dec << num_blocks;
1720 }
1721 break;
1722 }
1723 if (candidate->hidden || // Hidden, or
1724 candidate->visited || // already processed, or
1725 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1726 (!loop_head_stack.empty() && // outside current loop.
1727 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1728 continue;
1729 }
1730
1731 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1732 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1733 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1734 if (pred_bb != candidate && !pred_bb->visited &&
1735 !pred_bb->dominators->IsBitSet(candidate->id)) {
1736 break; // Keep non-null pred_bb to indicate failure.
1737 }
1738 }
1739 if (pred_bb == nullptr) {
1740 bb = candidate;
1741 break;
1742 }
1743 }
1744 // Compute blocks from which the loop head is reachable and process those blocks first.
1745 ArenaBitVector* reachable =
1746 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1747 loop_head_reachable_from[bb->id] = reachable;
1748 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1749 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1750 loop_head_stack.push_back(bb->id);
1751 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001752 }
1753
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001754 DCHECK_EQ(bb->hidden, false);
1755 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001756 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001757
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001758 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001759 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1760 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001761 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001762
Vladimir Marko55fff042014-07-10 12:42:52 +01001763 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001764 ChildBlockIterator succIter(bb, this);
1765 BasicBlock* successor = succIter.Next();
1766 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001767 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001768 continue;
1769 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001770
Vladimir Marko55fff042014-07-10 12:42:52 +01001771 // One more predecessor was visited.
1772 visited_cnt_values[successor->id] += 1u;
1773 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1774 if (loop_head_stack.empty() ||
1775 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1776 q.push(successor);
1777 } else {
1778 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1779 loop_exit_blocks.SetBit(successor->id);
1780 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001781 }
1782 }
1783 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001784
1785 // Prepare the loop head stack for iteration.
1786 topological_order_loop_head_stack_ =
1787 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001788}
1789
1790bool BasicBlock::IsExceptionBlock() const {
1791 if (block_type == kExceptionHandling) {
1792 return true;
1793 }
1794 return false;
1795}
1796
Wei Jin04f4d8a2014-05-29 18:04:29 -07001797bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1798 BasicBlock* target = GetBasicBlock(target_id);
1799
1800 if (source == nullptr || target == nullptr)
1801 return false;
1802
1803 int idx;
1804 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1805 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1806 if (bb == source)
1807 return true; // The block has been inserted by a suspend check before.
1808 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1809 return true;
1810 }
1811
1812 return false;
1813}
1814
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001815ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1816 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1817 visited_taken_(false), have_successors_(false) {
1818 // Check if we actually do have successors.
1819 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1820 have_successors_ = true;
1821 successor_iter_.Reset(basic_block_->successor_blocks);
1822 }
1823}
1824
1825BasicBlock* ChildBlockIterator::Next() {
1826 // We check if we have a basic block. If we don't we cannot get next child.
1827 if (basic_block_ == nullptr) {
1828 return nullptr;
1829 }
1830
1831 // If we haven't visited fallthrough, return that.
1832 if (visited_fallthrough_ == false) {
1833 visited_fallthrough_ = true;
1834
1835 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1836 if (result != nullptr) {
1837 return result;
1838 }
1839 }
1840
1841 // If we haven't visited taken, return that.
1842 if (visited_taken_ == false) {
1843 visited_taken_ = true;
1844
1845 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1846 if (result != nullptr) {
1847 return result;
1848 }
1849 }
1850
1851 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1852 if (have_successors_ == true) {
1853 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07001854 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1855 successor_block_info != nullptr;
1856 successor_block_info = successor_iter_.Next()) {
1857 // If block was replaced by zero block, take next one.
1858 if (successor_block_info->block != NullBasicBlockId) {
1859 return mir_graph_->GetBasicBlock(successor_block_info->block);
1860 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001861 }
1862 }
1863
1864 // We do not have anything.
1865 return nullptr;
1866}
1867
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001868BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1869 MIRGraph* mir_graph = c_unit->mir_graph.get();
1870 return Copy(mir_graph);
1871}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001872
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001873BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1874 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001875
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001876 // We don't do a memcpy style copy here because it would lead to a lot of things
1877 // to clean up. Let us do it by hand instead.
1878 // Copy in taken and fallthrough.
1879 result_bb->fall_through = fall_through;
1880 result_bb->taken = taken;
1881
1882 // Copy successor links if needed.
1883 ArenaAllocator* arena = mir_graph->GetArena();
1884
1885 result_bb->successor_block_list_type = successor_block_list_type;
1886 if (result_bb->successor_block_list_type != kNotUsed) {
1887 size_t size = successor_blocks->Size();
1888 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1889 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1890 while (true) {
1891 SuccessorBlockInfo* sbi_old = iterator.Next();
1892 if (sbi_old == nullptr) {
1893 break;
1894 }
1895 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1896 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1897 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001898 }
1899 }
1900
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001901 // Copy offset, method.
1902 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001903
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001904 // Now copy instructions.
1905 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1906 // Get a copy first.
1907 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001908
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001909 // Append it.
1910 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001911 }
1912
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001913 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001914}
1915
1916MIR* MIR::Copy(MIRGraph* mir_graph) {
1917 MIR* res = mir_graph->NewMIR();
1918 *res = *this;
1919
1920 // Remove links
1921 res->next = nullptr;
1922 res->bb = NullBasicBlockId;
1923 res->ssa_rep = nullptr;
1924
1925 return res;
1926}
1927
1928MIR* MIR::Copy(CompilationUnit* c_unit) {
1929 return Copy(c_unit->mir_graph.get());
1930}
1931
1932uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1933 // Default result.
1934 int res = 0;
1935
1936 // We are basically setting the iputs to their igets counterparts.
1937 switch (opcode) {
1938 case Instruction::IPUT:
1939 case Instruction::IPUT_OBJECT:
1940 case Instruction::IPUT_BOOLEAN:
1941 case Instruction::IPUT_BYTE:
1942 case Instruction::IPUT_CHAR:
1943 case Instruction::IPUT_SHORT:
1944 case Instruction::IPUT_QUICK:
1945 case Instruction::IPUT_OBJECT_QUICK:
1946 case Instruction::APUT:
1947 case Instruction::APUT_OBJECT:
1948 case Instruction::APUT_BOOLEAN:
1949 case Instruction::APUT_BYTE:
1950 case Instruction::APUT_CHAR:
1951 case Instruction::APUT_SHORT:
1952 case Instruction::SPUT:
1953 case Instruction::SPUT_OBJECT:
1954 case Instruction::SPUT_BOOLEAN:
1955 case Instruction::SPUT_BYTE:
1956 case Instruction::SPUT_CHAR:
1957 case Instruction::SPUT_SHORT:
1958 // Skip the VR containing what to store.
1959 res = 1;
1960 break;
1961 case Instruction::IPUT_WIDE:
1962 case Instruction::IPUT_WIDE_QUICK:
1963 case Instruction::APUT_WIDE:
1964 case Instruction::SPUT_WIDE:
1965 // Skip the two VRs containing what to store.
1966 res = 2;
1967 break;
1968 default:
1969 // Do nothing in the general case.
1970 break;
1971 }
1972
1973 return res;
1974}
1975
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001976/**
1977 * @brief Given a decoded instruction, it checks whether the instruction
1978 * sets a constant and if it does, more information is provided about the
1979 * constant being set.
1980 * @param ptr_value pointer to a 64-bit holder for the constant.
1981 * @param wide Updated by function whether a wide constant is being set by bytecode.
1982 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1983 */
1984bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1985 bool sets_const = true;
1986 int64_t value = vB;
1987
1988 DCHECK(ptr_value != nullptr);
1989 DCHECK(wide != nullptr);
1990
1991 switch (opcode) {
1992 case Instruction::CONST_4:
1993 case Instruction::CONST_16:
1994 case Instruction::CONST:
1995 *wide = false;
1996 value <<= 32; // In order to get the sign extend.
1997 value >>= 32;
1998 break;
1999 case Instruction::CONST_HIGH16:
2000 *wide = false;
2001 value <<= 48; // In order to get the sign extend.
2002 value >>= 32;
2003 break;
2004 case Instruction::CONST_WIDE_16:
2005 case Instruction::CONST_WIDE_32:
2006 *wide = true;
2007 value <<= 32; // In order to get the sign extend.
2008 value >>= 32;
2009 break;
2010 case Instruction::CONST_WIDE:
2011 *wide = true;
2012 value = vB_wide;
2013 break;
2014 case Instruction::CONST_WIDE_HIGH16:
2015 *wide = true;
2016 value <<= 48; // In order to get the sign extend.
2017 break;
2018 default:
2019 sets_const = false;
2020 break;
2021 }
2022
2023 if (sets_const) {
2024 *ptr_value = value;
2025 }
2026
2027 return sets_const;
2028}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002029
2030void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2031 // Reset flags for all MIRs in bb.
2032 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2033 mir->optimization_flags &= (~reset_flags);
2034 }
2035}
2036
2037void BasicBlock::Hide(CompilationUnit* c_unit) {
2038 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2039 block_type = kDalvikByteCode;
2040
2041 // Mark it as hidden.
2042 hidden = true;
2043
2044 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2045 // are updated to know that they no longer have a parent.
2046 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2047 mir->bb = NullBasicBlockId;
2048 }
2049 first_mir_insn = nullptr;
2050 last_mir_insn = nullptr;
2051
2052 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2053
2054 MIRGraph* mir_graph = c_unit->mir_graph.get();
2055 while (true) {
2056 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2057 if (pred_bb == nullptr) {
2058 break;
2059 }
2060
2061 // Sadly we have to go through the children by hand here.
2062 pred_bb->ReplaceChild(id, NullBasicBlockId);
2063 }
2064
2065 // Iterate through children of bb we are hiding.
2066 ChildBlockIterator successorChildIter(this, mir_graph);
2067
2068 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2069 // Replace child with null child.
2070 childPtr->predecessors->Delete(id);
2071 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002072
2073 // Remove link to children.
2074 taken = NullBasicBlockId;
2075 fall_through = NullBasicBlockId;
2076 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002077}
2078
2079bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2080 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2081 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2082 // then it is not live out of this BB.
2083 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2084
2085 int last_ssa_reg = -1;
2086
2087 // Walk through the MIRs backwards.
2088 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2089 // Get ssa rep.
2090 SSARepresentation *ssa_rep = mir->ssa_rep;
2091
2092 // Go through the defines for this MIR.
2093 for (int i = 0; i < ssa_rep->num_defs; i++) {
2094 DCHECK(ssa_rep->defs != nullptr);
2095
2096 // Get the ssa reg.
2097 int def_ssa_reg = ssa_rep->defs[i];
2098
2099 // Get dalvik reg.
2100 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2101
2102 // Compare dalvik regs.
2103 if (dalvik_reg == def_dalvik_reg) {
2104 // We found a def of the register that we are being asked about.
2105 // Remember it.
2106 last_ssa_reg = def_ssa_reg;
2107 }
2108 }
2109 }
2110
2111 if (last_ssa_reg == -1) {
2112 // If we get to this point we couldn't find a define of register user asked about.
2113 // Let's assume the user knows what he's doing so we can be safe and say that if we
2114 // couldn't find a def, it is live out.
2115 return true;
2116 }
2117
2118 // If it is not -1, we found a match, is it ssa_reg?
2119 return (ssa_reg == last_ssa_reg);
2120}
2121
2122bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2123 // We need to check taken, fall_through, and successor_blocks to replace.
2124 bool found = false;
2125 if (taken == old_bb) {
2126 taken = new_bb;
2127 found = true;
2128 }
2129
2130 if (fall_through == old_bb) {
2131 fall_through = new_bb;
2132 found = true;
2133 }
2134
2135 if (successor_block_list_type != kNotUsed) {
2136 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2137 while (true) {
2138 SuccessorBlockInfo* successor_block_info = iterator.Next();
2139 if (successor_block_info == nullptr) {
2140 break;
2141 }
2142 if (successor_block_info->block == old_bb) {
2143 successor_block_info->block = new_bb;
2144 found = true;
2145 }
2146 }
2147 }
2148
2149 return found;
2150}
2151
2152void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2153 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2154 bool found = false;
2155
2156 while (true) {
2157 BasicBlockId pred_bb_id = iterator.Next();
2158
2159 if (pred_bb_id == NullBasicBlockId) {
2160 break;
2161 }
2162
2163 if (pred_bb_id == old_parent) {
2164 size_t idx = iterator.GetIndex() - 1;
2165 predecessors->Put(idx, new_parent);
2166 found = true;
2167 break;
2168 }
2169 }
2170
2171 // If not found, add it.
2172 if (found == false) {
2173 predecessors->Insert(new_parent);
2174 }
2175}
2176
2177// Create a new basic block with block_id as num_blocks_ that is
2178// post-incremented.
2179BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2180 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2181 block_list_.Insert(res);
2182 return res;
2183}
2184
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002185void MIRGraph::CalculateBasicBlockInformation() {
2186 PassDriverMEPostOpt driver(cu_);
2187 driver.Launch();
2188}
2189
2190void MIRGraph::InitializeBasicBlockData() {
2191 num_blocks_ = block_list_.Size();
2192}
2193
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002194} // namespace art