blob: 462e129c87c2f52470dbf675d888658f49f4c393 [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),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800122 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700123 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
124 requested_backend_temp_(false),
125 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000126 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000127 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000128 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000129 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700130 method_lowering_infos_(arena, 0u),
131 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700132 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700133
134
135 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
136 // X86 requires a temp to keep track of the method address.
137 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
138 // this needs to be updated to reserve 0 temps for BE.
139 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
140 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
141 } else {
142 // Other architectures do not have a known lower bound for non-special temps.
143 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
144 max_available_non_special_compiler_temps_ = 0;
145 reserved_temps_for_backend_ = 0;
146 }
buzbee311ca162013-02-28 15:56:43 -0800147}
148
Ian Rogers6282dc12013-04-18 15:54:02 -0700149MIRGraph::~MIRGraph() {
150 STLDeleteElements(&m_units_);
151}
152
buzbee311ca162013-02-28 15:56:43 -0800153/*
154 * Parse an instruction, return the length of the instruction
155 */
Ian Rogers29a26482014-05-02 15:27:29 -0700156int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
157 const Instruction* inst = Instruction::At(code_ptr);
158 decoded_instruction->opcode = inst->Opcode();
159 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
160 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
161 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
162 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
163 if (inst->HasVarArgs()) {
164 inst->GetVarArgs(decoded_instruction->arg);
165 }
166 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800167}
168
169
170/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700171BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700172 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700173 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800174 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700175 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800176 while (insn) {
177 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700178 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800179 insn = insn->next;
180 }
181 if (insn == NULL) {
182 LOG(FATAL) << "Break split failed";
183 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700184 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700185 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800186
187 bottom_block->start_offset = code_offset;
188 bottom_block->first_mir_insn = insn;
189 bottom_block->last_mir_insn = orig_block->last_mir_insn;
190
Junmo Park90223cc2014-08-04 18:51:21 +0900191 /* If this block was terminated by a return, conditional branch or throw,
192 * the flag needs to go with the bottom block
193 */
buzbee311ca162013-02-28 15:56:43 -0800194 bottom_block->terminated_by_return = orig_block->terminated_by_return;
195 orig_block->terminated_by_return = false;
196
Junmo Park90223cc2014-08-04 18:51:21 +0900197 bottom_block->conditional_branch = orig_block->conditional_branch;
198 orig_block->conditional_branch = false;
199
200 bottom_block->explicit_throw = orig_block->explicit_throw;
201 orig_block->explicit_throw = false;
202
buzbee311ca162013-02-28 15:56:43 -0800203 /* Handle the taken path */
204 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700205 if (bottom_block->taken != NullBasicBlockId) {
206 orig_block->taken = NullBasicBlockId;
207 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
208 bb_taken->predecessors->Delete(orig_block->id);
209 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800210 }
211
212 /* Handle the fallthrough path */
213 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700214 orig_block->fall_through = bottom_block->id;
215 bottom_block->predecessors->Insert(orig_block->id);
216 if (bottom_block->fall_through != NullBasicBlockId) {
217 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
218 bb_fall_through->predecessors->Delete(orig_block->id);
219 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800220 }
221
222 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700223 if (orig_block->successor_block_list_type != kNotUsed) {
224 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
225 bottom_block->successor_blocks = orig_block->successor_blocks;
226 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700227 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700228 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800229 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700230 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700231 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700232 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700233 if (bb != nullptr) {
234 bb->predecessors->Delete(orig_block->id);
235 bb->predecessors->Insert(bottom_block->id);
236 }
buzbee311ca162013-02-28 15:56:43 -0800237 }
238 }
239
buzbee0d829482013-10-11 15:24:55 -0700240 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700241 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800242
buzbee311ca162013-02-28 15:56:43 -0800243 /*
244 * Update the immediate predecessor block pointer so that outgoing edges
245 * can be applied to the proper block.
246 */
247 if (immed_pred_block_p) {
248 DCHECK_EQ(*immed_pred_block_p, orig_block);
249 *immed_pred_block_p = bottom_block;
250 }
buzbeeb48819d2013-09-14 16:15:25 -0700251
252 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000253 DCHECK(insn != nullptr);
254 DCHECK(insn != orig_block->first_mir_insn);
255 DCHECK(insn == bottom_block->first_mir_insn);
256 DCHECK_EQ(insn->offset, bottom_block->start_offset);
257 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700258 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000259 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
260 MIR* p = insn;
261 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
262 while (p != bottom_block->last_mir_insn) {
263 p = p->next;
264 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700265 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700266 int opcode = p->dalvikInsn.opcode;
267 /*
268 * Some messiness here to ensure that we only enter real opcodes and only the
269 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000270 * CHECK and work portions. Since the 2nd half of a split operation is always
271 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700272 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700273 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000274 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700275 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
276 }
buzbeeb48819d2013-09-14 16:15:25 -0700277 }
278
buzbee311ca162013-02-28 15:56:43 -0800279 return bottom_block;
280}
281
282/*
283 * Given a code offset, find out the block that starts with it. If the offset
284 * is in the middle of an existing block, split it into two. If immed_pred_block_p
285 * is not non-null and is the block being split, update *immed_pred_block_p to
286 * point to the bottom block so that outgoing edges can be set up properly
287 * (by the caller)
288 * Utilizes a map for fast lookup of the typical cases.
289 */
buzbee0d829482013-10-11 15:24:55 -0700290BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700291 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700292 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800293 return NULL;
294 }
buzbeeb48819d2013-09-14 16:15:25 -0700295
296 int block_id = dex_pc_to_block_map_.Get(code_offset);
297 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
298
299 if ((bb != NULL) && (bb->start_offset == code_offset)) {
300 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700301 return bb;
302 }
buzbee311ca162013-02-28 15:56:43 -0800303
buzbeeb48819d2013-09-14 16:15:25 -0700304 // No direct hit.
305 if (!create) {
306 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800307 }
308
buzbeeb48819d2013-09-14 16:15:25 -0700309 if (bb != NULL) {
310 // The target exists somewhere in an existing block.
311 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
312 }
313
314 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700315 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
316 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800317 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700318 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800319 return bb;
320}
321
buzbeeb48819d2013-09-14 16:15:25 -0700322
buzbee311ca162013-02-28 15:56:43 -0800323/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700324void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800325 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700326 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800327
328 if (tries_size == 0) {
329 return;
330 }
331
332 for (int i = 0; i < tries_size; i++) {
333 const DexFile::TryItem* pTry =
334 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700335 DexOffset start_offset = pTry->start_addr_;
336 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800337 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700338 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800339 }
340 }
341
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700342 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800343 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
344 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
345 for (uint32_t idx = 0; idx < handlers_size; idx++) {
346 CatchHandlerIterator iterator(handlers_ptr);
347 for (; iterator.HasNext(); iterator.Next()) {
348 uint32_t address = iterator.GetHandlerAddress();
349 FindBlock(address, false /* split */, true /*create*/,
350 /* immed_pred_block_p */ NULL);
351 }
352 handlers_ptr = iterator.EndDataPointer();
353 }
354}
355
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100356bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
357 NarrowDexOffset catch_offset) {
358 // Catches for monitor-exit during stack unwinding have the pattern
359 // move-exception (move)* (goto)? monitor-exit throw
360 // In the currently generated dex bytecode we see these catching a bytecode range including
361 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
362 // it's the case for a given monitor-exit and catch block so that we can ignore it.
363 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
364 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
365 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700366 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100367 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
368 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700369 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100370 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
371 if (check_insn->VRegA_11x() == monitor_reg) {
372 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
373 return false;
374 }
375 check_insn = check_insn->Next();
376 while (true) {
377 int dest = -1;
378 bool wide = false;
379 switch (check_insn->Opcode()) {
380 case Instruction::MOVE_WIDE:
381 wide = true;
382 // Intentional fall-through.
383 case Instruction::MOVE_OBJECT:
384 case Instruction::MOVE:
385 dest = check_insn->VRegA_12x();
386 break;
387
388 case Instruction::MOVE_WIDE_FROM16:
389 wide = true;
390 // Intentional fall-through.
391 case Instruction::MOVE_OBJECT_FROM16:
392 case Instruction::MOVE_FROM16:
393 dest = check_insn->VRegA_22x();
394 break;
395
396 case Instruction::MOVE_WIDE_16:
397 wide = true;
398 // Intentional fall-through.
399 case Instruction::MOVE_OBJECT_16:
400 case Instruction::MOVE_16:
401 dest = check_insn->VRegA_32x();
402 break;
403
404 case Instruction::GOTO:
405 case Instruction::GOTO_16:
406 case Instruction::GOTO_32:
407 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
408 // Intentional fall-through.
409 default:
410 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
411 check_insn->VRegA_11x() == monitor_reg;
412 }
413
414 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
415 return false;
416 }
417
418 check_insn = check_insn->Next();
419 }
420}
421
buzbee311ca162013-02-28 15:56:43 -0800422/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700423BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
424 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700425 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700426 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800427 switch (insn->dalvikInsn.opcode) {
428 case Instruction::GOTO:
429 case Instruction::GOTO_16:
430 case Instruction::GOTO_32:
431 target += insn->dalvikInsn.vA;
432 break;
433 case Instruction::IF_EQ:
434 case Instruction::IF_NE:
435 case Instruction::IF_LT:
436 case Instruction::IF_GE:
437 case Instruction::IF_GT:
438 case Instruction::IF_LE:
439 cur_block->conditional_branch = true;
440 target += insn->dalvikInsn.vC;
441 break;
442 case Instruction::IF_EQZ:
443 case Instruction::IF_NEZ:
444 case Instruction::IF_LTZ:
445 case Instruction::IF_GEZ:
446 case Instruction::IF_GTZ:
447 case Instruction::IF_LEZ:
448 cur_block->conditional_branch = true;
449 target += insn->dalvikInsn.vB;
450 break;
451 default:
452 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
453 }
buzbeeb48819d2013-09-14 16:15:25 -0700454 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700455 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800456 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700457 cur_block->taken = taken_block->id;
458 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800459
460 /* Always terminate the current block for conditional branches */
461 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700462 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800463 /*
464 * If the method is processed
465 * in sequential order from the
466 * beginning, we don't need to
467 * specify split for continue
468 * blocks. However, this
469 * routine can be called by
470 * compileLoop, which starts
471 * parsing the method from an
472 * arbitrary address in the
473 * method body.
474 */
475 true,
476 /* create */
477 true,
478 /* immed_pred_block_p */
479 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700480 cur_block->fall_through = fallthrough_block->id;
481 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800482 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700483 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800484 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800485 }
486 return cur_block;
487}
488
489/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800490BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
491 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800492 const uint16_t* switch_data =
493 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
494 int size;
495 const int* keyTable;
496 const int* target_table;
497 int i;
498 int first_key;
499
500 /*
501 * Packed switch data format:
502 * ushort ident = 0x0100 magic value
503 * ushort size number of entries in the table
504 * int first_key first (and lowest) switch case value
505 * int targets[size] branch targets, relative to switch opcode
506 *
507 * Total size is (4+size*2) 16-bit code units.
508 */
509 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
510 DCHECK_EQ(static_cast<int>(switch_data[0]),
511 static_cast<int>(Instruction::kPackedSwitchSignature));
512 size = switch_data[1];
513 first_key = switch_data[2] | (switch_data[3] << 16);
514 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700515 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800516 /*
517 * Sparse switch data format:
518 * ushort ident = 0x0200 magic value
519 * ushort size number of entries in the table; > 0
520 * int keys[size] keys, sorted low-to-high; 32-bit aligned
521 * int targets[size] branch targets, relative to switch opcode
522 *
523 * Total size is (2+size*4) 16-bit code units.
524 */
525 } else {
526 DCHECK_EQ(static_cast<int>(switch_data[0]),
527 static_cast<int>(Instruction::kSparseSwitchSignature));
528 size = switch_data[1];
529 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
530 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700531 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800532 }
533
buzbee0d829482013-10-11 15:24:55 -0700534 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800535 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700536 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800537 }
buzbee0d829482013-10-11 15:24:55 -0700538 cur_block->successor_block_list_type =
539 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
540 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700541 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800542
543 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700544 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800545 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700546 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700547 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000548 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700549 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800550 successor_block_info->key =
551 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
552 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700553 cur_block->successor_blocks->Insert(successor_block_info);
554 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800555 }
556
557 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700558 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
559 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700560 cur_block->fall_through = fallthrough_block->id;
561 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800562 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800563}
564
565/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700566BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
567 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700568 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700569 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800570 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
571 bool build_all_edges =
572 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800573
574 /* In try block */
575 if (in_try_block) {
576 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
577
buzbee0d829482013-10-11 15:24:55 -0700578 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800579 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
580 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700581 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800582 }
583
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700584 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700585 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800586 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100587 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
588 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
589 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
590 continue;
591 }
592 if (cur_block->successor_block_list_type == kNotUsed) {
593 cur_block->successor_block_list_type = kCatch;
594 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
595 arena_, 2, kGrowableArraySuccessorBlocks);
596 }
buzbee311ca162013-02-28 15:56:43 -0800597 catch_block->catch_entry = true;
598 if (kIsDebugBuild) {
599 catches_.insert(catch_block->start_offset);
600 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700601 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000602 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700603 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800604 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700605 cur_block->successor_blocks->Insert(successor_block_info);
606 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800607 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100608 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
609 }
610 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700611 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700612 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700613 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800614 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700615 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800616 }
617
buzbee17189ac2013-11-08 11:07:02 -0800618 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800619 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700620 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700621 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800622 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
623 /* immed_pred_block_p */ NULL);
624 }
625 if (!in_try_block) {
626 // Don't split a THROW that can't rethrow - we're done.
627 return cur_block;
628 }
629 }
630
buzbee17189ac2013-11-08 11:07:02 -0800631 if (!build_all_edges) {
632 /*
633 * Even though there is an exception edge here, control cannot return to this
634 * method. Thus, for the purposes of dataflow analysis and optimization, we can
635 * ignore the edge. Doing this reduces compile time, and increases the scope
636 * of the basic-block level optimization pass.
637 */
638 return cur_block;
639 }
640
buzbee311ca162013-02-28 15:56:43 -0800641 /*
642 * Split the potentially-throwing instruction into two parts.
643 * The first half will be a pseudo-op that captures the exception
644 * edges and terminates the basic block. It always falls through.
645 * Then, create a new basic block that begins with the throwing instruction
646 * (minus exceptions). Note: this new basic block must NOT be entered into
647 * the block_map. If the potentially-throwing instruction is the target of a
648 * future branch, we need to find the check psuedo half. The new
649 * basic block containing the work portion of the instruction should
650 * only be entered via fallthrough from the block containing the
651 * pseudo exception edge MIR. Note also that this new block is
652 * not automatically terminated after the work portion, and may
653 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700654 *
655 * Note also that the dex_pc_to_block_map_ entry for the potentially
656 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800657 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700658 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700659 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800660 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700661 cur_block->fall_through = new_block->id;
662 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700663 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800664 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700665 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700666 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800667 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700668 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800669 return new_block;
670}
671
672/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
673void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700674 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700675 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800676 current_code_item_ = code_item;
677 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
678 current_method_ = m_units_.size();
679 current_offset_ = 0;
680 // TODO: will need to snapshot stack image and use that as the mir context identification.
681 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000682 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
683 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800684 const uint16_t* code_ptr = current_code_item_->insns_;
685 const uint16_t* code_end =
686 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
687
688 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700689 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700690 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700691 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 -0700692
buzbee311ca162013-02-28 15:56:43 -0800693 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700694 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
695 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800696
697 // If this is the first method, set up default entry and exit blocks.
698 if (current_method_ == 0) {
699 DCHECK(entry_block_ == NULL);
700 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700701 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700702 // Use id 0 to represent a null block.
703 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
704 DCHECK_EQ(null_block->id, NullBasicBlockId);
705 null_block->hidden = true;
706 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700707 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700708 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700709 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700710 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800711 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
712 cu_->dex_file = &dex_file;
713 cu_->class_def_idx = class_def_idx;
714 cu_->method_idx = method_idx;
715 cu_->access_flags = access_flags;
716 cu_->invoke_type = invoke_type;
717 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800718 cu_->code_item = current_code_item_;
719 } else {
720 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
721 /*
722 * Will need to manage storage for ins & outs, push prevous state and update
723 * insert point.
724 */
725 }
726
727 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700728 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700729 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800730 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700731 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700732 // TODO: for inlining support, insert at the insert point rather than entry block.
733 entry_block_->fall_through = cur_block->id;
734 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800735
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000736 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800737 ProcessTryCatchBlocks();
738
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000739 uint64_t merged_df_flags = 0u;
740
buzbee311ca162013-02-28 15:56:43 -0800741 /* Parse all instructions and put them into containing basic blocks */
742 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700743 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800744 insn->offset = current_offset_;
745 insn->m_unit_index = current_method_;
746 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800747 Instruction::Code opcode = insn->dalvikInsn.opcode;
748 if (opcode_count_ != NULL) {
749 opcode_count_[static_cast<int>(opcode)]++;
750 }
751
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700752 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800753 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800754
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700755 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000756 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800757
758 if (df_flags & DF_HAS_DEFS) {
759 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
760 }
761
buzbee1da1e2f2013-11-15 13:37:01 -0800762 if (df_flags & DF_LVN) {
763 cur_block->use_lvn = true; // Run local value numbering on this basic block.
764 }
765
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700766 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700767 if (opcode == Instruction::NOP) {
768 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
769 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
770 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
771 uint16_t following_raw_instruction = code_ptr[1];
772 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
773 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
774 (following_raw_instruction == Instruction::kArrayDataSignature)) {
775 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
776 }
777 }
778 if (width == 1) {
779 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700780 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700781 } else {
buzbee0d829482013-10-11 15:24:55 -0700782 DCHECK(cur_block->fall_through == NullBasicBlockId);
783 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700784 // Unreachable instruction, mark for no continuation.
785 flags &= ~Instruction::kContinue;
786 }
787 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700788 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700789 }
790
buzbeeb48819d2013-09-14 16:15:25 -0700791 // Associate the starting dex_pc for this opcode with its containing basic block.
792 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
793
buzbee27247762013-07-28 12:03:58 -0700794 code_ptr += width;
795
buzbee311ca162013-02-28 15:56:43 -0800796 if (flags & Instruction::kBranch) {
797 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
798 width, flags, code_ptr, code_end);
799 } else if (flags & Instruction::kReturn) {
800 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700801 cur_block->fall_through = exit_block_->id;
802 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800803 /*
804 * Terminate the current block if there are instructions
805 * afterwards.
806 */
807 if (code_ptr < code_end) {
808 /*
809 * Create a fallthrough block for real instructions
810 * (incl. NOP).
811 */
buzbee27247762013-07-28 12:03:58 -0700812 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
813 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800814 }
815 } else if (flags & Instruction::kThrow) {
816 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
817 code_ptr, code_end);
818 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800819 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800820 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700821 if (verify_flags & Instruction::kVerifyVarArgRange ||
822 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800823 /*
824 * The Quick backend's runtime model includes a gap between a method's
825 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
826 * which spans the gap is somewhat complicated, and should not happen
827 * in normal usage of dx. Punt to the interpreter.
828 */
829 int first_reg_in_range = insn->dalvikInsn.vC;
830 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
831 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
832 punt_to_interpreter_ = true;
833 }
834 }
buzbee311ca162013-02-28 15:56:43 -0800835 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700836 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800837 false, /* immed_pred_block_p */ NULL);
838 if (next_block) {
839 /*
840 * The next instruction could be the target of a previously parsed
841 * forward branch so a block is already created. If the current
842 * instruction is not an unconditional branch, connect them through
843 * the fall-through link.
844 */
buzbee0d829482013-10-11 15:24:55 -0700845 DCHECK(cur_block->fall_through == NullBasicBlockId ||
846 GetBasicBlock(cur_block->fall_through) == next_block ||
847 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800848
buzbee0d829482013-10-11 15:24:55 -0700849 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
850 cur_block->fall_through = next_block->id;
851 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800852 }
853 cur_block = next_block;
854 }
855 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000856 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000857
buzbee311ca162013-02-28 15:56:43 -0800858 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
859 DumpCFG("/sdcard/1_post_parse_cfg/", true);
860 }
861
862 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700863 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800864 }
865}
866
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700867void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800868 DCHECK(opcode_count_ != NULL);
869 LOG(INFO) << "Opcode Count";
870 for (int i = 0; i < kNumPackedOpcodes; i++) {
871 if (opcode_count_[i] != 0) {
872 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
873 << " " << opcode_count_[i];
874 }
875 }
876}
877
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700878uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
879 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
880 return oat_data_flow_attributes_[opcode];
881}
882
883uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
884 DCHECK(mir != nullptr);
885 Instruction::Code opcode = mir->dalvikInsn.opcode;
886 return GetDataFlowAttributes(opcode);
887}
888
buzbee311ca162013-02-28 15:56:43 -0800889// TODO: use a configurable base prefix, and adjust callers to supply pass name.
890/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800891void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800892 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700893 static AtomicInteger cnt(0);
894
895 // Increment counter to get a unique file number.
896 cnt++;
897
buzbee311ca162013-02-28 15:56:43 -0800898 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
899 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700900 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800901 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700902 suffix == nullptr ? "" : suffix,
903 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800904 file = fopen(fname.c_str(), "w");
905 if (file == NULL) {
906 return;
907 }
908 fprintf(file, "digraph G {\n");
909
910 fprintf(file, " rankdir=TB\n");
911
912 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
913 int idx;
914
915 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700916 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700917 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700918 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800919 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700920 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800921 if (bb->block_type == kEntryBlock) {
922 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
923 } else if (bb->block_type == kExitBlock) {
924 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
925 } else if (bb->block_type == kDalvikByteCode) {
926 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
927 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700928 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800929 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
930 bb->first_mir_insn ? " | " : " ");
931 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
932 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400933 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
934 if (opcode == kMirOpConstVector) {
935 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
936 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
937 mir->dalvikInsn.vA,
938 mir->dalvikInsn.vB,
939 mir->dalvikInsn.arg[0],
940 mir->dalvikInsn.arg[1],
941 mir->dalvikInsn.arg[2],
942 mir->dalvikInsn.arg[3],
943 mir->next ? " | " : " ");
944 } else {
945 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
946 extended_mir_op_names_[opcode - kMirOpFirst],
947 mir->dalvikInsn.vA,
948 mir->dalvikInsn.vB,
949 mir->dalvikInsn.vC,
950 mir->next ? " | " : " ");
951 }
952 } else {
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700953 fprintf(file, " {%04x %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400954 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700955 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
956 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400957 extended_mir_op_names_[opcode - kMirOpFirst],
958 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
959 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700960 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700961 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400962 mir->next ? " | " : " ");
963 }
buzbee311ca162013-02-28 15:56:43 -0800964 }
965 fprintf(file, " }\"];\n\n");
966 } else if (bb->block_type == kExceptionHandling) {
967 char block_name[BLOCK_NAME_LEN];
968
969 GetBlockName(bb, block_name);
970 fprintf(file, " %s [shape=invhouse];\n", block_name);
971 }
972
973 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
974
buzbee0d829482013-10-11 15:24:55 -0700975 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800976 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700977 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800978 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
979 block_name1, block_name2);
980 }
buzbee0d829482013-10-11 15:24:55 -0700981 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800982 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700983 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800984 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
985 }
986
buzbee0d829482013-10-11 15:24:55 -0700987 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800988 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
989 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700990 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
991 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700992 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800993
994 int succ_id = 0;
995 while (true) {
996 if (successor_block_info == NULL) break;
997
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700998 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700999 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -08001000
1001 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
1002 succ_id++,
1003 successor_block_info->key,
1004 dest_block->start_offset,
1005 (next_successor_block_info != NULL) ? " | " : " ");
1006
1007 successor_block_info = next_successor_block_info;
1008 }
1009 fprintf(file, " }\"];\n\n");
1010
1011 GetBlockName(bb, block_name1);
1012 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1013 block_name1, bb->start_offset, bb->id);
1014
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001015 // Link the successor pseudo-block with all of its potential targets.
1016 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001017
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001018 succ_id = 0;
1019 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001020 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001021 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001022
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001023 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001024
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001025 GetBlockName(dest_block, block_name2);
1026 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1027 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001028 }
1029 }
1030 fprintf(file, "\n");
1031
1032 if (cu_->verbose) {
1033 /* Display the dominator tree */
1034 GetBlockName(bb, block_name1);
1035 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1036 block_name1, block_name1);
1037 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001038 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001039 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1040 }
1041 }
1042 }
1043 fprintf(file, "}\n");
1044 fclose(file);
1045}
1046
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001047/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001048void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001049 // Insert it after the last MIR.
1050 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001051}
1052
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001053void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1054 // Insert it after the last MIR.
1055 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1056}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001057
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001058void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1059 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1060 MIR* new_mir = *it;
1061
1062 // Add a copy of each MIR.
1063 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1064 }
buzbee1fd33462013-03-25 13:40:45 -07001065}
1066
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001067/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001068void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001069 InsertMIRListAfter(current_mir, new_mir, new_mir);
1070}
buzbee1fd33462013-03-25 13:40:45 -07001071
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001072void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1073 // If no MIR, we are done.
1074 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1075 return;
buzbee1fd33462013-03-25 13:40:45 -07001076 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001077
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001078 // If insert_after is null, assume BB is empty.
1079 if (insert_after == nullptr) {
1080 first_mir_insn = first_list_mir;
1081 last_mir_insn = last_list_mir;
1082 last_list_mir->next = nullptr;
1083 } else {
1084 MIR* after_list = insert_after->next;
1085 insert_after->next = first_list_mir;
1086 last_list_mir->next = after_list;
1087 if (after_list == nullptr) {
1088 last_mir_insn = last_list_mir;
1089 }
1090 }
1091
1092 // Set this BB to be the basic block of the MIRs.
1093 MIR* last = last_list_mir->next;
1094 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1095 mir->bb = id;
1096 }
1097}
1098
1099/* Insert an MIR instruction to the head of a basic block. */
1100void BasicBlock::PrependMIR(MIR* mir) {
1101 InsertMIRListBefore(first_mir_insn, mir, mir);
1102}
1103
1104void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1105 // Insert it before the first MIR.
1106 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1107}
1108
1109void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1110 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1111 MIR* mir = *it;
1112
1113 InsertMIRListBefore(first_mir_insn, mir, mir);
1114 }
1115}
1116
1117/* Insert a MIR instruction before the specified MIR. */
1118void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1119 // Insert as a single element list.
1120 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001121}
1122
1123MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1124 MIR* current = first_mir_insn;
1125
1126 while (current != nullptr) {
1127 MIR* next = current->next;
1128
1129 if (next == mir) {
1130 return current;
1131 }
1132
1133 current = next;
1134 }
1135
1136 return nullptr;
1137}
1138
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001139void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1140 // If no MIR, we are done.
1141 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1142 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001143 }
1144
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001145 // If insert_before is null, assume BB is empty.
1146 if (insert_before == nullptr) {
1147 first_mir_insn = first_list_mir;
1148 last_mir_insn = last_list_mir;
1149 last_list_mir->next = nullptr;
1150 } else {
1151 if (first_mir_insn == insert_before) {
1152 last_list_mir->next = first_mir_insn;
1153 first_mir_insn = first_list_mir;
1154 } else {
1155 // Find the preceding MIR.
1156 MIR* before_list = FindPreviousMIR(insert_before);
1157 DCHECK(before_list != nullptr);
1158 before_list->next = first_list_mir;
1159 last_list_mir->next = insert_before;
1160 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001161 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001162
1163 // Set this BB to be the basic block of the MIRs.
1164 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1165 mir->bb = id;
1166 }
1167}
1168
1169bool BasicBlock::RemoveMIR(MIR* mir) {
1170 // Remove as a single element list.
1171 return RemoveMIRList(mir, mir);
1172}
1173
1174bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1175 if (first_list_mir == nullptr) {
1176 return false;
1177 }
1178
1179 // Try to find the MIR.
1180 MIR* before_list = nullptr;
1181 MIR* after_list = nullptr;
1182
1183 // If we are removing from the beginning of the MIR list.
1184 if (first_mir_insn == first_list_mir) {
1185 before_list = nullptr;
1186 } else {
1187 before_list = FindPreviousMIR(first_list_mir);
1188 if (before_list == nullptr) {
1189 // We did not find the mir.
1190 return false;
1191 }
1192 }
1193
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001194 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001195 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1196 mir->bb = NullBasicBlockId;
1197 }
1198
1199 after_list = last_list_mir->next;
1200
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001201 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001202 if (before_list == nullptr) {
1203 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001204 } else {
1205 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001206 }
1207
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001208 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001209 if (after_list == nullptr) {
1210 last_mir_insn = before_list;
1211 }
1212
1213 return true;
buzbee1fd33462013-03-25 13:40:45 -07001214}
1215
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001216MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001217 MIR* next_mir = nullptr;
1218
1219 if (current != nullptr) {
1220 next_mir = current->next;
1221 }
1222
1223 if (next_mir == nullptr) {
1224 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001225 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1226 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001227 }
1228 }
1229
1230 return next_mir;
1231}
1232
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001233char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001234 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001235 std::string str;
1236 int flags = 0;
1237 int opcode = insn.opcode;
1238 char* ret;
1239 bool nop = false;
1240 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001241 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001242
1243 // Handle special cases.
1244 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1245 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1246 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001247 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001248 insn = mir->meta.throw_insn->dalvikInsn;
1249 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001250 opcode = insn.opcode;
1251 } else if (opcode == kMirOpNop) {
1252 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001253 // Recover original opcode.
1254 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1255 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001256 nop = true;
1257 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001258 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1259 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001260
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001261 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001262 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1263 } else {
1264 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001265 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001266 str.append(Instruction::Name(insn.opcode));
1267 }
1268
1269 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001270 BasicBlockId* incoming = mir->meta.phi_incoming;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001271 if (defs > 0 && uses > 0) {
1272 str.append(StringPrintf(" %s = (%s",
1273 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1274 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1275 str.append(StringPrintf(":%d", incoming[0]));
1276 int i;
1277 for (i = 1; i < uses; i++) {
1278 str.append(StringPrintf(", %s:%d",
1279 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1280 incoming[i]));
1281 }
1282 str.append(")");
1283 } else {
1284 str.append(StringPrintf(" v%d", mir->dalvikInsn.vA));
buzbee1fd33462013-03-25 13:40:45 -07001285 }
buzbee1fd33462013-03-25 13:40:45 -07001286 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001287 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001288 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1289 (dalvik_format == Instruction::k3rc));
1290 if (defs != 0) {
1291 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1292 if (uses != 0) {
1293 str.append(", ");
1294 }
1295 }
1296 for (int i = 0; i < uses; i++) {
1297 str.append(
1298 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1299 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1300 // For the listing, skip the high sreg.
1301 i++;
1302 }
1303 if (i != (uses -1)) {
1304 str.append(",");
1305 }
1306 }
1307 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001308 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001309 case Instruction::k21s:
1310 case Instruction::k31i:
1311 case Instruction::k21h:
1312 str.append(StringPrintf(", #%d", insn.vB));
1313 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001314 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001315 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001316 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001317 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001318 case Instruction::k31c:
1319 str.append(StringPrintf(", index #%d", insn.vB));
1320 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001321 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001322 str.append(StringPrintf(", index #%d", insn.vC));
1323 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001324 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001325 case Instruction::k22b:
1326 str.append(StringPrintf(", #%d", insn.vC));
1327 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001328 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001329 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001330 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001331 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001332 if ((flags & Instruction::kBranch) != 0) {
1333 // For branches, decode the instructions to print out the branch targets.
1334 int offset = 0;
1335 switch (dalvik_format) {
1336 case Instruction::k21t:
1337 offset = insn.vB;
1338 break;
1339 case Instruction::k22t:
1340 offset = insn.vC;
1341 break;
1342 case Instruction::k10t:
1343 case Instruction::k20t:
1344 case Instruction::k30t:
1345 offset = insn.vA;
1346 break;
1347 default:
1348 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1349 }
1350 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1351 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1352 }
buzbee1fd33462013-03-25 13:40:45 -07001353 }
1354 if (nop) {
1355 str.append("]--optimized away");
1356 }
1357 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001358 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001359 strncpy(ret, str.c_str(), length);
1360 return ret;
1361}
1362
1363/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001364void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001365 static const struct { const char before; const char after; } match[] = {
1366 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1367 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1368 };
buzbee1fd33462013-03-25 13:40:45 -07001369 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1370 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1371 }
1372}
1373
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001374std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001375 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1376 // the arena. We should be smarter and just place straight into the arena, or compute the
1377 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001378 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1379}
1380
1381// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001382std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001383 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001384 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001385 return GetSSAName(ssa_reg);
1386 }
1387 if (IsConst(reg_location_[ssa_reg])) {
1388 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001389 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001390 ConstantValueWide(reg_location_[ssa_reg]));
1391 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001392 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001393 ConstantValue(reg_location_[ssa_reg]));
1394 }
1395 } else {
1396 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1397 }
1398}
1399
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001400void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001401 switch (bb->block_type) {
1402 case kEntryBlock:
1403 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1404 break;
1405 case kExitBlock:
1406 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1407 break;
1408 case kDalvikByteCode:
1409 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1410 break;
1411 case kExceptionHandling:
1412 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1413 bb->id);
1414 break;
1415 default:
1416 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1417 break;
1418 }
1419}
1420
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001421const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001422 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001423 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1424 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1425}
1426
1427/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001428void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001429 BasicBlock* bb;
1430 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001431 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001432 "Entry Block",
1433 "Code Block",
1434 "Exit Block",
1435 "Exception Handling",
1436 "Catch Block"
1437 };
1438
1439 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001440 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001441 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001442 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001443
1444 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001445 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001446 if (bb == NULL) break;
1447 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1448 bb->id,
1449 block_type_names[bb->block_type],
1450 bb->start_offset,
1451 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1452 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001453 if (bb->taken != NullBasicBlockId) {
1454 LOG(INFO) << " Taken branch: block " << bb->taken
1455 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001456 }
buzbee0d829482013-10-11 15:24:55 -07001457 if (bb->fall_through != NullBasicBlockId) {
1458 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1459 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001460 }
1461 }
1462}
1463
1464/*
1465 * Build an array of location records for the incoming arguments.
1466 * Note: one location record per word of arguments, with dummy
1467 * high-word loc for wide arguments. Also pull up any following
1468 * MOVE_RESULT and incorporate it into the invoke.
1469 */
1470CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001471 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001472 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001473 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001474 MIR* move_result_mir = FindMoveResult(bb, mir);
1475 if (move_result_mir == NULL) {
1476 info->result.location = kLocInvalid;
1477 } else {
1478 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001479 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1480 }
1481 info->num_arg_words = mir->ssa_rep->num_uses;
1482 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001483 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001484 for (int i = 0; i < info->num_arg_words; i++) {
1485 info->args[i] = GetRawSrc(mir, i);
1486 }
1487 info->opt_flags = mir->optimization_flags;
1488 info->type = type;
1489 info->is_range = is_range;
1490 info->index = mir->dalvikInsn.vB;
1491 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001492 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001493 return info;
1494}
1495
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001496// Allocate a new MIR.
1497MIR* MIRGraph::NewMIR() {
1498 MIR* mir = new (arena_) MIR();
1499 return mir;
1500}
1501
buzbee862a7602013-04-05 10:58:54 -07001502// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001503BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001504 BasicBlock* bb = new (arena_) BasicBlock();
1505
buzbee862a7602013-04-05 10:58:54 -07001506 bb->block_type = block_type;
1507 bb->id = block_id;
1508 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001509 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001510 (block_type == kExitBlock) ? 2048 : 2,
1511 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001512 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001513 block_id_map_.Put(block_id, block_id);
1514 return bb;
1515}
buzbee1fd33462013-03-25 13:40:45 -07001516
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001517void MIRGraph::InitializeConstantPropagation() {
1518 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001519 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001520}
1521
1522void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001523 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001524 int num_ssa_regs = GetNumSSARegs();
1525 use_counts_.Resize(num_ssa_regs + 32);
1526 raw_use_counts_.Resize(num_ssa_regs + 32);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001527 // Resize does not actually reset the number of used, so reset before initialization.
1528 use_counts_.Reset();
1529 raw_use_counts_.Reset();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001530 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001531 for (int i = 0; i < num_ssa_regs; i++) {
1532 use_counts_.Insert(0);
1533 raw_use_counts_.Insert(0);
1534 }
1535}
1536
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001537void MIRGraph::SSATransformationStart() {
1538 DCHECK(temp_scoped_alloc_.get() == nullptr);
1539 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001540 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001541 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1542 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1543
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001544 // Update the maximum number of reachable blocks.
1545 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001546}
1547
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001548void MIRGraph::SSATransformationEnd() {
1549 // Verify the dataflow information after the pass.
1550 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1551 VerifyDataflow();
1552 }
1553
1554 temp_bit_vector_size_ = 0u;
1555 temp_bit_vector_ = nullptr;
1556 DCHECK(temp_scoped_alloc_.get() != nullptr);
1557 temp_scoped_alloc_.reset();
1558}
1559
Vladimir Marko55fff042014-07-10 12:42:52 +01001560static BasicBlock* SelectTopologicalSortOrderFallBack(
1561 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1562 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1563 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1564 // No true loop head has been found but there may be true loop heads after the mess we need
1565 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1566 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1567 BasicBlock* fall_back = nullptr;
1568 size_t fall_back_num_reachable = 0u;
1569 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1570 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1571 AllNodesIterator iter(mir_graph);
1572 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1573 if (candidate->hidden || // Hidden, or
1574 candidate->visited || // already processed, or
1575 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1576 (current_loop != nullptr && // outside current loop.
1577 !current_loop->IsBitSet(candidate->id))) {
1578 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001579 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001580 DCHECK(tmp_stack->empty());
1581 tmp_stack->push_back(candidate->id);
1582 candidate_reachable.ClearAllBits();
1583 size_t num_reachable = 0u;
1584 while (!tmp_stack->empty()) {
1585 BasicBlockId current_id = tmp_stack->back();
1586 tmp_stack->pop_back();
1587 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1588 DCHECK(current_bb != nullptr);
1589 ChildBlockIterator child_iter(current_bb, mir_graph);
1590 BasicBlock* child_bb = child_iter.Next();
1591 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1592 DCHECK(!child_bb->hidden);
1593 if (child_bb->visited || // Already processed, or
1594 (current_loop != nullptr && // outside current loop.
1595 !current_loop->IsBitSet(child_bb->id))) {
1596 continue;
1597 }
1598 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1599 candidate_reachable.SetBit(child_bb->id);
1600 tmp_stack->push_back(child_bb->id);
1601 num_reachable += 1u;
1602 }
1603 }
1604 }
1605 if (fall_back_num_reachable < num_reachable) {
1606 fall_back_num_reachable = num_reachable;
1607 fall_back = candidate;
1608 }
1609 }
1610 return fall_back;
1611}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001612
Vladimir Marko55fff042014-07-10 12:42:52 +01001613// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1614static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1615 ArenaBitVector* reachable,
1616 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1617 // NOTE: Loop heads indicated by the "visited" flag.
1618 DCHECK(tmp_stack->empty());
1619 reachable->ClearAllBits();
1620 tmp_stack->push_back(bb_id);
1621 while (!tmp_stack->empty()) {
1622 BasicBlockId current_id = tmp_stack->back();
1623 tmp_stack->pop_back();
1624 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1625 DCHECK(current_bb != nullptr);
1626 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1627 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1628 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1629 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1630 reachable->SetBit(pred_bb->id);
1631 tmp_stack->push_back(pred_bb->id);
1632 }
1633 }
1634 }
1635}
1636
1637void MIRGraph::ComputeTopologicalSortOrder() {
1638 ScopedArenaAllocator allocator(&cu_->arena_stack);
1639 unsigned int num_blocks = GetNumBlocks();
1640
1641 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1642 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1643 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1644 size_t max_nested_loops = 0u;
1645 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1646 loop_exit_blocks.ClearAllBits();
1647
1648 // Count the number of blocks to process and add the entry block(s).
1649 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1650 unsigned int num_blocks_to_process = 0u;
1651 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001652 if (bb->hidden == true) {
1653 continue;
1654 }
1655
Vladimir Marko55fff042014-07-10 12:42:52 +01001656 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001657
Vladimir Marko55fff042014-07-10 12:42:52 +01001658 if (bb->predecessors->Size() == 0u) {
1659 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001660 q.push(bb);
1661 }
1662 }
1663
Vladimir Marko55fff042014-07-10 12:42:52 +01001664 // Create the topological order if need be.
1665 if (topological_order_ == nullptr) {
1666 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1667 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1668 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1669 }
1670 topological_order_->Reset();
1671 topological_order_loop_ends_->Reset();
1672 topological_order_indexes_->Reset();
1673 topological_order_loop_ends_->Resize(num_blocks);
1674 topological_order_indexes_->Resize(num_blocks);
1675 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1676 topological_order_loop_ends_->Insert(0u);
1677 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1678 }
1679
1680 // Mark all blocks as unvisited.
1681 ClearAllVisitedFlags();
1682
1683 // For loop heads, keep track from which blocks they are reachable not going through other
1684 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1685 // in this set go into the loop body, the other children are jumping over the loop.
1686 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1687 loop_head_reachable_from.resize(num_blocks, nullptr);
1688 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1689 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1690
1691 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001692 BasicBlock* bb = nullptr;
1693 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001694 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001695 // Get top.
1696 bb = q.front();
1697 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001698 if (bb->visited) {
1699 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1700 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1701 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1702 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1703 DCHECK_EQ(loop_head_stack.back(), bb->id);
1704 loop_head_stack.pop_back();
1705 ArenaBitVector* reachable =
1706 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1707 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1708 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1709 q.push(GetBasicBlock(candidate_id));
1710 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1711 // so clearing the bit has no effect on the iterator.
1712 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001713 }
1714 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001715 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001716 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001717 } else {
1718 // Find the new loop head.
1719 AllNodesIterator iter(this);
1720 while (true) {
1721 BasicBlock* candidate = iter.Next();
1722 if (candidate == nullptr) {
1723 // We did not find a true loop head, fall back to a reachable block in any loop.
1724 ArenaBitVector* current_loop =
1725 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1726 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1727 &allocator, &tmp_stack);
1728 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1729 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1730 LOG(INFO) << "Topological sort order: Using fall-back in "
1731 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1732 << " @0x" << std::hex << bb->start_offset
1733 << ", num_blocks = " << std::dec << num_blocks;
1734 }
1735 break;
1736 }
1737 if (candidate->hidden || // Hidden, or
1738 candidate->visited || // already processed, or
1739 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1740 (!loop_head_stack.empty() && // outside current loop.
1741 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1742 continue;
1743 }
1744
1745 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1746 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1747 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1748 if (pred_bb != candidate && !pred_bb->visited &&
1749 !pred_bb->dominators->IsBitSet(candidate->id)) {
1750 break; // Keep non-null pred_bb to indicate failure.
1751 }
1752 }
1753 if (pred_bb == nullptr) {
1754 bb = candidate;
1755 break;
1756 }
1757 }
1758 // Compute blocks from which the loop head is reachable and process those blocks first.
1759 ArenaBitVector* reachable =
1760 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1761 loop_head_reachable_from[bb->id] = reachable;
1762 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1763 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1764 loop_head_stack.push_back(bb->id);
1765 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001766 }
1767
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001768 DCHECK_EQ(bb->hidden, false);
1769 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001770 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001771
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001772 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001773 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1774 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001775 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001776
Vladimir Marko55fff042014-07-10 12:42:52 +01001777 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001778 ChildBlockIterator succIter(bb, this);
1779 BasicBlock* successor = succIter.Next();
1780 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001781 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001782 continue;
1783 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001784
Vladimir Marko55fff042014-07-10 12:42:52 +01001785 // One more predecessor was visited.
1786 visited_cnt_values[successor->id] += 1u;
1787 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1788 if (loop_head_stack.empty() ||
1789 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1790 q.push(successor);
1791 } else {
1792 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1793 loop_exit_blocks.SetBit(successor->id);
1794 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001795 }
1796 }
1797 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001798
1799 // Prepare the loop head stack for iteration.
1800 topological_order_loop_head_stack_ =
1801 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001802}
1803
1804bool BasicBlock::IsExceptionBlock() const {
1805 if (block_type == kExceptionHandling) {
1806 return true;
1807 }
1808 return false;
1809}
1810
Wei Jin04f4d8a2014-05-29 18:04:29 -07001811bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1812 BasicBlock* target = GetBasicBlock(target_id);
1813
1814 if (source == nullptr || target == nullptr)
1815 return false;
1816
1817 int idx;
1818 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1819 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1820 if (bb == source)
1821 return true; // The block has been inserted by a suspend check before.
1822 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1823 return true;
1824 }
1825
1826 return false;
1827}
1828
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001829ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1830 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1831 visited_taken_(false), have_successors_(false) {
1832 // Check if we actually do have successors.
1833 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1834 have_successors_ = true;
1835 successor_iter_.Reset(basic_block_->successor_blocks);
1836 }
1837}
1838
1839BasicBlock* ChildBlockIterator::Next() {
1840 // We check if we have a basic block. If we don't we cannot get next child.
1841 if (basic_block_ == nullptr) {
1842 return nullptr;
1843 }
1844
1845 // If we haven't visited fallthrough, return that.
1846 if (visited_fallthrough_ == false) {
1847 visited_fallthrough_ = true;
1848
1849 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1850 if (result != nullptr) {
1851 return result;
1852 }
1853 }
1854
1855 // If we haven't visited taken, return that.
1856 if (visited_taken_ == false) {
1857 visited_taken_ = true;
1858
1859 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1860 if (result != nullptr) {
1861 return result;
1862 }
1863 }
1864
1865 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1866 if (have_successors_ == true) {
1867 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07001868 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1869 successor_block_info != nullptr;
1870 successor_block_info = successor_iter_.Next()) {
1871 // If block was replaced by zero block, take next one.
1872 if (successor_block_info->block != NullBasicBlockId) {
1873 return mir_graph_->GetBasicBlock(successor_block_info->block);
1874 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001875 }
1876 }
1877
1878 // We do not have anything.
1879 return nullptr;
1880}
1881
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001882BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1883 MIRGraph* mir_graph = c_unit->mir_graph.get();
1884 return Copy(mir_graph);
1885}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001886
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001887BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1888 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001889
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001890 // We don't do a memcpy style copy here because it would lead to a lot of things
1891 // to clean up. Let us do it by hand instead.
1892 // Copy in taken and fallthrough.
1893 result_bb->fall_through = fall_through;
1894 result_bb->taken = taken;
1895
1896 // Copy successor links if needed.
1897 ArenaAllocator* arena = mir_graph->GetArena();
1898
1899 result_bb->successor_block_list_type = successor_block_list_type;
1900 if (result_bb->successor_block_list_type != kNotUsed) {
1901 size_t size = successor_blocks->Size();
1902 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1903 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1904 while (true) {
1905 SuccessorBlockInfo* sbi_old = iterator.Next();
1906 if (sbi_old == nullptr) {
1907 break;
1908 }
1909 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1910 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1911 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001912 }
1913 }
1914
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001915 // Copy offset, method.
1916 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001917
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001918 // Now copy instructions.
1919 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1920 // Get a copy first.
1921 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001922
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001923 // Append it.
1924 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001925 }
1926
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001927 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001928}
1929
1930MIR* MIR::Copy(MIRGraph* mir_graph) {
1931 MIR* res = mir_graph->NewMIR();
1932 *res = *this;
1933
1934 // Remove links
1935 res->next = nullptr;
1936 res->bb = NullBasicBlockId;
1937 res->ssa_rep = nullptr;
1938
1939 return res;
1940}
1941
1942MIR* MIR::Copy(CompilationUnit* c_unit) {
1943 return Copy(c_unit->mir_graph.get());
1944}
1945
1946uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1947 // Default result.
1948 int res = 0;
1949
1950 // We are basically setting the iputs to their igets counterparts.
1951 switch (opcode) {
1952 case Instruction::IPUT:
1953 case Instruction::IPUT_OBJECT:
1954 case Instruction::IPUT_BOOLEAN:
1955 case Instruction::IPUT_BYTE:
1956 case Instruction::IPUT_CHAR:
1957 case Instruction::IPUT_SHORT:
1958 case Instruction::IPUT_QUICK:
1959 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07001960 case Instruction::IPUT_BOOLEAN_QUICK:
1961 case Instruction::IPUT_BYTE_QUICK:
1962 case Instruction::IPUT_CHAR_QUICK:
1963 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001964 case Instruction::APUT:
1965 case Instruction::APUT_OBJECT:
1966 case Instruction::APUT_BOOLEAN:
1967 case Instruction::APUT_BYTE:
1968 case Instruction::APUT_CHAR:
1969 case Instruction::APUT_SHORT:
1970 case Instruction::SPUT:
1971 case Instruction::SPUT_OBJECT:
1972 case Instruction::SPUT_BOOLEAN:
1973 case Instruction::SPUT_BYTE:
1974 case Instruction::SPUT_CHAR:
1975 case Instruction::SPUT_SHORT:
1976 // Skip the VR containing what to store.
1977 res = 1;
1978 break;
1979 case Instruction::IPUT_WIDE:
1980 case Instruction::IPUT_WIDE_QUICK:
1981 case Instruction::APUT_WIDE:
1982 case Instruction::SPUT_WIDE:
1983 // Skip the two VRs containing what to store.
1984 res = 2;
1985 break;
1986 default:
1987 // Do nothing in the general case.
1988 break;
1989 }
1990
1991 return res;
1992}
1993
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001994/**
1995 * @brief Given a decoded instruction, it checks whether the instruction
1996 * sets a constant and if it does, more information is provided about the
1997 * constant being set.
1998 * @param ptr_value pointer to a 64-bit holder for the constant.
1999 * @param wide Updated by function whether a wide constant is being set by bytecode.
2000 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2001 */
2002bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2003 bool sets_const = true;
2004 int64_t value = vB;
2005
2006 DCHECK(ptr_value != nullptr);
2007 DCHECK(wide != nullptr);
2008
2009 switch (opcode) {
2010 case Instruction::CONST_4:
2011 case Instruction::CONST_16:
2012 case Instruction::CONST:
2013 *wide = false;
2014 value <<= 32; // In order to get the sign extend.
2015 value >>= 32;
2016 break;
2017 case Instruction::CONST_HIGH16:
2018 *wide = false;
2019 value <<= 48; // In order to get the sign extend.
2020 value >>= 32;
2021 break;
2022 case Instruction::CONST_WIDE_16:
2023 case Instruction::CONST_WIDE_32:
2024 *wide = true;
2025 value <<= 32; // In order to get the sign extend.
2026 value >>= 32;
2027 break;
2028 case Instruction::CONST_WIDE:
2029 *wide = true;
2030 value = vB_wide;
2031 break;
2032 case Instruction::CONST_WIDE_HIGH16:
2033 *wide = true;
2034 value <<= 48; // In order to get the sign extend.
2035 break;
2036 default:
2037 sets_const = false;
2038 break;
2039 }
2040
2041 if (sets_const) {
2042 *ptr_value = value;
2043 }
2044
2045 return sets_const;
2046}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002047
2048void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2049 // Reset flags for all MIRs in bb.
2050 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2051 mir->optimization_flags &= (~reset_flags);
2052 }
2053}
2054
2055void BasicBlock::Hide(CompilationUnit* c_unit) {
2056 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2057 block_type = kDalvikByteCode;
2058
2059 // Mark it as hidden.
2060 hidden = true;
2061
2062 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2063 // are updated to know that they no longer have a parent.
2064 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2065 mir->bb = NullBasicBlockId;
2066 }
2067 first_mir_insn = nullptr;
2068 last_mir_insn = nullptr;
2069
2070 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2071
2072 MIRGraph* mir_graph = c_unit->mir_graph.get();
2073 while (true) {
2074 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2075 if (pred_bb == nullptr) {
2076 break;
2077 }
2078
2079 // Sadly we have to go through the children by hand here.
2080 pred_bb->ReplaceChild(id, NullBasicBlockId);
2081 }
2082
2083 // Iterate through children of bb we are hiding.
2084 ChildBlockIterator successorChildIter(this, mir_graph);
2085
2086 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2087 // Replace child with null child.
2088 childPtr->predecessors->Delete(id);
2089 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002090
2091 // Remove link to children.
2092 taken = NullBasicBlockId;
2093 fall_through = NullBasicBlockId;
2094 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002095}
2096
2097bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2098 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2099 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2100 // then it is not live out of this BB.
2101 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2102
2103 int last_ssa_reg = -1;
2104
2105 // Walk through the MIRs backwards.
2106 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2107 // Get ssa rep.
2108 SSARepresentation *ssa_rep = mir->ssa_rep;
2109
2110 // Go through the defines for this MIR.
2111 for (int i = 0; i < ssa_rep->num_defs; i++) {
2112 DCHECK(ssa_rep->defs != nullptr);
2113
2114 // Get the ssa reg.
2115 int def_ssa_reg = ssa_rep->defs[i];
2116
2117 // Get dalvik reg.
2118 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2119
2120 // Compare dalvik regs.
2121 if (dalvik_reg == def_dalvik_reg) {
2122 // We found a def of the register that we are being asked about.
2123 // Remember it.
2124 last_ssa_reg = def_ssa_reg;
2125 }
2126 }
2127 }
2128
2129 if (last_ssa_reg == -1) {
2130 // If we get to this point we couldn't find a define of register user asked about.
2131 // Let's assume the user knows what he's doing so we can be safe and say that if we
2132 // couldn't find a def, it is live out.
2133 return true;
2134 }
2135
2136 // If it is not -1, we found a match, is it ssa_reg?
2137 return (ssa_reg == last_ssa_reg);
2138}
2139
2140bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2141 // We need to check taken, fall_through, and successor_blocks to replace.
2142 bool found = false;
2143 if (taken == old_bb) {
2144 taken = new_bb;
2145 found = true;
2146 }
2147
2148 if (fall_through == old_bb) {
2149 fall_through = new_bb;
2150 found = true;
2151 }
2152
2153 if (successor_block_list_type != kNotUsed) {
2154 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2155 while (true) {
2156 SuccessorBlockInfo* successor_block_info = iterator.Next();
2157 if (successor_block_info == nullptr) {
2158 break;
2159 }
2160 if (successor_block_info->block == old_bb) {
2161 successor_block_info->block = new_bb;
2162 found = true;
2163 }
2164 }
2165 }
2166
2167 return found;
2168}
2169
2170void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2171 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2172 bool found = false;
2173
2174 while (true) {
2175 BasicBlockId pred_bb_id = iterator.Next();
2176
2177 if (pred_bb_id == NullBasicBlockId) {
2178 break;
2179 }
2180
2181 if (pred_bb_id == old_parent) {
2182 size_t idx = iterator.GetIndex() - 1;
2183 predecessors->Put(idx, new_parent);
2184 found = true;
2185 break;
2186 }
2187 }
2188
2189 // If not found, add it.
2190 if (found == false) {
2191 predecessors->Insert(new_parent);
2192 }
2193}
2194
2195// Create a new basic block with block_id as num_blocks_ that is
2196// post-incremented.
2197BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2198 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2199 block_list_.Insert(res);
2200 return res;
2201}
2202
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002203void MIRGraph::CalculateBasicBlockInformation() {
2204 PassDriverMEPostOpt driver(cu_);
2205 driver.Launch();
2206}
2207
2208void MIRGraph::InitializeBasicBlockData() {
2209 num_blocks_ = block_list_.Size();
2210}
2211
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002212int MIR::DecodedInstruction::FlagsOf() const {
2213 // Calculate new index.
2214 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2215
2216 // Check if it is an extended or not.
2217 if (idx < 0) {
2218 return Instruction::FlagsOf(opcode);
2219 }
2220
2221 // For extended, we use a switch.
2222 switch (static_cast<int>(opcode)) {
2223 case kMirOpPhi:
2224 return Instruction::kContinue;
2225 case kMirOpCopy:
2226 return Instruction::kContinue;
2227 case kMirOpFusedCmplFloat:
2228 return Instruction::kContinue | Instruction::kBranch;
2229 case kMirOpFusedCmpgFloat:
2230 return Instruction::kContinue | Instruction::kBranch;
2231 case kMirOpFusedCmplDouble:
2232 return Instruction::kContinue | Instruction::kBranch;
2233 case kMirOpFusedCmpgDouble:
2234 return Instruction::kContinue | Instruction::kBranch;
2235 case kMirOpFusedCmpLong:
2236 return Instruction::kContinue | Instruction::kBranch;
2237 case kMirOpNop:
2238 return Instruction::kContinue;
2239 case kMirOpNullCheck:
2240 return Instruction::kContinue | Instruction::kThrow;
2241 case kMirOpRangeCheck:
2242 return Instruction::kContinue | Instruction::kThrow;
2243 case kMirOpDivZeroCheck:
2244 return Instruction::kContinue | Instruction::kThrow;
2245 case kMirOpCheck:
2246 return 0;
2247 case kMirOpCheckPart2:
2248 return 0;
2249 case kMirOpSelect:
2250 return Instruction::kContinue;
2251 case kMirOpConstVector:
2252 return Instruction::kContinue;
2253 case kMirOpMoveVector:
2254 return Instruction::kContinue;
2255 case kMirOpPackedMultiply:
2256 return Instruction::kContinue;
2257 case kMirOpPackedAddition:
2258 return Instruction::kContinue;
2259 case kMirOpPackedSubtract:
2260 return Instruction::kContinue;
2261 case kMirOpPackedShiftLeft:
2262 return Instruction::kContinue;
2263 case kMirOpPackedSignedShiftRight:
2264 return Instruction::kContinue;
2265 case kMirOpPackedUnsignedShiftRight:
2266 return Instruction::kContinue;
2267 case kMirOpPackedAnd:
2268 return Instruction::kContinue;
2269 case kMirOpPackedOr:
2270 return Instruction::kContinue;
2271 case kMirOpPackedXor:
2272 return Instruction::kContinue;
2273 case kMirOpPackedAddReduce:
2274 return Instruction::kContinue;
2275 case kMirOpPackedReduce:
2276 return Instruction::kContinue;
2277 case kMirOpPackedSet:
2278 return Instruction::kContinue;
2279 case kMirOpReserveVectorRegisters:
2280 return Instruction::kContinue;
2281 case kMirOpReturnVectorRegisters:
2282 return Instruction::kContinue;
2283 default:
2284 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2285 return 0;
2286 }
2287}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002288} // namespace art