blob: 49e5c7682c5727bac666a34850fecefeae2ecd5e [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"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010033#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000034
buzbee311ca162013-02-28 15:56:43 -080035namespace art {
36
37#define MAX_PATTERN_LEN 5
38
buzbee1fd33462013-03-25 13:40:45 -070039const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
40 "Phi",
41 "Copy",
42 "FusedCmplFloat",
43 "FusedCmpgFloat",
44 "FusedCmplDouble",
45 "FusedCmpgDouble",
46 "FusedCmpLong",
47 "Nop",
48 "OpNullCheck",
49 "OpRangeCheck",
50 "OpDivZeroCheck",
51 "Check1",
52 "Check2",
53 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040054 "ConstVector",
55 "MoveVector",
56 "PackedMultiply",
57 "PackedAddition",
58 "PackedSubtract",
59 "PackedShiftLeft",
60 "PackedSignedShiftRight",
61 "PackedUnsignedShiftRight",
62 "PackedAnd",
63 "PackedOr",
64 "PackedXor",
65 "PackedAddReduce",
66 "PackedReduce",
67 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070068 "ReserveVectorRegisters",
69 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070070 "MemBarrier",
buzbee1fd33462013-03-25 13:40:45 -070071};
72
buzbee862a7602013-04-05 10:58:54 -070073MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070074 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010075 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070076 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080077 ssa_base_vregs_(NULL),
78 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080079 vreg_to_ssa_map_(NULL),
80 ssa_last_defs_(NULL),
81 is_constant_v_(NULL),
82 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070083 use_counts_(arena, 256, kGrowableArrayMisc),
84 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080085 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070086 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070087 dfs_order_(NULL),
88 dfs_post_order_(NULL),
89 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070090 topological_order_(nullptr),
Vladimir Marko55fff042014-07-10 12:42:52 +010091 topological_order_loop_ends_(nullptr),
92 topological_order_indexes_(nullptr),
93 topological_order_loop_head_stack_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080094 i_dom_list_(NULL),
95 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000096 temp_scoped_alloc_(),
97 temp_insn_data_(nullptr),
98 temp_bit_vector_size_(0u),
99 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100100 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -0700101 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -0800102 try_block_addr_(NULL),
103 entry_block_(NULL),
104 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800105 num_blocks_(0),
106 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700107 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100108 m_units_(arena->Adapter()),
109 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800110 current_method_(kInvalidEntry),
111 current_offset_(kInvalidEntry),
112 def_count_(0),
113 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700114 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100115 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700116 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700117 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
118 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700119 arena_(arena),
120 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800121 forward_branches_(0),
122 compiler_temps_(arena, 6, kGrowableArrayMisc),
123 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800124 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000125 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000126 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000127 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000128 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700129 method_lowering_infos_(arena, 0u),
130 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700131 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800132 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
133 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800134}
135
Ian Rogers6282dc12013-04-18 15:54:02 -0700136MIRGraph::~MIRGraph() {
137 STLDeleteElements(&m_units_);
138}
139
buzbee311ca162013-02-28 15:56:43 -0800140/*
141 * Parse an instruction, return the length of the instruction
142 */
Ian Rogers29a26482014-05-02 15:27:29 -0700143int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
144 const Instruction* inst = Instruction::At(code_ptr);
145 decoded_instruction->opcode = inst->Opcode();
146 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
147 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
148 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
149 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
150 if (inst->HasVarArgs()) {
151 inst->GetVarArgs(decoded_instruction->arg);
152 }
153 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800154}
155
156
157/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700158BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700159 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700160 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800161 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700162 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800163 while (insn) {
164 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700165 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800166 insn = insn->next;
167 }
168 if (insn == NULL) {
169 LOG(FATAL) << "Break split failed";
170 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700171 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700172 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800173
174 bottom_block->start_offset = code_offset;
175 bottom_block->first_mir_insn = insn;
176 bottom_block->last_mir_insn = orig_block->last_mir_insn;
177
Junmo Park90223cc2014-08-04 18:51:21 +0900178 /* If this block was terminated by a return, conditional branch or throw,
179 * the flag needs to go with the bottom block
180 */
buzbee311ca162013-02-28 15:56:43 -0800181 bottom_block->terminated_by_return = orig_block->terminated_by_return;
182 orig_block->terminated_by_return = false;
183
Junmo Park90223cc2014-08-04 18:51:21 +0900184 bottom_block->conditional_branch = orig_block->conditional_branch;
185 orig_block->conditional_branch = false;
186
187 bottom_block->explicit_throw = orig_block->explicit_throw;
188 orig_block->explicit_throw = false;
189
buzbee311ca162013-02-28 15:56:43 -0800190 /* Handle the taken path */
191 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700192 if (bottom_block->taken != NullBasicBlockId) {
193 orig_block->taken = NullBasicBlockId;
194 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
195 bb_taken->predecessors->Delete(orig_block->id);
196 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800197 }
198
199 /* Handle the fallthrough path */
200 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700201 orig_block->fall_through = bottom_block->id;
202 bottom_block->predecessors->Insert(orig_block->id);
203 if (bottom_block->fall_through != NullBasicBlockId) {
204 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
205 bb_fall_through->predecessors->Delete(orig_block->id);
206 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800207 }
208
209 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700210 if (orig_block->successor_block_list_type != kNotUsed) {
211 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
212 bottom_block->successor_blocks = orig_block->successor_blocks;
213 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700214 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700215 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800216 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700217 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700218 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700219 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700220 if (bb != nullptr) {
221 bb->predecessors->Delete(orig_block->id);
222 bb->predecessors->Insert(bottom_block->id);
223 }
buzbee311ca162013-02-28 15:56:43 -0800224 }
225 }
226
buzbee0d829482013-10-11 15:24:55 -0700227 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700228 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800229
buzbee311ca162013-02-28 15:56:43 -0800230 /*
231 * Update the immediate predecessor block pointer so that outgoing edges
232 * can be applied to the proper block.
233 */
234 if (immed_pred_block_p) {
235 DCHECK_EQ(*immed_pred_block_p, orig_block);
236 *immed_pred_block_p = bottom_block;
237 }
buzbeeb48819d2013-09-14 16:15:25 -0700238
239 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000240 DCHECK(insn != nullptr);
241 DCHECK(insn != orig_block->first_mir_insn);
242 DCHECK(insn == bottom_block->first_mir_insn);
243 DCHECK_EQ(insn->offset, bottom_block->start_offset);
244 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700245 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000246 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
247 MIR* p = insn;
248 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
249 while (p != bottom_block->last_mir_insn) {
250 p = p->next;
251 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700252 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700253 int opcode = p->dalvikInsn.opcode;
254 /*
255 * Some messiness here to ensure that we only enter real opcodes and only the
256 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000257 * CHECK and work portions. Since the 2nd half of a split operation is always
258 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700259 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700260 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000261 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700262 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
263 }
buzbeeb48819d2013-09-14 16:15:25 -0700264 }
265
buzbee311ca162013-02-28 15:56:43 -0800266 return bottom_block;
267}
268
269/*
270 * Given a code offset, find out the block that starts with it. If the offset
271 * is in the middle of an existing block, split it into two. If immed_pred_block_p
272 * is not non-null and is the block being split, update *immed_pred_block_p to
273 * point to the bottom block so that outgoing edges can be set up properly
274 * (by the caller)
275 * Utilizes a map for fast lookup of the typical cases.
276 */
buzbee0d829482013-10-11 15:24:55 -0700277BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700278 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700279 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800280 return NULL;
281 }
buzbeeb48819d2013-09-14 16:15:25 -0700282
283 int block_id = dex_pc_to_block_map_.Get(code_offset);
284 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
285
286 if ((bb != NULL) && (bb->start_offset == code_offset)) {
287 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700288 return bb;
289 }
buzbee311ca162013-02-28 15:56:43 -0800290
buzbeeb48819d2013-09-14 16:15:25 -0700291 // No direct hit.
292 if (!create) {
293 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800294 }
295
buzbeeb48819d2013-09-14 16:15:25 -0700296 if (bb != NULL) {
297 // The target exists somewhere in an existing block.
298 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
299 }
300
301 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700302 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
303 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800304 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700305 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800306 return bb;
307}
308
buzbeeb48819d2013-09-14 16:15:25 -0700309
buzbee311ca162013-02-28 15:56:43 -0800310/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700311void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800312 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700313 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800314
315 if (tries_size == 0) {
316 return;
317 }
318
319 for (int i = 0; i < tries_size; i++) {
320 const DexFile::TryItem* pTry =
321 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700322 DexOffset start_offset = pTry->start_addr_;
323 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800324 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700325 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800326 }
327 }
328
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700329 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800330 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
331 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
332 for (uint32_t idx = 0; idx < handlers_size; idx++) {
333 CatchHandlerIterator iterator(handlers_ptr);
334 for (; iterator.HasNext(); iterator.Next()) {
335 uint32_t address = iterator.GetHandlerAddress();
336 FindBlock(address, false /* split */, true /*create*/,
337 /* immed_pred_block_p */ NULL);
338 }
339 handlers_ptr = iterator.EndDataPointer();
340 }
341}
342
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100343bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
344 NarrowDexOffset catch_offset) {
345 // Catches for monitor-exit during stack unwinding have the pattern
346 // move-exception (move)* (goto)? monitor-exit throw
347 // In the currently generated dex bytecode we see these catching a bytecode range including
348 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
349 // it's the case for a given monitor-exit and catch block so that we can ignore it.
350 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
351 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
352 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700353 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100354 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
355 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700356 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100357 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
358 if (check_insn->VRegA_11x() == monitor_reg) {
359 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
360 return false;
361 }
362 check_insn = check_insn->Next();
363 while (true) {
364 int dest = -1;
365 bool wide = false;
366 switch (check_insn->Opcode()) {
367 case Instruction::MOVE_WIDE:
368 wide = true;
369 // Intentional fall-through.
370 case Instruction::MOVE_OBJECT:
371 case Instruction::MOVE:
372 dest = check_insn->VRegA_12x();
373 break;
374
375 case Instruction::MOVE_WIDE_FROM16:
376 wide = true;
377 // Intentional fall-through.
378 case Instruction::MOVE_OBJECT_FROM16:
379 case Instruction::MOVE_FROM16:
380 dest = check_insn->VRegA_22x();
381 break;
382
383 case Instruction::MOVE_WIDE_16:
384 wide = true;
385 // Intentional fall-through.
386 case Instruction::MOVE_OBJECT_16:
387 case Instruction::MOVE_16:
388 dest = check_insn->VRegA_32x();
389 break;
390
391 case Instruction::GOTO:
392 case Instruction::GOTO_16:
393 case Instruction::GOTO_32:
394 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
395 // Intentional fall-through.
396 default:
397 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
398 check_insn->VRegA_11x() == monitor_reg;
399 }
400
401 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
402 return false;
403 }
404
405 check_insn = check_insn->Next();
406 }
407}
408
buzbee311ca162013-02-28 15:56:43 -0800409/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700410BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
411 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700412 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700413 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800414 switch (insn->dalvikInsn.opcode) {
415 case Instruction::GOTO:
416 case Instruction::GOTO_16:
417 case Instruction::GOTO_32:
418 target += insn->dalvikInsn.vA;
419 break;
420 case Instruction::IF_EQ:
421 case Instruction::IF_NE:
422 case Instruction::IF_LT:
423 case Instruction::IF_GE:
424 case Instruction::IF_GT:
425 case Instruction::IF_LE:
426 cur_block->conditional_branch = true;
427 target += insn->dalvikInsn.vC;
428 break;
429 case Instruction::IF_EQZ:
430 case Instruction::IF_NEZ:
431 case Instruction::IF_LTZ:
432 case Instruction::IF_GEZ:
433 case Instruction::IF_GTZ:
434 case Instruction::IF_LEZ:
435 cur_block->conditional_branch = true;
436 target += insn->dalvikInsn.vB;
437 break;
438 default:
439 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
440 }
buzbeeb48819d2013-09-14 16:15:25 -0700441 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700442 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800443 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700444 cur_block->taken = taken_block->id;
445 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800446
447 /* Always terminate the current block for conditional branches */
448 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700449 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800450 /*
451 * If the method is processed
452 * in sequential order from the
453 * beginning, we don't need to
454 * specify split for continue
455 * blocks. However, this
456 * routine can be called by
457 * compileLoop, which starts
458 * parsing the method from an
459 * arbitrary address in the
460 * method body.
461 */
462 true,
463 /* create */
464 true,
465 /* immed_pred_block_p */
466 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700467 cur_block->fall_through = fallthrough_block->id;
468 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800469 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700470 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800471 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800472 }
473 return cur_block;
474}
475
476/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800477BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
478 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800479 const uint16_t* switch_data =
480 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
481 int size;
482 const int* keyTable;
483 const int* target_table;
484 int i;
485 int first_key;
486
487 /*
488 * Packed switch data format:
489 * ushort ident = 0x0100 magic value
490 * ushort size number of entries in the table
491 * int first_key first (and lowest) switch case value
492 * int targets[size] branch targets, relative to switch opcode
493 *
494 * Total size is (4+size*2) 16-bit code units.
495 */
496 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
497 DCHECK_EQ(static_cast<int>(switch_data[0]),
498 static_cast<int>(Instruction::kPackedSwitchSignature));
499 size = switch_data[1];
500 first_key = switch_data[2] | (switch_data[3] << 16);
501 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700502 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800503 /*
504 * Sparse switch data format:
505 * ushort ident = 0x0200 magic value
506 * ushort size number of entries in the table; > 0
507 * int keys[size] keys, sorted low-to-high; 32-bit aligned
508 * int targets[size] branch targets, relative to switch opcode
509 *
510 * Total size is (2+size*4) 16-bit code units.
511 */
512 } else {
513 DCHECK_EQ(static_cast<int>(switch_data[0]),
514 static_cast<int>(Instruction::kSparseSwitchSignature));
515 size = switch_data[1];
516 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
517 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700518 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800519 }
520
buzbee0d829482013-10-11 15:24:55 -0700521 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800522 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700523 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800524 }
buzbee0d829482013-10-11 15:24:55 -0700525 cur_block->successor_block_list_type =
526 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
527 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700528 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800529
530 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700531 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800532 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700533 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700534 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000535 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700536 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800537 successor_block_info->key =
538 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
539 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700540 cur_block->successor_blocks->Insert(successor_block_info);
541 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800542 }
543
544 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700545 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
546 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700547 cur_block->fall_through = fallthrough_block->id;
548 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800549 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800550}
551
552/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700553BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
554 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700555 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700556 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800557 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
558 bool build_all_edges =
559 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800560
561 /* In try block */
562 if (in_try_block) {
563 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
564
buzbee0d829482013-10-11 15:24:55 -0700565 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800566 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
567 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700568 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800569 }
570
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700571 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700572 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800573 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100574 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
575 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
576 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
577 continue;
578 }
579 if (cur_block->successor_block_list_type == kNotUsed) {
580 cur_block->successor_block_list_type = kCatch;
581 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
582 arena_, 2, kGrowableArraySuccessorBlocks);
583 }
buzbee311ca162013-02-28 15:56:43 -0800584 catch_block->catch_entry = true;
585 if (kIsDebugBuild) {
586 catches_.insert(catch_block->start_offset);
587 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700588 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000589 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700590 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800591 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700592 cur_block->successor_blocks->Insert(successor_block_info);
593 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800594 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100595 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
596 }
597 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700598 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700599 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700600 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800601 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700602 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800603 }
604
buzbee17189ac2013-11-08 11:07:02 -0800605 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800606 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700607 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700608 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800609 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
610 /* immed_pred_block_p */ NULL);
611 }
612 if (!in_try_block) {
613 // Don't split a THROW that can't rethrow - we're done.
614 return cur_block;
615 }
616 }
617
buzbee17189ac2013-11-08 11:07:02 -0800618 if (!build_all_edges) {
619 /*
620 * Even though there is an exception edge here, control cannot return to this
621 * method. Thus, for the purposes of dataflow analysis and optimization, we can
622 * ignore the edge. Doing this reduces compile time, and increases the scope
623 * of the basic-block level optimization pass.
624 */
625 return cur_block;
626 }
627
buzbee311ca162013-02-28 15:56:43 -0800628 /*
629 * Split the potentially-throwing instruction into two parts.
630 * The first half will be a pseudo-op that captures the exception
631 * edges and terminates the basic block. It always falls through.
632 * Then, create a new basic block that begins with the throwing instruction
633 * (minus exceptions). Note: this new basic block must NOT be entered into
634 * the block_map. If the potentially-throwing instruction is the target of a
635 * future branch, we need to find the check psuedo half. The new
636 * basic block containing the work portion of the instruction should
637 * only be entered via fallthrough from the block containing the
638 * pseudo exception edge MIR. Note also that this new block is
639 * not automatically terminated after the work portion, and may
640 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700641 *
642 * Note also that the dex_pc_to_block_map_ entry for the potentially
643 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800644 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700645 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700646 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800647 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700648 cur_block->fall_through = new_block->id;
649 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700650 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800651 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700652 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700653 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800654 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700655 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800656 return new_block;
657}
658
659/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
660void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700661 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700662 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800663 current_code_item_ = code_item;
664 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
665 current_method_ = m_units_.size();
666 current_offset_ = 0;
667 // TODO: will need to snapshot stack image and use that as the mir context identification.
668 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000669 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
670 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800671 const uint16_t* code_ptr = current_code_item_->insns_;
672 const uint16_t* code_end =
673 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
674
675 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700676 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700677 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700678 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 -0700679
buzbee311ca162013-02-28 15:56:43 -0800680 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700681 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
682 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800683
684 // If this is the first method, set up default entry and exit blocks.
685 if (current_method_ == 0) {
686 DCHECK(entry_block_ == NULL);
687 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700688 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700689 // Use id 0 to represent a null block.
690 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
691 DCHECK_EQ(null_block->id, NullBasicBlockId);
692 null_block->hidden = true;
693 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700694 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700695 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700696 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700697 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800698 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
699 cu_->dex_file = &dex_file;
700 cu_->class_def_idx = class_def_idx;
701 cu_->method_idx = method_idx;
702 cu_->access_flags = access_flags;
703 cu_->invoke_type = invoke_type;
704 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
705 cu_->num_ins = current_code_item_->ins_size_;
706 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
707 cu_->num_outs = current_code_item_->outs_size_;
708 cu_->num_dalvik_registers = current_code_item_->registers_size_;
709 cu_->insns = current_code_item_->insns_;
710 cu_->code_item = current_code_item_;
711 } else {
712 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
713 /*
714 * Will need to manage storage for ins & outs, push prevous state and update
715 * insert point.
716 */
717 }
718
719 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700720 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700721 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800722 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700723 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700724 // TODO: for inlining support, insert at the insert point rather than entry block.
725 entry_block_->fall_through = cur_block->id;
726 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800727
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000728 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800729 ProcessTryCatchBlocks();
730
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000731 uint64_t merged_df_flags = 0u;
732
buzbee311ca162013-02-28 15:56:43 -0800733 /* Parse all instructions and put them into containing basic blocks */
734 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700735 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800736 insn->offset = current_offset_;
737 insn->m_unit_index = current_method_;
738 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800739 Instruction::Code opcode = insn->dalvikInsn.opcode;
740 if (opcode_count_ != NULL) {
741 opcode_count_[static_cast<int>(opcode)]++;
742 }
743
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700744 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800745 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800746
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700747 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000748 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800749
750 if (df_flags & DF_HAS_DEFS) {
751 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
752 }
753
buzbee1da1e2f2013-11-15 13:37:01 -0800754 if (df_flags & DF_LVN) {
755 cur_block->use_lvn = true; // Run local value numbering on this basic block.
756 }
757
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700758 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700759 if (opcode == Instruction::NOP) {
760 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
761 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
762 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
763 uint16_t following_raw_instruction = code_ptr[1];
764 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
765 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
766 (following_raw_instruction == Instruction::kArrayDataSignature)) {
767 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
768 }
769 }
770 if (width == 1) {
771 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700772 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700773 } else {
buzbee0d829482013-10-11 15:24:55 -0700774 DCHECK(cur_block->fall_through == NullBasicBlockId);
775 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700776 // Unreachable instruction, mark for no continuation.
777 flags &= ~Instruction::kContinue;
778 }
779 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700780 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700781 }
782
buzbeeb48819d2013-09-14 16:15:25 -0700783 // Associate the starting dex_pc for this opcode with its containing basic block.
784 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
785
buzbee27247762013-07-28 12:03:58 -0700786 code_ptr += width;
787
buzbee311ca162013-02-28 15:56:43 -0800788 if (flags & Instruction::kBranch) {
789 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
790 width, flags, code_ptr, code_end);
791 } else if (flags & Instruction::kReturn) {
792 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700793 cur_block->fall_through = exit_block_->id;
794 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800795 /*
796 * Terminate the current block if there are instructions
797 * afterwards.
798 */
799 if (code_ptr < code_end) {
800 /*
801 * Create a fallthrough block for real instructions
802 * (incl. NOP).
803 */
buzbee27247762013-07-28 12:03:58 -0700804 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
805 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800806 }
807 } else if (flags & Instruction::kThrow) {
808 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
809 code_ptr, code_end);
810 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800811 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800812 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700813 if (verify_flags & Instruction::kVerifyVarArgRange ||
814 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800815 /*
816 * The Quick backend's runtime model includes a gap between a method's
817 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
818 * which spans the gap is somewhat complicated, and should not happen
819 * in normal usage of dx. Punt to the interpreter.
820 */
821 int first_reg_in_range = insn->dalvikInsn.vC;
822 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
823 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
824 punt_to_interpreter_ = true;
825 }
826 }
buzbee311ca162013-02-28 15:56:43 -0800827 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700828 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800829 false, /* immed_pred_block_p */ NULL);
830 if (next_block) {
831 /*
832 * The next instruction could be the target of a previously parsed
833 * forward branch so a block is already created. If the current
834 * instruction is not an unconditional branch, connect them through
835 * the fall-through link.
836 */
buzbee0d829482013-10-11 15:24:55 -0700837 DCHECK(cur_block->fall_through == NullBasicBlockId ||
838 GetBasicBlock(cur_block->fall_through) == next_block ||
839 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800840
buzbee0d829482013-10-11 15:24:55 -0700841 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
842 cur_block->fall_through = next_block->id;
843 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800844 }
845 cur_block = next_block;
846 }
847 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000848 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000849
buzbee311ca162013-02-28 15:56:43 -0800850 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
851 DumpCFG("/sdcard/1_post_parse_cfg/", true);
852 }
853
854 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700855 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800856 }
857}
858
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700859void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800860 DCHECK(opcode_count_ != NULL);
861 LOG(INFO) << "Opcode Count";
862 for (int i = 0; i < kNumPackedOpcodes; i++) {
863 if (opcode_count_[i] != 0) {
864 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
865 << " " << opcode_count_[i];
866 }
867 }
868}
869
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700870uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
871 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
872 return oat_data_flow_attributes_[opcode];
873}
874
875uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
876 DCHECK(mir != nullptr);
877 Instruction::Code opcode = mir->dalvikInsn.opcode;
878 return GetDataFlowAttributes(opcode);
879}
880
buzbee311ca162013-02-28 15:56:43 -0800881// TODO: use a configurable base prefix, and adjust callers to supply pass name.
882/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800883void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800884 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700885 static AtomicInteger cnt(0);
886
887 // Increment counter to get a unique file number.
888 cnt++;
889
buzbee311ca162013-02-28 15:56:43 -0800890 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
891 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700892 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800893 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700894 suffix == nullptr ? "" : suffix,
895 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800896 file = fopen(fname.c_str(), "w");
897 if (file == NULL) {
898 return;
899 }
900 fprintf(file, "digraph G {\n");
901
902 fprintf(file, " rankdir=TB\n");
903
904 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
905 int idx;
906
907 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700908 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700909 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700910 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800911 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700912 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800913 if (bb->block_type == kEntryBlock) {
914 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
915 } else if (bb->block_type == kExitBlock) {
916 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
917 } else if (bb->block_type == kDalvikByteCode) {
918 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
919 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700920 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800921 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
922 bb->first_mir_insn ? " | " : " ");
923 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
924 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400925 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
926 if (opcode == kMirOpConstVector) {
927 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
928 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
929 mir->dalvikInsn.vA,
930 mir->dalvikInsn.vB,
931 mir->dalvikInsn.arg[0],
932 mir->dalvikInsn.arg[1],
933 mir->dalvikInsn.arg[2],
934 mir->dalvikInsn.arg[3],
935 mir->next ? " | " : " ");
936 } else {
937 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
938 extended_mir_op_names_[opcode - kMirOpFirst],
939 mir->dalvikInsn.vA,
940 mir->dalvikInsn.vB,
941 mir->dalvikInsn.vC,
942 mir->next ? " | " : " ");
943 }
944 } else {
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700945 fprintf(file, " {%04x %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400946 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700947 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
948 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400949 extended_mir_op_names_[opcode - kMirOpFirst],
950 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
951 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700952 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700953 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400954 mir->next ? " | " : " ");
955 }
buzbee311ca162013-02-28 15:56:43 -0800956 }
957 fprintf(file, " }\"];\n\n");
958 } else if (bb->block_type == kExceptionHandling) {
959 char block_name[BLOCK_NAME_LEN];
960
961 GetBlockName(bb, block_name);
962 fprintf(file, " %s [shape=invhouse];\n", block_name);
963 }
964
965 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
966
buzbee0d829482013-10-11 15:24:55 -0700967 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800968 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700969 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800970 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
971 block_name1, block_name2);
972 }
buzbee0d829482013-10-11 15:24:55 -0700973 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800974 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700975 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800976 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
977 }
978
buzbee0d829482013-10-11 15:24:55 -0700979 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800980 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
981 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700982 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
983 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700984 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800985
986 int succ_id = 0;
987 while (true) {
988 if (successor_block_info == NULL) break;
989
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700990 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700991 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800992
993 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
994 succ_id++,
995 successor_block_info->key,
996 dest_block->start_offset,
997 (next_successor_block_info != NULL) ? " | " : " ");
998
999 successor_block_info = next_successor_block_info;
1000 }
1001 fprintf(file, " }\"];\n\n");
1002
1003 GetBlockName(bb, block_name1);
1004 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1005 block_name1, bb->start_offset, bb->id);
1006
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001007 // Link the successor pseudo-block with all of its potential targets.
1008 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001009
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001010 succ_id = 0;
1011 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001012 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001013 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001014
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001015 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001016
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001017 GetBlockName(dest_block, block_name2);
1018 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1019 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001020 }
1021 }
1022 fprintf(file, "\n");
1023
1024 if (cu_->verbose) {
1025 /* Display the dominator tree */
1026 GetBlockName(bb, block_name1);
1027 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1028 block_name1, block_name1);
1029 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001030 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001031 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1032 }
1033 }
1034 }
1035 fprintf(file, "}\n");
1036 fclose(file);
1037}
1038
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001039/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001040void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001041 // Insert it after the last MIR.
1042 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001043}
1044
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001045void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1046 // Insert it after the last MIR.
1047 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1048}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001049
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001050void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1051 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1052 MIR* new_mir = *it;
1053
1054 // Add a copy of each MIR.
1055 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1056 }
buzbee1fd33462013-03-25 13:40:45 -07001057}
1058
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001059/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001060void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001061 InsertMIRListAfter(current_mir, new_mir, new_mir);
1062}
buzbee1fd33462013-03-25 13:40:45 -07001063
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001064void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1065 // If no MIR, we are done.
1066 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1067 return;
buzbee1fd33462013-03-25 13:40:45 -07001068 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001069
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001070 // If insert_after is null, assume BB is empty.
1071 if (insert_after == nullptr) {
1072 first_mir_insn = first_list_mir;
1073 last_mir_insn = last_list_mir;
1074 last_list_mir->next = nullptr;
1075 } else {
1076 MIR* after_list = insert_after->next;
1077 insert_after->next = first_list_mir;
1078 last_list_mir->next = after_list;
1079 if (after_list == nullptr) {
1080 last_mir_insn = last_list_mir;
1081 }
1082 }
1083
1084 // Set this BB to be the basic block of the MIRs.
1085 MIR* last = last_list_mir->next;
1086 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1087 mir->bb = id;
1088 }
1089}
1090
1091/* Insert an MIR instruction to the head of a basic block. */
1092void BasicBlock::PrependMIR(MIR* mir) {
1093 InsertMIRListBefore(first_mir_insn, mir, mir);
1094}
1095
1096void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1097 // Insert it before the first MIR.
1098 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1099}
1100
1101void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1102 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1103 MIR* mir = *it;
1104
1105 InsertMIRListBefore(first_mir_insn, mir, mir);
1106 }
1107}
1108
1109/* Insert a MIR instruction before the specified MIR. */
1110void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1111 // Insert as a single element list.
1112 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001113}
1114
1115MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1116 MIR* current = first_mir_insn;
1117
1118 while (current != nullptr) {
1119 MIR* next = current->next;
1120
1121 if (next == mir) {
1122 return current;
1123 }
1124
1125 current = next;
1126 }
1127
1128 return nullptr;
1129}
1130
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001131void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1132 // If no MIR, we are done.
1133 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1134 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001135 }
1136
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001137 // If insert_before is null, assume BB is empty.
1138 if (insert_before == nullptr) {
1139 first_mir_insn = first_list_mir;
1140 last_mir_insn = last_list_mir;
1141 last_list_mir->next = nullptr;
1142 } else {
1143 if (first_mir_insn == insert_before) {
1144 last_list_mir->next = first_mir_insn;
1145 first_mir_insn = first_list_mir;
1146 } else {
1147 // Find the preceding MIR.
1148 MIR* before_list = FindPreviousMIR(insert_before);
1149 DCHECK(before_list != nullptr);
1150 before_list->next = first_list_mir;
1151 last_list_mir->next = insert_before;
1152 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001153 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001154
1155 // Set this BB to be the basic block of the MIRs.
1156 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1157 mir->bb = id;
1158 }
1159}
1160
1161bool BasicBlock::RemoveMIR(MIR* mir) {
1162 // Remove as a single element list.
1163 return RemoveMIRList(mir, mir);
1164}
1165
1166bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1167 if (first_list_mir == nullptr) {
1168 return false;
1169 }
1170
1171 // Try to find the MIR.
1172 MIR* before_list = nullptr;
1173 MIR* after_list = nullptr;
1174
1175 // If we are removing from the beginning of the MIR list.
1176 if (first_mir_insn == first_list_mir) {
1177 before_list = nullptr;
1178 } else {
1179 before_list = FindPreviousMIR(first_list_mir);
1180 if (before_list == nullptr) {
1181 // We did not find the mir.
1182 return false;
1183 }
1184 }
1185
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001186 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001187 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1188 mir->bb = NullBasicBlockId;
1189 }
1190
1191 after_list = last_list_mir->next;
1192
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001193 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001194 if (before_list == nullptr) {
1195 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001196 } else {
1197 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001198 }
1199
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001200 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001201 if (after_list == nullptr) {
1202 last_mir_insn = before_list;
1203 }
1204
1205 return true;
buzbee1fd33462013-03-25 13:40:45 -07001206}
1207
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001208MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001209 MIR* next_mir = nullptr;
1210
1211 if (current != nullptr) {
1212 next_mir = current->next;
1213 }
1214
1215 if (next_mir == nullptr) {
1216 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001217 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1218 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001219 }
1220 }
1221
1222 return next_mir;
1223}
1224
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001225char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001226 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001227 std::string str;
1228 int flags = 0;
1229 int opcode = insn.opcode;
1230 char* ret;
1231 bool nop = false;
1232 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001233 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001234
1235 // Handle special cases.
1236 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1237 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1238 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001239 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001240 insn = mir->meta.throw_insn->dalvikInsn;
1241 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001242 opcode = insn.opcode;
1243 } else if (opcode == kMirOpNop) {
1244 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001245 // Recover original opcode.
1246 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1247 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001248 nop = true;
1249 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001250 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1251 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001252
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001253 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001254 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1255 } else {
1256 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001257 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001258 str.append(Instruction::Name(insn.opcode));
1259 }
1260
1261 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001262 BasicBlockId* incoming = mir->meta.phi_incoming;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001263 if (defs > 0 && uses > 0) {
1264 str.append(StringPrintf(" %s = (%s",
1265 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1266 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1267 str.append(StringPrintf(":%d", incoming[0]));
1268 int i;
1269 for (i = 1; i < uses; i++) {
1270 str.append(StringPrintf(", %s:%d",
1271 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1272 incoming[i]));
1273 }
1274 str.append(")");
1275 } else {
1276 str.append(StringPrintf(" v%d", mir->dalvikInsn.vA));
buzbee1fd33462013-03-25 13:40:45 -07001277 }
buzbee1fd33462013-03-25 13:40:45 -07001278 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001279 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001280 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1281 (dalvik_format == Instruction::k3rc));
1282 if (defs != 0) {
1283 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1284 if (uses != 0) {
1285 str.append(", ");
1286 }
1287 }
1288 for (int i = 0; i < uses; i++) {
1289 str.append(
1290 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1291 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1292 // For the listing, skip the high sreg.
1293 i++;
1294 }
1295 if (i != (uses -1)) {
1296 str.append(",");
1297 }
1298 }
1299 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001300 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001301 case Instruction::k21s:
1302 case Instruction::k31i:
1303 case Instruction::k21h:
1304 str.append(StringPrintf(", #%d", insn.vB));
1305 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001306 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001307 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001308 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001309 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001310 case Instruction::k31c:
1311 str.append(StringPrintf(", index #%d", insn.vB));
1312 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001313 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001314 str.append(StringPrintf(", index #%d", insn.vC));
1315 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001316 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001317 case Instruction::k22b:
1318 str.append(StringPrintf(", #%d", insn.vC));
1319 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001320 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001321 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001322 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001323 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001324 if ((flags & Instruction::kBranch) != 0) {
1325 // For branches, decode the instructions to print out the branch targets.
1326 int offset = 0;
1327 switch (dalvik_format) {
1328 case Instruction::k21t:
1329 offset = insn.vB;
1330 break;
1331 case Instruction::k22t:
1332 offset = insn.vC;
1333 break;
1334 case Instruction::k10t:
1335 case Instruction::k20t:
1336 case Instruction::k30t:
1337 offset = insn.vA;
1338 break;
1339 default:
1340 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1341 }
1342 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1343 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1344 }
buzbee1fd33462013-03-25 13:40:45 -07001345 }
1346 if (nop) {
1347 str.append("]--optimized away");
1348 }
1349 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001350 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001351 strncpy(ret, str.c_str(), length);
1352 return ret;
1353}
1354
1355/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001356void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001357 static const struct { const char before; const char after; } match[] = {
1358 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1359 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1360 };
buzbee1fd33462013-03-25 13:40:45 -07001361 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1362 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1363 }
1364}
1365
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001366std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001367 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1368 // the arena. We should be smarter and just place straight into the arena, or compute the
1369 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001370 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1371}
1372
1373// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001374std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001375 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001376 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001377 return GetSSAName(ssa_reg);
1378 }
1379 if (IsConst(reg_location_[ssa_reg])) {
1380 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001381 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001382 ConstantValueWide(reg_location_[ssa_reg]));
1383 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001384 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001385 ConstantValue(reg_location_[ssa_reg]));
1386 }
1387 } else {
1388 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1389 }
1390}
1391
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001392void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001393 switch (bb->block_type) {
1394 case kEntryBlock:
1395 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1396 break;
1397 case kExitBlock:
1398 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1399 break;
1400 case kDalvikByteCode:
1401 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1402 break;
1403 case kExceptionHandling:
1404 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1405 bb->id);
1406 break;
1407 default:
1408 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1409 break;
1410 }
1411}
1412
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001413const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001414 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001415 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1416 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1417}
1418
1419/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001420void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001421 BasicBlock* bb;
1422 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001423 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001424 "Entry Block",
1425 "Code Block",
1426 "Exit Block",
1427 "Exception Handling",
1428 "Catch Block"
1429 };
1430
1431 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1432 LOG(INFO) << cu_->insns << " insns";
1433 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001434 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001435
1436 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001437 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001438 if (bb == NULL) break;
1439 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1440 bb->id,
1441 block_type_names[bb->block_type],
1442 bb->start_offset,
1443 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1444 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001445 if (bb->taken != NullBasicBlockId) {
1446 LOG(INFO) << " Taken branch: block " << bb->taken
1447 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001448 }
buzbee0d829482013-10-11 15:24:55 -07001449 if (bb->fall_through != NullBasicBlockId) {
1450 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1451 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001452 }
1453 }
1454}
1455
1456/*
1457 * Build an array of location records for the incoming arguments.
1458 * Note: one location record per word of arguments, with dummy
1459 * high-word loc for wide arguments. Also pull up any following
1460 * MOVE_RESULT and incorporate it into the invoke.
1461 */
1462CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001463 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001464 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001465 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001466 MIR* move_result_mir = FindMoveResult(bb, mir);
1467 if (move_result_mir == NULL) {
1468 info->result.location = kLocInvalid;
1469 } else {
1470 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001471 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1472 }
1473 info->num_arg_words = mir->ssa_rep->num_uses;
1474 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001475 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001476 for (int i = 0; i < info->num_arg_words; i++) {
1477 info->args[i] = GetRawSrc(mir, i);
1478 }
1479 info->opt_flags = mir->optimization_flags;
1480 info->type = type;
1481 info->is_range = is_range;
1482 info->index = mir->dalvikInsn.vB;
1483 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001484 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001485 return info;
1486}
1487
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001488// Allocate a new MIR.
1489MIR* MIRGraph::NewMIR() {
1490 MIR* mir = new (arena_) MIR();
1491 return mir;
1492}
1493
buzbee862a7602013-04-05 10:58:54 -07001494// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001495BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001496 BasicBlock* bb = new (arena_) BasicBlock();
1497
buzbee862a7602013-04-05 10:58:54 -07001498 bb->block_type = block_type;
1499 bb->id = block_id;
1500 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001501 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001502 (block_type == kExitBlock) ? 2048 : 2,
1503 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001504 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001505 block_id_map_.Put(block_id, block_id);
1506 return bb;
1507}
buzbee1fd33462013-03-25 13:40:45 -07001508
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001509void MIRGraph::InitializeConstantPropagation() {
1510 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001511 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001512}
1513
1514void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001515 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001516 int num_ssa_regs = GetNumSSARegs();
1517 use_counts_.Resize(num_ssa_regs + 32);
1518 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001519 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001520 for (int i = 0; i < num_ssa_regs; i++) {
1521 use_counts_.Insert(0);
1522 raw_use_counts_.Insert(0);
1523 }
1524}
1525
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001526void MIRGraph::SSATransformationStart() {
1527 DCHECK(temp_scoped_alloc_.get() == nullptr);
1528 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1529 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1530 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1531 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1532
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001533 // Update the maximum number of reachable blocks.
1534 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001535}
1536
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001537void MIRGraph::SSATransformationEnd() {
1538 // Verify the dataflow information after the pass.
1539 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1540 VerifyDataflow();
1541 }
1542
1543 temp_bit_vector_size_ = 0u;
1544 temp_bit_vector_ = nullptr;
1545 DCHECK(temp_scoped_alloc_.get() != nullptr);
1546 temp_scoped_alloc_.reset();
1547}
1548
Vladimir Marko55fff042014-07-10 12:42:52 +01001549static BasicBlock* SelectTopologicalSortOrderFallBack(
1550 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1551 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1552 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1553 // No true loop head has been found but there may be true loop heads after the mess we need
1554 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1555 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1556 BasicBlock* fall_back = nullptr;
1557 size_t fall_back_num_reachable = 0u;
1558 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1559 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1560 AllNodesIterator iter(mir_graph);
1561 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1562 if (candidate->hidden || // Hidden, or
1563 candidate->visited || // already processed, or
1564 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1565 (current_loop != nullptr && // outside current loop.
1566 !current_loop->IsBitSet(candidate->id))) {
1567 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001568 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001569 DCHECK(tmp_stack->empty());
1570 tmp_stack->push_back(candidate->id);
1571 candidate_reachable.ClearAllBits();
1572 size_t num_reachable = 0u;
1573 while (!tmp_stack->empty()) {
1574 BasicBlockId current_id = tmp_stack->back();
1575 tmp_stack->pop_back();
1576 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1577 DCHECK(current_bb != nullptr);
1578 ChildBlockIterator child_iter(current_bb, mir_graph);
1579 BasicBlock* child_bb = child_iter.Next();
1580 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1581 DCHECK(!child_bb->hidden);
1582 if (child_bb->visited || // Already processed, or
1583 (current_loop != nullptr && // outside current loop.
1584 !current_loop->IsBitSet(child_bb->id))) {
1585 continue;
1586 }
1587 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1588 candidate_reachable.SetBit(child_bb->id);
1589 tmp_stack->push_back(child_bb->id);
1590 num_reachable += 1u;
1591 }
1592 }
1593 }
1594 if (fall_back_num_reachable < num_reachable) {
1595 fall_back_num_reachable = num_reachable;
1596 fall_back = candidate;
1597 }
1598 }
1599 return fall_back;
1600}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001601
Vladimir Marko55fff042014-07-10 12:42:52 +01001602// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1603static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1604 ArenaBitVector* reachable,
1605 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1606 // NOTE: Loop heads indicated by the "visited" flag.
1607 DCHECK(tmp_stack->empty());
1608 reachable->ClearAllBits();
1609 tmp_stack->push_back(bb_id);
1610 while (!tmp_stack->empty()) {
1611 BasicBlockId current_id = tmp_stack->back();
1612 tmp_stack->pop_back();
1613 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1614 DCHECK(current_bb != nullptr);
1615 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1616 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1617 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1618 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1619 reachable->SetBit(pred_bb->id);
1620 tmp_stack->push_back(pred_bb->id);
1621 }
1622 }
1623 }
1624}
1625
1626void MIRGraph::ComputeTopologicalSortOrder() {
1627 ScopedArenaAllocator allocator(&cu_->arena_stack);
1628 unsigned int num_blocks = GetNumBlocks();
1629
1630 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1631 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1632 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1633 size_t max_nested_loops = 0u;
1634 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1635 loop_exit_blocks.ClearAllBits();
1636
1637 // Count the number of blocks to process and add the entry block(s).
1638 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1639 unsigned int num_blocks_to_process = 0u;
1640 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001641 if (bb->hidden == true) {
1642 continue;
1643 }
1644
Vladimir Marko55fff042014-07-10 12:42:52 +01001645 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001646
Vladimir Marko55fff042014-07-10 12:42:52 +01001647 if (bb->predecessors->Size() == 0u) {
1648 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001649 q.push(bb);
1650 }
1651 }
1652
Vladimir Marko55fff042014-07-10 12:42:52 +01001653 // Create the topological order if need be.
1654 if (topological_order_ == nullptr) {
1655 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1656 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1657 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1658 }
1659 topological_order_->Reset();
1660 topological_order_loop_ends_->Reset();
1661 topological_order_indexes_->Reset();
1662 topological_order_loop_ends_->Resize(num_blocks);
1663 topological_order_indexes_->Resize(num_blocks);
1664 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1665 topological_order_loop_ends_->Insert(0u);
1666 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1667 }
1668
1669 // Mark all blocks as unvisited.
1670 ClearAllVisitedFlags();
1671
1672 // For loop heads, keep track from which blocks they are reachable not going through other
1673 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1674 // in this set go into the loop body, the other children are jumping over the loop.
1675 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1676 loop_head_reachable_from.resize(num_blocks, nullptr);
1677 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1678 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1679
1680 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001681 BasicBlock* bb = nullptr;
1682 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001683 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001684 // Get top.
1685 bb = q.front();
1686 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001687 if (bb->visited) {
1688 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1689 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1690 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1691 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1692 DCHECK_EQ(loop_head_stack.back(), bb->id);
1693 loop_head_stack.pop_back();
1694 ArenaBitVector* reachable =
1695 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1696 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1697 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1698 q.push(GetBasicBlock(candidate_id));
1699 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1700 // so clearing the bit has no effect on the iterator.
1701 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001702 }
1703 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001704 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001705 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001706 } else {
1707 // Find the new loop head.
1708 AllNodesIterator iter(this);
1709 while (true) {
1710 BasicBlock* candidate = iter.Next();
1711 if (candidate == nullptr) {
1712 // We did not find a true loop head, fall back to a reachable block in any loop.
1713 ArenaBitVector* current_loop =
1714 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1715 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1716 &allocator, &tmp_stack);
1717 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1718 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1719 LOG(INFO) << "Topological sort order: Using fall-back in "
1720 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1721 << " @0x" << std::hex << bb->start_offset
1722 << ", num_blocks = " << std::dec << num_blocks;
1723 }
1724 break;
1725 }
1726 if (candidate->hidden || // Hidden, or
1727 candidate->visited || // already processed, or
1728 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1729 (!loop_head_stack.empty() && // outside current loop.
1730 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1731 continue;
1732 }
1733
1734 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1735 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1736 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1737 if (pred_bb != candidate && !pred_bb->visited &&
1738 !pred_bb->dominators->IsBitSet(candidate->id)) {
1739 break; // Keep non-null pred_bb to indicate failure.
1740 }
1741 }
1742 if (pred_bb == nullptr) {
1743 bb = candidate;
1744 break;
1745 }
1746 }
1747 // Compute blocks from which the loop head is reachable and process those blocks first.
1748 ArenaBitVector* reachable =
1749 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1750 loop_head_reachable_from[bb->id] = reachable;
1751 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1752 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1753 loop_head_stack.push_back(bb->id);
1754 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001755 }
1756
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001757 DCHECK_EQ(bb->hidden, false);
1758 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001759 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001760
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001761 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001762 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1763 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001764 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001765
Vladimir Marko55fff042014-07-10 12:42:52 +01001766 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001767 ChildBlockIterator succIter(bb, this);
1768 BasicBlock* successor = succIter.Next();
1769 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001770 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001771 continue;
1772 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001773
Vladimir Marko55fff042014-07-10 12:42:52 +01001774 // One more predecessor was visited.
1775 visited_cnt_values[successor->id] += 1u;
1776 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1777 if (loop_head_stack.empty() ||
1778 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1779 q.push(successor);
1780 } else {
1781 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1782 loop_exit_blocks.SetBit(successor->id);
1783 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001784 }
1785 }
1786 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001787
1788 // Prepare the loop head stack for iteration.
1789 topological_order_loop_head_stack_ =
1790 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001791}
1792
1793bool BasicBlock::IsExceptionBlock() const {
1794 if (block_type == kExceptionHandling) {
1795 return true;
1796 }
1797 return false;
1798}
1799
Wei Jin04f4d8a2014-05-29 18:04:29 -07001800bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1801 BasicBlock* target = GetBasicBlock(target_id);
1802
1803 if (source == nullptr || target == nullptr)
1804 return false;
1805
1806 int idx;
1807 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1808 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1809 if (bb == source)
1810 return true; // The block has been inserted by a suspend check before.
1811 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1812 return true;
1813 }
1814
1815 return false;
1816}
1817
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001818ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1819 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1820 visited_taken_(false), have_successors_(false) {
1821 // Check if we actually do have successors.
1822 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1823 have_successors_ = true;
1824 successor_iter_.Reset(basic_block_->successor_blocks);
1825 }
1826}
1827
1828BasicBlock* ChildBlockIterator::Next() {
1829 // We check if we have a basic block. If we don't we cannot get next child.
1830 if (basic_block_ == nullptr) {
1831 return nullptr;
1832 }
1833
1834 // If we haven't visited fallthrough, return that.
1835 if (visited_fallthrough_ == false) {
1836 visited_fallthrough_ = true;
1837
1838 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1839 if (result != nullptr) {
1840 return result;
1841 }
1842 }
1843
1844 // If we haven't visited taken, return that.
1845 if (visited_taken_ == false) {
1846 visited_taken_ = true;
1847
1848 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1849 if (result != nullptr) {
1850 return result;
1851 }
1852 }
1853
1854 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1855 if (have_successors_ == true) {
1856 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07001857 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1858 successor_block_info != nullptr;
1859 successor_block_info = successor_iter_.Next()) {
1860 // If block was replaced by zero block, take next one.
1861 if (successor_block_info->block != NullBasicBlockId) {
1862 return mir_graph_->GetBasicBlock(successor_block_info->block);
1863 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001864 }
1865 }
1866
1867 // We do not have anything.
1868 return nullptr;
1869}
1870
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001871BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1872 MIRGraph* mir_graph = c_unit->mir_graph.get();
1873 return Copy(mir_graph);
1874}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001875
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001876BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1877 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001878
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001879 // We don't do a memcpy style copy here because it would lead to a lot of things
1880 // to clean up. Let us do it by hand instead.
1881 // Copy in taken and fallthrough.
1882 result_bb->fall_through = fall_through;
1883 result_bb->taken = taken;
1884
1885 // Copy successor links if needed.
1886 ArenaAllocator* arena = mir_graph->GetArena();
1887
1888 result_bb->successor_block_list_type = successor_block_list_type;
1889 if (result_bb->successor_block_list_type != kNotUsed) {
1890 size_t size = successor_blocks->Size();
1891 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1892 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1893 while (true) {
1894 SuccessorBlockInfo* sbi_old = iterator.Next();
1895 if (sbi_old == nullptr) {
1896 break;
1897 }
1898 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1899 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1900 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001901 }
1902 }
1903
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001904 // Copy offset, method.
1905 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001906
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001907 // Now copy instructions.
1908 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1909 // Get a copy first.
1910 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001911
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001912 // Append it.
1913 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001914 }
1915
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001916 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001917}
1918
1919MIR* MIR::Copy(MIRGraph* mir_graph) {
1920 MIR* res = mir_graph->NewMIR();
1921 *res = *this;
1922
1923 // Remove links
1924 res->next = nullptr;
1925 res->bb = NullBasicBlockId;
1926 res->ssa_rep = nullptr;
1927
1928 return res;
1929}
1930
1931MIR* MIR::Copy(CompilationUnit* c_unit) {
1932 return Copy(c_unit->mir_graph.get());
1933}
1934
1935uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1936 // Default result.
1937 int res = 0;
1938
1939 // We are basically setting the iputs to their igets counterparts.
1940 switch (opcode) {
1941 case Instruction::IPUT:
1942 case Instruction::IPUT_OBJECT:
1943 case Instruction::IPUT_BOOLEAN:
1944 case Instruction::IPUT_BYTE:
1945 case Instruction::IPUT_CHAR:
1946 case Instruction::IPUT_SHORT:
1947 case Instruction::IPUT_QUICK:
1948 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07001949 case Instruction::IPUT_BOOLEAN_QUICK:
1950 case Instruction::IPUT_BYTE_QUICK:
1951 case Instruction::IPUT_CHAR_QUICK:
1952 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001953 case Instruction::APUT:
1954 case Instruction::APUT_OBJECT:
1955 case Instruction::APUT_BOOLEAN:
1956 case Instruction::APUT_BYTE:
1957 case Instruction::APUT_CHAR:
1958 case Instruction::APUT_SHORT:
1959 case Instruction::SPUT:
1960 case Instruction::SPUT_OBJECT:
1961 case Instruction::SPUT_BOOLEAN:
1962 case Instruction::SPUT_BYTE:
1963 case Instruction::SPUT_CHAR:
1964 case Instruction::SPUT_SHORT:
1965 // Skip the VR containing what to store.
1966 res = 1;
1967 break;
1968 case Instruction::IPUT_WIDE:
1969 case Instruction::IPUT_WIDE_QUICK:
1970 case Instruction::APUT_WIDE:
1971 case Instruction::SPUT_WIDE:
1972 // Skip the two VRs containing what to store.
1973 res = 2;
1974 break;
1975 default:
1976 // Do nothing in the general case.
1977 break;
1978 }
1979
1980 return res;
1981}
1982
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001983/**
1984 * @brief Given a decoded instruction, it checks whether the instruction
1985 * sets a constant and if it does, more information is provided about the
1986 * constant being set.
1987 * @param ptr_value pointer to a 64-bit holder for the constant.
1988 * @param wide Updated by function whether a wide constant is being set by bytecode.
1989 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1990 */
1991bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1992 bool sets_const = true;
1993 int64_t value = vB;
1994
1995 DCHECK(ptr_value != nullptr);
1996 DCHECK(wide != nullptr);
1997
1998 switch (opcode) {
1999 case Instruction::CONST_4:
2000 case Instruction::CONST_16:
2001 case Instruction::CONST:
2002 *wide = false;
2003 value <<= 32; // In order to get the sign extend.
2004 value >>= 32;
2005 break;
2006 case Instruction::CONST_HIGH16:
2007 *wide = false;
2008 value <<= 48; // In order to get the sign extend.
2009 value >>= 32;
2010 break;
2011 case Instruction::CONST_WIDE_16:
2012 case Instruction::CONST_WIDE_32:
2013 *wide = true;
2014 value <<= 32; // In order to get the sign extend.
2015 value >>= 32;
2016 break;
2017 case Instruction::CONST_WIDE:
2018 *wide = true;
2019 value = vB_wide;
2020 break;
2021 case Instruction::CONST_WIDE_HIGH16:
2022 *wide = true;
2023 value <<= 48; // In order to get the sign extend.
2024 break;
2025 default:
2026 sets_const = false;
2027 break;
2028 }
2029
2030 if (sets_const) {
2031 *ptr_value = value;
2032 }
2033
2034 return sets_const;
2035}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002036
2037void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2038 // Reset flags for all MIRs in bb.
2039 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2040 mir->optimization_flags &= (~reset_flags);
2041 }
2042}
2043
2044void BasicBlock::Hide(CompilationUnit* c_unit) {
2045 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2046 block_type = kDalvikByteCode;
2047
2048 // Mark it as hidden.
2049 hidden = true;
2050
2051 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2052 // are updated to know that they no longer have a parent.
2053 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2054 mir->bb = NullBasicBlockId;
2055 }
2056 first_mir_insn = nullptr;
2057 last_mir_insn = nullptr;
2058
2059 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2060
2061 MIRGraph* mir_graph = c_unit->mir_graph.get();
2062 while (true) {
2063 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2064 if (pred_bb == nullptr) {
2065 break;
2066 }
2067
2068 // Sadly we have to go through the children by hand here.
2069 pred_bb->ReplaceChild(id, NullBasicBlockId);
2070 }
2071
2072 // Iterate through children of bb we are hiding.
2073 ChildBlockIterator successorChildIter(this, mir_graph);
2074
2075 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2076 // Replace child with null child.
2077 childPtr->predecessors->Delete(id);
2078 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002079
2080 // Remove link to children.
2081 taken = NullBasicBlockId;
2082 fall_through = NullBasicBlockId;
2083 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002084}
2085
2086bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2087 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2088 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2089 // then it is not live out of this BB.
2090 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2091
2092 int last_ssa_reg = -1;
2093
2094 // Walk through the MIRs backwards.
2095 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2096 // Get ssa rep.
2097 SSARepresentation *ssa_rep = mir->ssa_rep;
2098
2099 // Go through the defines for this MIR.
2100 for (int i = 0; i < ssa_rep->num_defs; i++) {
2101 DCHECK(ssa_rep->defs != nullptr);
2102
2103 // Get the ssa reg.
2104 int def_ssa_reg = ssa_rep->defs[i];
2105
2106 // Get dalvik reg.
2107 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2108
2109 // Compare dalvik regs.
2110 if (dalvik_reg == def_dalvik_reg) {
2111 // We found a def of the register that we are being asked about.
2112 // Remember it.
2113 last_ssa_reg = def_ssa_reg;
2114 }
2115 }
2116 }
2117
2118 if (last_ssa_reg == -1) {
2119 // If we get to this point we couldn't find a define of register user asked about.
2120 // Let's assume the user knows what he's doing so we can be safe and say that if we
2121 // couldn't find a def, it is live out.
2122 return true;
2123 }
2124
2125 // If it is not -1, we found a match, is it ssa_reg?
2126 return (ssa_reg == last_ssa_reg);
2127}
2128
2129bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2130 // We need to check taken, fall_through, and successor_blocks to replace.
2131 bool found = false;
2132 if (taken == old_bb) {
2133 taken = new_bb;
2134 found = true;
2135 }
2136
2137 if (fall_through == old_bb) {
2138 fall_through = new_bb;
2139 found = true;
2140 }
2141
2142 if (successor_block_list_type != kNotUsed) {
2143 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2144 while (true) {
2145 SuccessorBlockInfo* successor_block_info = iterator.Next();
2146 if (successor_block_info == nullptr) {
2147 break;
2148 }
2149 if (successor_block_info->block == old_bb) {
2150 successor_block_info->block = new_bb;
2151 found = true;
2152 }
2153 }
2154 }
2155
2156 return found;
2157}
2158
2159void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2160 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2161 bool found = false;
2162
2163 while (true) {
2164 BasicBlockId pred_bb_id = iterator.Next();
2165
2166 if (pred_bb_id == NullBasicBlockId) {
2167 break;
2168 }
2169
2170 if (pred_bb_id == old_parent) {
2171 size_t idx = iterator.GetIndex() - 1;
2172 predecessors->Put(idx, new_parent);
2173 found = true;
2174 break;
2175 }
2176 }
2177
2178 // If not found, add it.
2179 if (found == false) {
2180 predecessors->Insert(new_parent);
2181 }
2182}
2183
2184// Create a new basic block with block_id as num_blocks_ that is
2185// post-incremented.
2186BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2187 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2188 block_list_.Insert(res);
2189 return res;
2190}
2191
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002192void MIRGraph::CalculateBasicBlockInformation() {
2193 PassDriverMEPostOpt driver(cu_);
2194 driver.Launch();
2195}
2196
2197void MIRGraph::InitializeBasicBlockData() {
2198 num_blocks_ = block_list_.Size();
2199}
2200
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002201int MIR::DecodedInstruction::FlagsOf() const {
2202 // Calculate new index.
2203 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2204
2205 // Check if it is an extended or not.
2206 if (idx < 0) {
2207 return Instruction::FlagsOf(opcode);
2208 }
2209
2210 // For extended, we use a switch.
2211 switch (static_cast<int>(opcode)) {
2212 case kMirOpPhi:
2213 return Instruction::kContinue;
2214 case kMirOpCopy:
2215 return Instruction::kContinue;
2216 case kMirOpFusedCmplFloat:
2217 return Instruction::kContinue | Instruction::kBranch;
2218 case kMirOpFusedCmpgFloat:
2219 return Instruction::kContinue | Instruction::kBranch;
2220 case kMirOpFusedCmplDouble:
2221 return Instruction::kContinue | Instruction::kBranch;
2222 case kMirOpFusedCmpgDouble:
2223 return Instruction::kContinue | Instruction::kBranch;
2224 case kMirOpFusedCmpLong:
2225 return Instruction::kContinue | Instruction::kBranch;
2226 case kMirOpNop:
2227 return Instruction::kContinue;
2228 case kMirOpNullCheck:
2229 return Instruction::kContinue | Instruction::kThrow;
2230 case kMirOpRangeCheck:
2231 return Instruction::kContinue | Instruction::kThrow;
2232 case kMirOpDivZeroCheck:
2233 return Instruction::kContinue | Instruction::kThrow;
2234 case kMirOpCheck:
2235 return 0;
2236 case kMirOpCheckPart2:
2237 return 0;
2238 case kMirOpSelect:
2239 return Instruction::kContinue;
2240 case kMirOpConstVector:
2241 return Instruction::kContinue;
2242 case kMirOpMoveVector:
2243 return Instruction::kContinue;
2244 case kMirOpPackedMultiply:
2245 return Instruction::kContinue;
2246 case kMirOpPackedAddition:
2247 return Instruction::kContinue;
2248 case kMirOpPackedSubtract:
2249 return Instruction::kContinue;
2250 case kMirOpPackedShiftLeft:
2251 return Instruction::kContinue;
2252 case kMirOpPackedSignedShiftRight:
2253 return Instruction::kContinue;
2254 case kMirOpPackedUnsignedShiftRight:
2255 return Instruction::kContinue;
2256 case kMirOpPackedAnd:
2257 return Instruction::kContinue;
2258 case kMirOpPackedOr:
2259 return Instruction::kContinue;
2260 case kMirOpPackedXor:
2261 return Instruction::kContinue;
2262 case kMirOpPackedAddReduce:
2263 return Instruction::kContinue;
2264 case kMirOpPackedReduce:
2265 return Instruction::kContinue;
2266 case kMirOpPackedSet:
2267 return Instruction::kContinue;
2268 case kMirOpReserveVectorRegisters:
2269 return Instruction::kContinue;
2270 case kMirOpReturnVectorRegisters:
2271 return Instruction::kContinue;
2272 default:
2273 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2274 return 0;
2275 }
2276}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002277} // namespace art