blob: e0f471ebeb28670d735a3e4a1528de7f1f24437c [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",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070071 "PackedArrayGet",
72 "PackedArrayPut",
buzbee1fd33462013-03-25 13:40:45 -070073};
74
buzbee862a7602013-04-05 10:58:54 -070075MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070076 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010077 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070078 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010079 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
80 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
buzbee311ca162013-02-28 15:56:43 -080081 vreg_to_ssa_map_(NULL),
82 ssa_last_defs_(NULL),
83 is_constant_v_(NULL),
84 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010085 use_counts_(arena->Adapter()),
86 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080087 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070088 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010089 dfs_orders_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010090 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
91 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
92 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
93 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
94 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
95 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
96 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +010097 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -080098 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000099 temp_scoped_alloc_(),
100 temp_insn_data_(nullptr),
101 temp_bit_vector_size_(0u),
102 temp_bit_vector_(nullptr),
Vladimir Marko5229cf12014-10-09 14:57:59 +0100103 temp_bit_matrix_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100104 temp_gvn_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100105 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800106 try_block_addr_(NULL),
107 entry_block_(NULL),
108 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800109 num_blocks_(0),
110 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100111 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100112 m_units_(arena->Adapter()),
113 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800114 current_method_(kInvalidEntry),
115 current_offset_(kInvalidEntry),
116 def_count_(0),
117 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700118 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100119 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700120 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700121 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
122 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700123 arena_(arena),
124 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800125 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800126 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700127 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
128 requested_backend_temp_(false),
129 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000130 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000131 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100132 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
133 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
134 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
135 gen_suspend_test_list_(arena->Adapter()) {
136 use_counts_.reserve(256);
137 raw_use_counts_.reserve(256);
138 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700139 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700140
141
142 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
143 // X86 requires a temp to keep track of the method address.
144 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
145 // this needs to be updated to reserve 0 temps for BE.
146 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
147 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
148 } else {
149 // Other architectures do not have a known lower bound for non-special temps.
150 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
151 max_available_non_special_compiler_temps_ = 0;
152 reserved_temps_for_backend_ = 0;
153 }
buzbee311ca162013-02-28 15:56:43 -0800154}
155
Ian Rogers6282dc12013-04-18 15:54:02 -0700156MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100157 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700158 STLDeleteElements(&m_units_);
159}
160
buzbee311ca162013-02-28 15:56:43 -0800161/*
162 * Parse an instruction, return the length of the instruction
163 */
Ian Rogers29a26482014-05-02 15:27:29 -0700164int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
165 const Instruction* inst = Instruction::At(code_ptr);
166 decoded_instruction->opcode = inst->Opcode();
167 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
168 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
169 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
170 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
171 if (inst->HasVarArgs()) {
172 inst->GetVarArgs(decoded_instruction->arg);
173 }
174 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800175}
176
177
178/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700179BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700180 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700181 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800182 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400183 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800184 while (insn) {
185 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700186 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800187 insn = insn->next;
188 }
189 if (insn == NULL) {
190 LOG(FATAL) << "Break split failed";
191 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400192 // Now insn is at the instruction where we want to split, namely
193 // insn will be the first instruction of the "bottom" block.
194 // Similarly, prev will be the last instruction of the "top" block
195
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100196 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800197
198 bottom_block->start_offset = code_offset;
199 bottom_block->first_mir_insn = insn;
200 bottom_block->last_mir_insn = orig_block->last_mir_insn;
201
Junmo Park90223cc2014-08-04 18:51:21 +0900202 /* If this block was terminated by a return, conditional branch or throw,
203 * the flag needs to go with the bottom block
204 */
buzbee311ca162013-02-28 15:56:43 -0800205 bottom_block->terminated_by_return = orig_block->terminated_by_return;
206 orig_block->terminated_by_return = false;
207
Junmo Park90223cc2014-08-04 18:51:21 +0900208 bottom_block->conditional_branch = orig_block->conditional_branch;
209 orig_block->conditional_branch = false;
210
211 bottom_block->explicit_throw = orig_block->explicit_throw;
212 orig_block->explicit_throw = false;
213
buzbee311ca162013-02-28 15:56:43 -0800214 /* Handle the taken path */
215 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700216 if (bottom_block->taken != NullBasicBlockId) {
217 orig_block->taken = NullBasicBlockId;
218 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100219 bb_taken->ErasePredecessor(orig_block->id);
220 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800221 }
222
223 /* Handle the fallthrough path */
224 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700225 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100226 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700227 if (bottom_block->fall_through != NullBasicBlockId) {
228 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100229 bb_fall_through->ErasePredecessor(orig_block->id);
230 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800231 }
232
233 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700234 if (orig_block->successor_block_list_type != kNotUsed) {
235 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100236 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700237 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
239 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700240 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700241 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 bb->ErasePredecessor(orig_block->id);
243 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700244 }
buzbee311ca162013-02-28 15:56:43 -0800245 }
246 }
247
buzbee0d829482013-10-11 15:24:55 -0700248 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700249 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800250
buzbee311ca162013-02-28 15:56:43 -0800251 /*
252 * Update the immediate predecessor block pointer so that outgoing edges
253 * can be applied to the proper block.
254 */
255 if (immed_pred_block_p) {
256 DCHECK_EQ(*immed_pred_block_p, orig_block);
257 *immed_pred_block_p = bottom_block;
258 }
buzbeeb48819d2013-09-14 16:15:25 -0700259
260 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000261 DCHECK(insn != nullptr);
262 DCHECK(insn != orig_block->first_mir_insn);
263 DCHECK(insn == bottom_block->first_mir_insn);
264 DCHECK_EQ(insn->offset, bottom_block->start_offset);
265 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700266 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100267 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400268 // Scan the "bottom" instructions, remapping them to the
269 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000270 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400271 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100272 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000273 while (p != bottom_block->last_mir_insn) {
274 p = p->next;
275 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700276 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700277 int opcode = p->dalvikInsn.opcode;
278 /*
279 * Some messiness here to ensure that we only enter real opcodes and only the
280 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000281 * CHECK and work portions. Since the 2nd half of a split operation is always
282 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700283 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700284 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400285 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
286 // At first glance the instructions should all be mapped to orig_block.
287 // However, multiple instructions may correspond to the same dex, hence an earlier
288 // instruction may have already moved the mapping for dex to bottom_block.
289 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100290 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700291 }
buzbeeb48819d2013-09-14 16:15:25 -0700292 }
293
buzbee311ca162013-02-28 15:56:43 -0800294 return bottom_block;
295}
296
297/*
298 * Given a code offset, find out the block that starts with it. If the offset
299 * is in the middle of an existing block, split it into two. If immed_pred_block_p
300 * is not non-null and is the block being split, update *immed_pred_block_p to
301 * point to the bottom block so that outgoing edges can be set up properly
302 * (by the caller)
303 * Utilizes a map for fast lookup of the typical cases.
304 */
buzbee0d829482013-10-11 15:24:55 -0700305BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700306 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700307 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800308 return NULL;
309 }
buzbeeb48819d2013-09-14 16:15:25 -0700310
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100311 int block_id = dex_pc_to_block_map_[code_offset];
312 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700313
314 if ((bb != NULL) && (bb->start_offset == code_offset)) {
315 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700316 return bb;
317 }
buzbee311ca162013-02-28 15:56:43 -0800318
buzbeeb48819d2013-09-14 16:15:25 -0700319 // No direct hit.
320 if (!create) {
321 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800322 }
323
buzbeeb48819d2013-09-14 16:15:25 -0700324 if (bb != NULL) {
325 // The target exists somewhere in an existing block.
326 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
327 }
328
329 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100330 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800331 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100332 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800333 return bb;
334}
335
buzbeeb48819d2013-09-14 16:15:25 -0700336
buzbee311ca162013-02-28 15:56:43 -0800337/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700338void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800339 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700340 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800341
342 if (tries_size == 0) {
343 return;
344 }
345
346 for (int i = 0; i < tries_size; i++) {
347 const DexFile::TryItem* pTry =
348 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700349 DexOffset start_offset = pTry->start_addr_;
350 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800351 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700352 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800353 }
354 }
355
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700356 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700357 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800358 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
359 for (uint32_t idx = 0; idx < handlers_size; idx++) {
360 CatchHandlerIterator iterator(handlers_ptr);
361 for (; iterator.HasNext(); iterator.Next()) {
362 uint32_t address = iterator.GetHandlerAddress();
363 FindBlock(address, false /* split */, true /*create*/,
364 /* immed_pred_block_p */ NULL);
365 }
366 handlers_ptr = iterator.EndDataPointer();
367 }
368}
369
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100370bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
371 NarrowDexOffset catch_offset) {
372 // Catches for monitor-exit during stack unwinding have the pattern
373 // move-exception (move)* (goto)? monitor-exit throw
374 // In the currently generated dex bytecode we see these catching a bytecode range including
375 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
376 // it's the case for a given monitor-exit and catch block so that we can ignore it.
377 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
378 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
379 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700380 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100381 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
382 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700383 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100384 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
385 if (check_insn->VRegA_11x() == monitor_reg) {
386 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
387 return false;
388 }
389 check_insn = check_insn->Next();
390 while (true) {
391 int dest = -1;
392 bool wide = false;
393 switch (check_insn->Opcode()) {
394 case Instruction::MOVE_WIDE:
395 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700396 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100397 case Instruction::MOVE_OBJECT:
398 case Instruction::MOVE:
399 dest = check_insn->VRegA_12x();
400 break;
401
402 case Instruction::MOVE_WIDE_FROM16:
403 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700404 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100405 case Instruction::MOVE_OBJECT_FROM16:
406 case Instruction::MOVE_FROM16:
407 dest = check_insn->VRegA_22x();
408 break;
409
410 case Instruction::MOVE_WIDE_16:
411 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700412 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100413 case Instruction::MOVE_OBJECT_16:
414 case Instruction::MOVE_16:
415 dest = check_insn->VRegA_32x();
416 break;
417
418 case Instruction::GOTO:
419 case Instruction::GOTO_16:
420 case Instruction::GOTO_32:
421 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700422 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100423 default:
424 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
425 check_insn->VRegA_11x() == monitor_reg;
426 }
427
428 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
429 return false;
430 }
431
432 check_insn = check_insn->Next();
433 }
434}
435
buzbee311ca162013-02-28 15:56:43 -0800436/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700437BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
438 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700439 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700440 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800441 switch (insn->dalvikInsn.opcode) {
442 case Instruction::GOTO:
443 case Instruction::GOTO_16:
444 case Instruction::GOTO_32:
445 target += insn->dalvikInsn.vA;
446 break;
447 case Instruction::IF_EQ:
448 case Instruction::IF_NE:
449 case Instruction::IF_LT:
450 case Instruction::IF_GE:
451 case Instruction::IF_GT:
452 case Instruction::IF_LE:
453 cur_block->conditional_branch = true;
454 target += insn->dalvikInsn.vC;
455 break;
456 case Instruction::IF_EQZ:
457 case Instruction::IF_NEZ:
458 case Instruction::IF_LTZ:
459 case Instruction::IF_GEZ:
460 case Instruction::IF_GTZ:
461 case Instruction::IF_LEZ:
462 cur_block->conditional_branch = true;
463 target += insn->dalvikInsn.vB;
464 break;
465 default:
466 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
467 }
buzbeeb48819d2013-09-14 16:15:25 -0700468 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700469 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800470 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700471 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100472 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800473
474 /* Always terminate the current block for conditional branches */
475 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700476 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800477 /*
478 * If the method is processed
479 * in sequential order from the
480 * beginning, we don't need to
481 * specify split for continue
482 * blocks. However, this
483 * routine can be called by
484 * compileLoop, which starts
485 * parsing the method from an
486 * arbitrary address in the
487 * method body.
488 */
489 true,
490 /* create */
491 true,
492 /* immed_pred_block_p */
493 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700494 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100495 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800496 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700497 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800498 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800499 }
500 return cur_block;
501}
502
503/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800504BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
505 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800506 const uint16_t* switch_data =
507 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
508 int size;
509 const int* keyTable;
510 const int* target_table;
511 int i;
512 int first_key;
513
514 /*
515 * Packed switch data format:
516 * ushort ident = 0x0100 magic value
517 * ushort size number of entries in the table
518 * int first_key first (and lowest) switch case value
519 * int targets[size] branch targets, relative to switch opcode
520 *
521 * Total size is (4+size*2) 16-bit code units.
522 */
523 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
524 DCHECK_EQ(static_cast<int>(switch_data[0]),
525 static_cast<int>(Instruction::kPackedSwitchSignature));
526 size = switch_data[1];
527 first_key = switch_data[2] | (switch_data[3] << 16);
528 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700529 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800530 /*
531 * Sparse switch data format:
532 * ushort ident = 0x0200 magic value
533 * ushort size number of entries in the table; > 0
534 * int keys[size] keys, sorted low-to-high; 32-bit aligned
535 * int targets[size] branch targets, relative to switch opcode
536 *
537 * Total size is (2+size*4) 16-bit code units.
538 */
539 } else {
540 DCHECK_EQ(static_cast<int>(switch_data[0]),
541 static_cast<int>(Instruction::kSparseSwitchSignature));
542 size = switch_data[1];
543 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
544 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700545 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800546 }
547
buzbee0d829482013-10-11 15:24:55 -0700548 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800549 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700550 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800551 }
buzbee0d829482013-10-11 15:24:55 -0700552 cur_block->successor_block_list_type =
553 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100554 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800555
556 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700557 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800558 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700559 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700560 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000561 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700562 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800563 successor_block_info->key =
564 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
565 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100566 cur_block->successor_blocks.push_back(successor_block_info);
567 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800568 }
569
570 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700571 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
572 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700573 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100574 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800575 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800576}
577
578/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700579BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
580 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700581 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700582 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800583 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800584
585 /* In try block */
586 if (in_try_block) {
587 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
588
buzbee0d829482013-10-11 15:24:55 -0700589 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800590 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
591 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700592 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800593 }
594
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700595 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700596 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800597 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100598 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
599 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
600 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
601 continue;
602 }
603 if (cur_block->successor_block_list_type == kNotUsed) {
604 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100605 }
buzbee311ca162013-02-28 15:56:43 -0800606 catch_block->catch_entry = true;
607 if (kIsDebugBuild) {
608 catches_.insert(catch_block->start_offset);
609 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700610 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000611 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700612 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800613 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100614 cur_block->successor_blocks.push_back(successor_block_info);
615 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800616 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100617 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
618 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100619 bool build_all_edges =
620 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100621 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100622 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700623 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800624 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100625 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800626 }
627
buzbee17189ac2013-11-08 11:07:02 -0800628 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800629 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700630 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700631 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800632 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
633 /* immed_pred_block_p */ NULL);
634 }
635 if (!in_try_block) {
636 // Don't split a THROW that can't rethrow - we're done.
637 return cur_block;
638 }
639 }
640
buzbee17189ac2013-11-08 11:07:02 -0800641 if (!build_all_edges) {
642 /*
643 * Even though there is an exception edge here, control cannot return to this
644 * method. Thus, for the purposes of dataflow analysis and optimization, we can
645 * ignore the edge. Doing this reduces compile time, and increases the scope
646 * of the basic-block level optimization pass.
647 */
648 return cur_block;
649 }
650
buzbee311ca162013-02-28 15:56:43 -0800651 /*
652 * Split the potentially-throwing instruction into two parts.
653 * The first half will be a pseudo-op that captures the exception
654 * edges and terminates the basic block. It always falls through.
655 * Then, create a new basic block that begins with the throwing instruction
656 * (minus exceptions). Note: this new basic block must NOT be entered into
657 * the block_map. If the potentially-throwing instruction is the target of a
658 * future branch, we need to find the check psuedo half. The new
659 * basic block containing the work portion of the instruction should
660 * only be entered via fallthrough from the block containing the
661 * pseudo exception edge MIR. Note also that this new block is
662 * not automatically terminated after the work portion, and may
663 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700664 *
665 * Note also that the dex_pc_to_block_map_ entry for the potentially
666 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800667 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100668 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800669 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700670 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100671 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700672 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800673 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700674 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700675 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800676 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700677 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800678 return new_block;
679}
680
681/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
682void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700683 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700684 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800685 current_code_item_ = code_item;
686 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
687 current_method_ = m_units_.size();
688 current_offset_ = 0;
689 // TODO: will need to snapshot stack image and use that as the mir context identification.
690 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000691 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
692 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800693 const uint16_t* code_ptr = current_code_item_->insns_;
694 const uint16_t* code_end =
695 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
696
697 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700698 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100699 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
700 dex_pc_to_block_map_.resize(dex_pc_to_block_map_.size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700701
buzbee311ca162013-02-28 15:56:43 -0800702 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700703 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
704 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800705
706 // If this is the first method, set up default entry and exit blocks.
707 if (current_method_ == 0) {
708 DCHECK(entry_block_ == NULL);
709 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700710 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700711 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100712 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700713 DCHECK_EQ(null_block->id, NullBasicBlockId);
714 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100715 entry_block_ = CreateNewBB(kEntryBlock);
716 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800717 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
718 cu_->dex_file = &dex_file;
719 cu_->class_def_idx = class_def_idx;
720 cu_->method_idx = method_idx;
721 cu_->access_flags = access_flags;
722 cu_->invoke_type = invoke_type;
723 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800724 } else {
725 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
726 /*
727 * Will need to manage storage for ins & outs, push prevous state and update
728 * insert point.
729 */
730 }
731
732 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100733 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700734 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800735 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700736 // TODO: for inlining support, insert at the insert point rather than entry block.
737 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100738 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800739
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000740 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800741 ProcessTryCatchBlocks();
742
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000743 uint64_t merged_df_flags = 0u;
744
buzbee311ca162013-02-28 15:56:43 -0800745 /* Parse all instructions and put them into containing basic blocks */
746 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700747 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800748 insn->offset = current_offset_;
749 insn->m_unit_index = current_method_;
750 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800751 Instruction::Code opcode = insn->dalvikInsn.opcode;
752 if (opcode_count_ != NULL) {
753 opcode_count_[static_cast<int>(opcode)]++;
754 }
755
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700756 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800757 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800758
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700759 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000760 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800761
762 if (df_flags & DF_HAS_DEFS) {
763 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
764 }
765
buzbee1da1e2f2013-11-15 13:37:01 -0800766 if (df_flags & DF_LVN) {
767 cur_block->use_lvn = true; // Run local value numbering on this basic block.
768 }
769
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700770 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700771 if (opcode == Instruction::NOP) {
772 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
773 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
774 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
775 uint16_t following_raw_instruction = code_ptr[1];
776 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
777 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
778 (following_raw_instruction == Instruction::kArrayDataSignature)) {
779 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
780 }
781 }
782 if (width == 1) {
783 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700784 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700785 } else {
buzbee0d829482013-10-11 15:24:55 -0700786 DCHECK(cur_block->fall_through == NullBasicBlockId);
787 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700788 // Unreachable instruction, mark for no continuation.
789 flags &= ~Instruction::kContinue;
790 }
791 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700792 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700793 }
794
buzbeeb48819d2013-09-14 16:15:25 -0700795 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100796 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700797
buzbee27247762013-07-28 12:03:58 -0700798 code_ptr += width;
799
buzbee311ca162013-02-28 15:56:43 -0800800 if (flags & Instruction::kBranch) {
801 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
802 width, flags, code_ptr, code_end);
803 } else if (flags & Instruction::kReturn) {
804 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700805 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100806 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800807 /*
808 * Terminate the current block if there are instructions
809 * afterwards.
810 */
811 if (code_ptr < code_end) {
812 /*
813 * Create a fallthrough block for real instructions
814 * (incl. NOP).
815 */
buzbee27247762013-07-28 12:03:58 -0700816 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
817 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800818 }
819 } else if (flags & Instruction::kThrow) {
820 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
821 code_ptr, code_end);
822 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800823 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800824 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700825 if (verify_flags & Instruction::kVerifyVarArgRange ||
826 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800827 /*
828 * The Quick backend's runtime model includes a gap between a method's
829 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
830 * which spans the gap is somewhat complicated, and should not happen
831 * in normal usage of dx. Punt to the interpreter.
832 */
833 int first_reg_in_range = insn->dalvikInsn.vC;
834 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
835 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
836 punt_to_interpreter_ = true;
837 }
838 }
buzbee311ca162013-02-28 15:56:43 -0800839 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700840 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800841 false, /* immed_pred_block_p */ NULL);
842 if (next_block) {
843 /*
844 * The next instruction could be the target of a previously parsed
845 * forward branch so a block is already created. If the current
846 * instruction is not an unconditional branch, connect them through
847 * the fall-through link.
848 */
buzbee0d829482013-10-11 15:24:55 -0700849 DCHECK(cur_block->fall_through == NullBasicBlockId ||
850 GetBasicBlock(cur_block->fall_through) == next_block ||
851 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800852
buzbee0d829482013-10-11 15:24:55 -0700853 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
854 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100855 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800856 }
857 cur_block = next_block;
858 }
859 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000860 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000861
buzbee311ca162013-02-28 15:56:43 -0800862 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
863 DumpCFG("/sdcard/1_post_parse_cfg/", true);
864 }
865
866 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700867 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800868 }
869}
870
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700871void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800872 DCHECK(opcode_count_ != NULL);
873 LOG(INFO) << "Opcode Count";
874 for (int i = 0; i < kNumPackedOpcodes; i++) {
875 if (opcode_count_[i] != 0) {
876 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
877 << " " << opcode_count_[i];
878 }
879 }
880}
881
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700882uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
883 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
884 return oat_data_flow_attributes_[opcode];
885}
886
887uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
888 DCHECK(mir != nullptr);
889 Instruction::Code opcode = mir->dalvikInsn.opcode;
890 return GetDataFlowAttributes(opcode);
891}
892
buzbee311ca162013-02-28 15:56:43 -0800893// TODO: use a configurable base prefix, and adjust callers to supply pass name.
894/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800895void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800896 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700897 static AtomicInteger cnt(0);
898
899 // Increment counter to get a unique file number.
900 cnt++;
901
buzbee311ca162013-02-28 15:56:43 -0800902 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
903 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700904 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800905 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700906 suffix == nullptr ? "" : suffix,
907 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800908 file = fopen(fname.c_str(), "w");
909 if (file == NULL) {
910 return;
911 }
912 fprintf(file, "digraph G {\n");
913
914 fprintf(file, " rankdir=TB\n");
915
916 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
917 int idx;
918
919 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100920 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700921 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700922 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800923 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700924 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800925 if (bb->block_type == kEntryBlock) {
926 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
927 } else if (bb->block_type == kExitBlock) {
928 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
929 } else if (bb->block_type == kDalvikByteCode) {
930 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
931 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700932 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800933 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
934 bb->first_mir_insn ? " | " : " ");
935 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
936 int opcode = mir->dalvikInsn.opcode;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100937 fprintf(file, " {%04x %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400938 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700939 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
940 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400941 extended_mir_op_names_[opcode - kMirOpFirst],
942 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
943 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700944 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700945 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700946 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100947 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
948 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400949 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800950 }
951 fprintf(file, " }\"];\n\n");
952 } else if (bb->block_type == kExceptionHandling) {
953 char block_name[BLOCK_NAME_LEN];
954
955 GetBlockName(bb, block_name);
956 fprintf(file, " %s [shape=invhouse];\n", block_name);
957 }
958
959 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
960
buzbee0d829482013-10-11 15:24:55 -0700961 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800962 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700963 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800964 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
965 block_name1, block_name2);
966 }
buzbee0d829482013-10-11 15:24:55 -0700967 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800968 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700969 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800970 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
971 }
972
buzbee0d829482013-10-11 15:24:55 -0700973 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800974 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
975 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700976 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800977
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100978 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800979 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100980 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700981 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800982 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100983 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800984 successor_block_info->key,
985 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100986 (succ_id != last_succ_id) ? " | " : " ");
987 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800988 }
989 fprintf(file, " }\"];\n\n");
990
991 GetBlockName(bb, block_name1);
992 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
993 block_name1, bb->start_offset, bb->id);
994
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700995 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700996 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100997 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700998 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800999
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001000 GetBlockName(dest_block, block_name2);
1001 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1002 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001003 }
1004 }
1005 fprintf(file, "\n");
1006
1007 if (cu_->verbose) {
1008 /* Display the dominator tree */
1009 GetBlockName(bb, block_name1);
1010 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1011 block_name1, block_name1);
1012 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001013 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001014 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1015 }
1016 }
1017 }
1018 fprintf(file, "}\n");
1019 fclose(file);
1020}
1021
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001022/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001023void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001024 // Insert it after the last MIR.
1025 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001026}
1027
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001028void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1029 // Insert it after the last MIR.
1030 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1031}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001032
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001033void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1034 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1035 MIR* new_mir = *it;
1036
1037 // Add a copy of each MIR.
1038 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1039 }
buzbee1fd33462013-03-25 13:40:45 -07001040}
1041
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001042/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001043void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001044 InsertMIRListAfter(current_mir, new_mir, new_mir);
1045}
buzbee1fd33462013-03-25 13:40:45 -07001046
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001047void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1048 // If no MIR, we are done.
1049 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1050 return;
buzbee1fd33462013-03-25 13:40:45 -07001051 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001052
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001053 // If insert_after is null, assume BB is empty.
1054 if (insert_after == nullptr) {
1055 first_mir_insn = first_list_mir;
1056 last_mir_insn = last_list_mir;
1057 last_list_mir->next = nullptr;
1058 } else {
1059 MIR* after_list = insert_after->next;
1060 insert_after->next = first_list_mir;
1061 last_list_mir->next = after_list;
1062 if (after_list == nullptr) {
1063 last_mir_insn = last_list_mir;
1064 }
1065 }
1066
1067 // Set this BB to be the basic block of the MIRs.
1068 MIR* last = last_list_mir->next;
1069 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1070 mir->bb = id;
1071 }
1072}
1073
1074/* Insert an MIR instruction to the head of a basic block. */
1075void BasicBlock::PrependMIR(MIR* mir) {
1076 InsertMIRListBefore(first_mir_insn, mir, mir);
1077}
1078
1079void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1080 // Insert it before the first MIR.
1081 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1082}
1083
1084void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1085 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1086 MIR* mir = *it;
1087
1088 InsertMIRListBefore(first_mir_insn, mir, mir);
1089 }
1090}
1091
1092/* Insert a MIR instruction before the specified MIR. */
1093void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1094 // Insert as a single element list.
1095 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001096}
1097
1098MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1099 MIR* current = first_mir_insn;
1100
1101 while (current != nullptr) {
1102 MIR* next = current->next;
1103
1104 if (next == mir) {
1105 return current;
1106 }
1107
1108 current = next;
1109 }
1110
1111 return nullptr;
1112}
1113
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001114void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1115 // If no MIR, we are done.
1116 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1117 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001118 }
1119
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001120 // If insert_before is null, assume BB is empty.
1121 if (insert_before == nullptr) {
1122 first_mir_insn = first_list_mir;
1123 last_mir_insn = last_list_mir;
1124 last_list_mir->next = nullptr;
1125 } else {
1126 if (first_mir_insn == insert_before) {
1127 last_list_mir->next = first_mir_insn;
1128 first_mir_insn = first_list_mir;
1129 } else {
1130 // Find the preceding MIR.
1131 MIR* before_list = FindPreviousMIR(insert_before);
1132 DCHECK(before_list != nullptr);
1133 before_list->next = first_list_mir;
1134 last_list_mir->next = insert_before;
1135 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001136 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001137
1138 // Set this BB to be the basic block of the MIRs.
1139 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1140 mir->bb = id;
1141 }
1142}
1143
1144bool BasicBlock::RemoveMIR(MIR* mir) {
1145 // Remove as a single element list.
1146 return RemoveMIRList(mir, mir);
1147}
1148
1149bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1150 if (first_list_mir == nullptr) {
1151 return false;
1152 }
1153
1154 // Try to find the MIR.
1155 MIR* before_list = nullptr;
1156 MIR* after_list = nullptr;
1157
1158 // If we are removing from the beginning of the MIR list.
1159 if (first_mir_insn == first_list_mir) {
1160 before_list = nullptr;
1161 } else {
1162 before_list = FindPreviousMIR(first_list_mir);
1163 if (before_list == nullptr) {
1164 // We did not find the mir.
1165 return false;
1166 }
1167 }
1168
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001169 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001170 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001171 mir->bb = NullBasicBlockId;
1172 }
1173
1174 after_list = last_list_mir->next;
1175
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001176 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001177 if (before_list == nullptr) {
1178 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001179 } else {
1180 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001181 }
1182
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001183 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001184 if (after_list == nullptr) {
1185 last_mir_insn = before_list;
1186 }
1187
1188 return true;
buzbee1fd33462013-03-25 13:40:45 -07001189}
1190
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001191MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001192 MIR* next_mir = nullptr;
1193
1194 if (current != nullptr) {
1195 next_mir = current->next;
1196 }
1197
1198 if (next_mir == nullptr) {
1199 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001200 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1201 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001202 }
1203 }
1204
1205 return next_mir;
1206}
1207
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001208static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1209 DCHECK(decoded_mir != nullptr);
1210 OpSize type = static_cast<OpSize>(type_size >> 16);
1211 uint16_t vect_size = (type_size & 0xFFFF);
1212
1213 // Now print the type and vector size.
1214 std::stringstream ss;
1215 ss << " (type:";
1216 ss << type;
1217 ss << " vectsize:";
1218 ss << vect_size;
1219 ss << ")";
1220
1221 decoded_mir->append(ss.str());
1222}
1223
1224void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1225 DCHECK(decoded_mir != nullptr);
1226 int opcode = mir->dalvikInsn.opcode;
1227 SSARepresentation* ssa_rep = mir->ssa_rep;
1228 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1229 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1230
1231 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1232
1233 switch (opcode) {
1234 case kMirOpPhi: {
1235 if (defs > 0 && uses > 0) {
1236 BasicBlockId* incoming = mir->meta.phi_incoming;
1237 decoded_mir->append(StringPrintf(" %s = (%s",
1238 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1239 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1240 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1241 for (int i = 1; i < uses; i++) {
1242 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1243 }
1244 decoded_mir->append(")");
1245 }
1246 break;
1247 }
1248 case kMirOpCopy:
1249 if (ssa_rep != nullptr) {
1250 decoded_mir->append(" ");
1251 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1252 if (defs > 1) {
1253 decoded_mir->append(", ");
1254 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1255 }
1256 decoded_mir->append(" = ");
1257 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1258 if (uses > 1) {
1259 decoded_mir->append(", ");
1260 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1261 }
1262 } else {
1263 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1264 }
1265 break;
1266 case kMirOpFusedCmplFloat:
1267 case kMirOpFusedCmpgFloat:
1268 case kMirOpFusedCmplDouble:
1269 case kMirOpFusedCmpgDouble:
1270 case kMirOpFusedCmpLong:
1271 if (ssa_rep != nullptr) {
1272 decoded_mir->append(" ");
1273 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1274 for (int i = 1; i < uses; i++) {
1275 decoded_mir->append(", ");
1276 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1277 }
1278 } else {
1279 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1280 }
1281 break;
1282 case kMirOpMoveVector:
1283 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1284 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1285 break;
1286 case kMirOpPackedAddition:
1287 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1288 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1289 break;
1290 case kMirOpPackedMultiply:
1291 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1292 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1293 break;
1294 case kMirOpPackedSubtract:
1295 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1296 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1297 break;
1298 case kMirOpPackedAnd:
1299 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1300 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1301 break;
1302 case kMirOpPackedOr:
1303 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1304 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1305 break;
1306 case kMirOpPackedXor:
1307 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1308 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1309 break;
1310 case kMirOpPackedShiftLeft:
1311 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1312 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1313 break;
1314 case kMirOpPackedUnsignedShiftRight:
1315 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1316 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1317 break;
1318 case kMirOpPackedSignedShiftRight:
1319 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1320 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1321 break;
1322 case kMirOpConstVector:
1323 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1324 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1325 break;
1326 case kMirOpPackedSet:
1327 if (ssa_rep != nullptr) {
1328 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1329 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1330 if (uses > 1) {
1331 decoded_mir->append(", ");
1332 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1333 }
1334 } else {
1335 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1336 }
1337 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1338 break;
1339 case kMirOpPackedAddReduce:
1340 if (ssa_rep != nullptr) {
1341 decoded_mir->append(" ");
1342 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1343 if (defs > 1) {
1344 decoded_mir->append(", ");
1345 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1346 }
1347 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1348 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1349 if (uses > 1) {
1350 decoded_mir->append(", ");
1351 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1352 }
1353 } else {
1354 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1355 }
1356 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1357 break;
1358 case kMirOpPackedReduce:
1359 if (ssa_rep != nullptr) {
1360 decoded_mir->append(" ");
1361 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1362 if (defs > 1) {
1363 decoded_mir->append(", ");
1364 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1365 }
1366 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1367 } else {
1368 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1369 }
1370 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1371 break;
1372 case kMirOpReserveVectorRegisters:
1373 case kMirOpReturnVectorRegisters:
1374 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1375 break;
1376 case kMirOpMemBarrier: {
1377 decoded_mir->append(" type:");
1378 std::stringstream ss;
1379 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1380 decoded_mir->append(ss.str());
1381 break;
1382 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001383 case kMirOpPackedArrayGet:
1384 case kMirOpPackedArrayPut:
1385 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1386 if (ssa_rep != nullptr) {
1387 decoded_mir->append(StringPrintf(", %s[%s]",
1388 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1389 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1390 } else {
1391 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1392 }
1393 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1394 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001395 default:
1396 break;
1397 }
1398}
1399
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001400char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001401 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001402 std::string str;
1403 int flags = 0;
1404 int opcode = insn.opcode;
1405 char* ret;
1406 bool nop = false;
1407 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001408 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001409
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001410 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001411 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1412 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1413 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001414 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001415 insn = mir->meta.throw_insn->dalvikInsn;
1416 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001417 opcode = insn.opcode;
1418 } else if (opcode == kMirOpNop) {
1419 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001420 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1421 // Recover original opcode.
1422 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1423 opcode = insn.opcode;
1424 }
buzbee1fd33462013-03-25 13:40:45 -07001425 nop = true;
1426 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001427 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1428 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001429
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001430 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001431 // Note that this does not check the MIR's opcode in all cases. In cases where it
1432 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1433 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001434 } else {
1435 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001436 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001437 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001438
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001439 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001440 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1441 (dalvik_format == Instruction::k3rc));
1442 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001443 str.append(" ");
1444 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1445 if (defs > 1) {
1446 str.append(", ");
1447 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1448 }
buzbee1fd33462013-03-25 13:40:45 -07001449 if (uses != 0) {
1450 str.append(", ");
1451 }
1452 }
1453 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001454 str.append(" ");
1455 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001456 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1457 // For the listing, skip the high sreg.
1458 i++;
1459 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001460 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001461 str.append(",");
1462 }
1463 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001464
buzbee1fd33462013-03-25 13:40:45 -07001465 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001466 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001467 case Instruction::k21s:
1468 case Instruction::k31i:
1469 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001470 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001471 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001472 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001473 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001474 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001475 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001476 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001477 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001478 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001479 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001480 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001481 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001482 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001483 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001484 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001485 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001486 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001487 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001488 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001489 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001490
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001491 if ((flags & Instruction::kBranch) != 0) {
1492 // For branches, decode the instructions to print out the branch targets.
1493 int offset = 0;
1494 switch (dalvik_format) {
1495 case Instruction::k21t:
1496 offset = insn.vB;
1497 break;
1498 case Instruction::k22t:
1499 offset = insn.vC;
1500 break;
1501 case Instruction::k10t:
1502 case Instruction::k20t:
1503 case Instruction::k30t:
1504 offset = insn.vA;
1505 break;
1506 default:
1507 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001508 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001509 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001510 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001511 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1512 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001513
1514 if (nop) {
1515 str.append("]--optimized away");
1516 }
buzbee1fd33462013-03-25 13:40:45 -07001517 }
1518 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001519 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001520 strncpy(ret, str.c_str(), length);
1521 return ret;
1522}
1523
1524/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001525void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001526 static const struct { const char before; const char after; } match[] = {
1527 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1528 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1529 };
buzbee1fd33462013-03-25 13:40:45 -07001530 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1531 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1532 }
1533}
1534
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001535std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001536 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1537 // the arena. We should be smarter and just place straight into the arena, or compute the
1538 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001539 int vreg = SRegToVReg(ssa_reg);
1540 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1541 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1542 } else {
1543 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1544 }
buzbee1fd33462013-03-25 13:40:45 -07001545}
1546
1547// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001548std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001549 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001550 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001551 return GetSSAName(ssa_reg);
1552 }
1553 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001554 if (!singles_only && reg_location_[ssa_reg].wide &&
1555 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001556 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001557 ConstantValueWide(reg_location_[ssa_reg]));
1558 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001559 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001560 ConstantValue(reg_location_[ssa_reg]));
1561 }
1562 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001563 int vreg = SRegToVReg(ssa_reg);
1564 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1565 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1566 } else {
1567 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1568 }
buzbee1fd33462013-03-25 13:40:45 -07001569 }
1570}
1571
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001572void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001573 switch (bb->block_type) {
1574 case kEntryBlock:
1575 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1576 break;
1577 case kExitBlock:
1578 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1579 break;
1580 case kDalvikByteCode:
1581 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1582 break;
1583 case kExceptionHandling:
1584 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1585 bb->id);
1586 break;
1587 default:
1588 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1589 break;
1590 }
1591}
1592
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001593const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001594 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001595 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1596 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1597}
1598
1599/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001600void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001601 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001602 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001603 "Entry Block",
1604 "Code Block",
1605 "Exit Block",
1606 "Exception Handling",
1607 "Catch Block"
1608 };
1609
1610 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001611 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001612 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001613
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001614 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001615 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1616 bb->id,
1617 block_type_names[bb->block_type],
1618 bb->start_offset,
1619 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1620 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001621 if (bb->taken != NullBasicBlockId) {
1622 LOG(INFO) << " Taken branch: block " << bb->taken
1623 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001624 }
buzbee0d829482013-10-11 15:24:55 -07001625 if (bb->fall_through != NullBasicBlockId) {
1626 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1627 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001628 }
1629 }
1630}
1631
1632/*
1633 * Build an array of location records for the incoming arguments.
1634 * Note: one location record per word of arguments, with dummy
1635 * high-word loc for wide arguments. Also pull up any following
1636 * MOVE_RESULT and incorporate it into the invoke.
1637 */
1638CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001639 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001640 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001641 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001642 MIR* move_result_mir = FindMoveResult(bb, mir);
1643 if (move_result_mir == NULL) {
1644 info->result.location = kLocInvalid;
1645 } else {
1646 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001647 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1648 }
1649 info->num_arg_words = mir->ssa_rep->num_uses;
1650 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001651 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001652 for (int i = 0; i < info->num_arg_words; i++) {
1653 info->args[i] = GetRawSrc(mir, i);
1654 }
1655 info->opt_flags = mir->optimization_flags;
1656 info->type = type;
1657 info->is_range = is_range;
1658 info->index = mir->dalvikInsn.vB;
1659 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001660 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001661 return info;
1662}
1663
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001664// Allocate a new MIR.
1665MIR* MIRGraph::NewMIR() {
1666 MIR* mir = new (arena_) MIR();
1667 return mir;
1668}
1669
buzbee862a7602013-04-05 10:58:54 -07001670// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001671BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001672 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001673
buzbee862a7602013-04-05 10:58:54 -07001674 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001675 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001676 block_id_map_.Put(block_id, block_id);
1677 return bb;
1678}
buzbee1fd33462013-03-25 13:40:45 -07001679
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001680void MIRGraph::InitializeConstantPropagation() {
1681 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001682 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001683}
1684
1685void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001686 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001687 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001688 use_counts_.clear();
1689 use_counts_.reserve(num_ssa_regs + 32);
1690 use_counts_.resize(num_ssa_regs, 0u);
1691 raw_use_counts_.clear();
1692 raw_use_counts_.reserve(num_ssa_regs + 32);
1693 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001694}
1695
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001696void MIRGraph::SSATransformationStart() {
1697 DCHECK(temp_scoped_alloc_.get() == nullptr);
1698 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001699 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001700 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1701 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001702}
1703
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001704void MIRGraph::SSATransformationEnd() {
1705 // Verify the dataflow information after the pass.
1706 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1707 VerifyDataflow();
1708 }
1709
1710 temp_bit_vector_size_ = 0u;
1711 temp_bit_vector_ = nullptr;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001712 temp_bit_matrix_ = nullptr; // Def block matrix.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001713 DCHECK(temp_scoped_alloc_.get() != nullptr);
1714 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001715
1716 // Update the maximum number of reachable blocks.
1717 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001718}
1719
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001720size_t MIRGraph::GetNumDalvikInsns() const {
1721 size_t cumulative_size = 0u;
1722 bool counted_current_item = false;
1723 const uint8_t size_for_null_code_item = 2u;
1724
1725 for (auto it : m_units_) {
1726 const DexFile::CodeItem* code_item = it->GetCodeItem();
1727 // Even if the code item is null, we still count non-zero value so that
1728 // each m_unit is counted as having impact.
1729 cumulative_size += (code_item == nullptr ?
1730 size_for_null_code_item : code_item->insns_size_in_code_units_);
1731 if (code_item == current_code_item_) {
1732 counted_current_item = true;
1733 }
1734 }
1735
1736 // If the current code item was not counted yet, count it now.
1737 // This can happen for example in unit tests where some fields like m_units_
1738 // are not initialized.
1739 if (counted_current_item == false) {
1740 cumulative_size += (current_code_item_ == nullptr ?
1741 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1742 }
1743
1744 return cumulative_size;
1745}
1746
Vladimir Marko55fff042014-07-10 12:42:52 +01001747static BasicBlock* SelectTopologicalSortOrderFallBack(
1748 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1749 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1750 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1751 // No true loop head has been found but there may be true loop heads after the mess we need
1752 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1753 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1754 BasicBlock* fall_back = nullptr;
1755 size_t fall_back_num_reachable = 0u;
1756 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1757 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1758 AllNodesIterator iter(mir_graph);
1759 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1760 if (candidate->hidden || // Hidden, or
1761 candidate->visited || // already processed, or
1762 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1763 (current_loop != nullptr && // outside current loop.
1764 !current_loop->IsBitSet(candidate->id))) {
1765 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001766 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001767 DCHECK(tmp_stack->empty());
1768 tmp_stack->push_back(candidate->id);
1769 candidate_reachable.ClearAllBits();
1770 size_t num_reachable = 0u;
1771 while (!tmp_stack->empty()) {
1772 BasicBlockId current_id = tmp_stack->back();
1773 tmp_stack->pop_back();
1774 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1775 DCHECK(current_bb != nullptr);
1776 ChildBlockIterator child_iter(current_bb, mir_graph);
1777 BasicBlock* child_bb = child_iter.Next();
1778 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1779 DCHECK(!child_bb->hidden);
1780 if (child_bb->visited || // Already processed, or
1781 (current_loop != nullptr && // outside current loop.
1782 !current_loop->IsBitSet(child_bb->id))) {
1783 continue;
1784 }
1785 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1786 candidate_reachable.SetBit(child_bb->id);
1787 tmp_stack->push_back(child_bb->id);
1788 num_reachable += 1u;
1789 }
1790 }
1791 }
1792 if (fall_back_num_reachable < num_reachable) {
1793 fall_back_num_reachable = num_reachable;
1794 fall_back = candidate;
1795 }
1796 }
1797 return fall_back;
1798}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001799
Vladimir Marko55fff042014-07-10 12:42:52 +01001800// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1801static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1802 ArenaBitVector* reachable,
1803 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1804 // NOTE: Loop heads indicated by the "visited" flag.
1805 DCHECK(tmp_stack->empty());
1806 reachable->ClearAllBits();
1807 tmp_stack->push_back(bb_id);
1808 while (!tmp_stack->empty()) {
1809 BasicBlockId current_id = tmp_stack->back();
1810 tmp_stack->pop_back();
1811 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1812 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001813 for (BasicBlockId pred_id : current_bb->predecessors) {
1814 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1815 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001816 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1817 reachable->SetBit(pred_bb->id);
1818 tmp_stack->push_back(pred_bb->id);
1819 }
1820 }
1821 }
1822}
1823
1824void MIRGraph::ComputeTopologicalSortOrder() {
1825 ScopedArenaAllocator allocator(&cu_->arena_stack);
1826 unsigned int num_blocks = GetNumBlocks();
1827
1828 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1829 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1830 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1831 size_t max_nested_loops = 0u;
1832 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1833 loop_exit_blocks.ClearAllBits();
1834
1835 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001836 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001837 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001838 if (bb->hidden == true) {
1839 continue;
1840 }
1841
Vladimir Marko55fff042014-07-10 12:42:52 +01001842 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001843
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001844 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001845 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001846 q.push(bb);
1847 }
1848 }
1849
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001850 // Clear the topological order arrays.
1851 topological_order_.clear();
1852 topological_order_.reserve(num_blocks);
1853 topological_order_loop_ends_.clear();
1854 topological_order_loop_ends_.resize(num_blocks, 0u);
1855 topological_order_indexes_.clear();
1856 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001857
1858 // Mark all blocks as unvisited.
1859 ClearAllVisitedFlags();
1860
1861 // For loop heads, keep track from which blocks they are reachable not going through other
1862 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1863 // in this set go into the loop body, the other children are jumping over the loop.
1864 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1865 loop_head_reachable_from.resize(num_blocks, nullptr);
1866 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1867 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1868
1869 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001870 BasicBlock* bb = nullptr;
1871 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001872 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001873 // Get top.
1874 bb = q.front();
1875 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001876 if (bb->visited) {
1877 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1878 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001879 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1880 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001881 DCHECK_EQ(loop_head_stack.back(), bb->id);
1882 loop_head_stack.pop_back();
1883 ArenaBitVector* reachable =
1884 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1885 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1886 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1887 q.push(GetBasicBlock(candidate_id));
1888 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1889 // so clearing the bit has no effect on the iterator.
1890 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001891 }
1892 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001893 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001894 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001895 } else {
1896 // Find the new loop head.
1897 AllNodesIterator iter(this);
1898 while (true) {
1899 BasicBlock* candidate = iter.Next();
1900 if (candidate == nullptr) {
1901 // We did not find a true loop head, fall back to a reachable block in any loop.
1902 ArenaBitVector* current_loop =
1903 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1904 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1905 &allocator, &tmp_stack);
1906 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1907 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1908 LOG(INFO) << "Topological sort order: Using fall-back in "
1909 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1910 << " @0x" << std::hex << bb->start_offset
1911 << ", num_blocks = " << std::dec << num_blocks;
1912 }
1913 break;
1914 }
1915 if (candidate->hidden || // Hidden, or
1916 candidate->visited || // already processed, or
1917 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1918 (!loop_head_stack.empty() && // outside current loop.
1919 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1920 continue;
1921 }
1922
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001923 for (BasicBlockId pred_id : candidate->predecessors) {
1924 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1925 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001926 if (pred_bb != candidate && !pred_bb->visited &&
1927 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001928 candidate = nullptr; // Set candidate to null to indicate failure.
1929 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001930 }
1931 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001932 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001933 bb = candidate;
1934 break;
1935 }
1936 }
1937 // Compute blocks from which the loop head is reachable and process those blocks first.
1938 ArenaBitVector* reachable =
1939 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1940 loop_head_reachable_from[bb->id] = reachable;
1941 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1942 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1943 loop_head_stack.push_back(bb->id);
1944 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001945 }
1946
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001947 DCHECK_EQ(bb->hidden, false);
1948 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001949 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001950
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001951 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001952 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1953 topological_order_indexes_[bb->id] = idx;
1954 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001955
Vladimir Marko55fff042014-07-10 12:42:52 +01001956 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001957 ChildBlockIterator succIter(bb, this);
1958 BasicBlock* successor = succIter.Next();
1959 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001960 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001961 continue;
1962 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001963
Vladimir Marko55fff042014-07-10 12:42:52 +01001964 // One more predecessor was visited.
1965 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001966 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001967 if (loop_head_stack.empty() ||
1968 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1969 q.push(successor);
1970 } else {
1971 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1972 loop_exit_blocks.SetBit(successor->id);
1973 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001974 }
1975 }
1976 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001977
1978 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001979 topological_order_loop_head_stack_.clear();
1980 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01001981 max_nested_loops_ = max_nested_loops;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001982}
1983
1984bool BasicBlock::IsExceptionBlock() const {
1985 if (block_type == kExceptionHandling) {
1986 return true;
1987 }
1988 return false;
1989}
1990
Wei Jin04f4d8a2014-05-29 18:04:29 -07001991bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1992 BasicBlock* target = GetBasicBlock(target_id);
1993
1994 if (source == nullptr || target == nullptr)
1995 return false;
1996
1997 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001998 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1999 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07002000 if (bb == source)
2001 return true; // The block has been inserted by a suspend check before.
2002 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
2003 return true;
2004 }
2005
2006 return false;
2007}
2008
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002009ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2010 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2011 visited_taken_(false), have_successors_(false) {
2012 // Check if we actually do have successors.
2013 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2014 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002015 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002016 }
2017}
2018
2019BasicBlock* ChildBlockIterator::Next() {
2020 // We check if we have a basic block. If we don't we cannot get next child.
2021 if (basic_block_ == nullptr) {
2022 return nullptr;
2023 }
2024
2025 // If we haven't visited fallthrough, return that.
2026 if (visited_fallthrough_ == false) {
2027 visited_fallthrough_ = true;
2028
2029 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2030 if (result != nullptr) {
2031 return result;
2032 }
2033 }
2034
2035 // If we haven't visited taken, return that.
2036 if (visited_taken_ == false) {
2037 visited_taken_ = true;
2038
2039 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2040 if (result != nullptr) {
2041 return result;
2042 }
2043 }
2044
2045 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2046 if (have_successors_ == true) {
2047 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002048 auto end = basic_block_->successor_blocks.cend();
2049 while (successor_iter_ != end) {
2050 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2051 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002052 // If block was replaced by zero block, take next one.
2053 if (successor_block_info->block != NullBasicBlockId) {
2054 return mir_graph_->GetBasicBlock(successor_block_info->block);
2055 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002056 }
2057 }
2058
2059 // We do not have anything.
2060 return nullptr;
2061}
2062
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002063BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2064 MIRGraph* mir_graph = c_unit->mir_graph.get();
2065 return Copy(mir_graph);
2066}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002067
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002068BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2069 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002070
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002071 // We don't do a memcpy style copy here because it would lead to a lot of things
2072 // to clean up. Let us do it by hand instead.
2073 // Copy in taken and fallthrough.
2074 result_bb->fall_through = fall_through;
2075 result_bb->taken = taken;
2076
2077 // Copy successor links if needed.
2078 ArenaAllocator* arena = mir_graph->GetArena();
2079
2080 result_bb->successor_block_list_type = successor_block_list_type;
2081 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002082 result_bb->successor_blocks.reserve(successor_blocks.size());
2083 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2084 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2085 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002086 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002087 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002088 }
2089 }
2090
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002091 // Copy offset, method.
2092 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002093
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002094 // Now copy instructions.
2095 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2096 // Get a copy first.
2097 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002098
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002099 // Append it.
2100 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002101 }
2102
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002103 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002104}
2105
2106MIR* MIR::Copy(MIRGraph* mir_graph) {
2107 MIR* res = mir_graph->NewMIR();
2108 *res = *this;
2109
2110 // Remove links
2111 res->next = nullptr;
2112 res->bb = NullBasicBlockId;
2113 res->ssa_rep = nullptr;
2114
2115 return res;
2116}
2117
2118MIR* MIR::Copy(CompilationUnit* c_unit) {
2119 return Copy(c_unit->mir_graph.get());
2120}
2121
2122uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2123 // Default result.
2124 int res = 0;
2125
2126 // We are basically setting the iputs to their igets counterparts.
2127 switch (opcode) {
2128 case Instruction::IPUT:
2129 case Instruction::IPUT_OBJECT:
2130 case Instruction::IPUT_BOOLEAN:
2131 case Instruction::IPUT_BYTE:
2132 case Instruction::IPUT_CHAR:
2133 case Instruction::IPUT_SHORT:
2134 case Instruction::IPUT_QUICK:
2135 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002136 case Instruction::IPUT_BOOLEAN_QUICK:
2137 case Instruction::IPUT_BYTE_QUICK:
2138 case Instruction::IPUT_CHAR_QUICK:
2139 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002140 case Instruction::APUT:
2141 case Instruction::APUT_OBJECT:
2142 case Instruction::APUT_BOOLEAN:
2143 case Instruction::APUT_BYTE:
2144 case Instruction::APUT_CHAR:
2145 case Instruction::APUT_SHORT:
2146 case Instruction::SPUT:
2147 case Instruction::SPUT_OBJECT:
2148 case Instruction::SPUT_BOOLEAN:
2149 case Instruction::SPUT_BYTE:
2150 case Instruction::SPUT_CHAR:
2151 case Instruction::SPUT_SHORT:
2152 // Skip the VR containing what to store.
2153 res = 1;
2154 break;
2155 case Instruction::IPUT_WIDE:
2156 case Instruction::IPUT_WIDE_QUICK:
2157 case Instruction::APUT_WIDE:
2158 case Instruction::SPUT_WIDE:
2159 // Skip the two VRs containing what to store.
2160 res = 2;
2161 break;
2162 default:
2163 // Do nothing in the general case.
2164 break;
2165 }
2166
2167 return res;
2168}
2169
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002170/**
2171 * @brief Given a decoded instruction, it checks whether the instruction
2172 * sets a constant and if it does, more information is provided about the
2173 * constant being set.
2174 * @param ptr_value pointer to a 64-bit holder for the constant.
2175 * @param wide Updated by function whether a wide constant is being set by bytecode.
2176 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2177 */
2178bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2179 bool sets_const = true;
2180 int64_t value = vB;
2181
2182 DCHECK(ptr_value != nullptr);
2183 DCHECK(wide != nullptr);
2184
2185 switch (opcode) {
2186 case Instruction::CONST_4:
2187 case Instruction::CONST_16:
2188 case Instruction::CONST:
2189 *wide = false;
2190 value <<= 32; // In order to get the sign extend.
2191 value >>= 32;
2192 break;
2193 case Instruction::CONST_HIGH16:
2194 *wide = false;
2195 value <<= 48; // In order to get the sign extend.
2196 value >>= 32;
2197 break;
2198 case Instruction::CONST_WIDE_16:
2199 case Instruction::CONST_WIDE_32:
2200 *wide = true;
2201 value <<= 32; // In order to get the sign extend.
2202 value >>= 32;
2203 break;
2204 case Instruction::CONST_WIDE:
2205 *wide = true;
2206 value = vB_wide;
2207 break;
2208 case Instruction::CONST_WIDE_HIGH16:
2209 *wide = true;
2210 value <<= 48; // In order to get the sign extend.
2211 break;
2212 default:
2213 sets_const = false;
2214 break;
2215 }
2216
2217 if (sets_const) {
2218 *ptr_value = value;
2219 }
2220
2221 return sets_const;
2222}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002223
2224void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2225 // Reset flags for all MIRs in bb.
2226 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2227 mir->optimization_flags &= (~reset_flags);
2228 }
2229}
2230
Vladimir Marko312eb252014-10-07 15:01:57 +01002231void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002232 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2233 block_type = kDalvikByteCode;
2234
2235 // Mark it as hidden.
2236 hidden = true;
2237
2238 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2239 // are updated to know that they no longer have a parent.
2240 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2241 mir->bb = NullBasicBlockId;
2242 }
2243 first_mir_insn = nullptr;
2244 last_mir_insn = nullptr;
2245
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002246 for (BasicBlockId pred_id : predecessors) {
2247 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2248 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002249
2250 // Sadly we have to go through the children by hand here.
2251 pred_bb->ReplaceChild(id, NullBasicBlockId);
2252 }
2253
2254 // Iterate through children of bb we are hiding.
2255 ChildBlockIterator successorChildIter(this, mir_graph);
2256
2257 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002258 // Erase this predecessor from child.
2259 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002260 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002261
2262 // Remove link to children.
2263 taken = NullBasicBlockId;
2264 fall_through = NullBasicBlockId;
2265 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002266}
2267
Vladimir Marko312eb252014-10-07 15:01:57 +01002268/*
2269 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2270 */
2271void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2272 DCHECK(predecessors.empty()); // Unreachable.
2273
2274 // Mark as dead and hidden.
2275 block_type = kDead;
2276 hidden = true;
2277
2278 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2279 // are updated to know that they no longer have a parent.
2280 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2281 mir->bb = NullBasicBlockId;
2282 }
2283 first_mir_insn = nullptr;
2284 last_mir_insn = nullptr;
2285
2286 data_flow_info = nullptr;
2287
2288 // Erase this bb from all children's predecessors and kill unreachable children.
2289 ChildBlockIterator iter(this, mir_graph);
2290 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2291 succ_bb->ErasePredecessor(id);
2292 if (succ_bb->predecessors.empty()) {
2293 succ_bb->KillUnreachable(mir_graph);
2294 }
2295 }
2296
2297 // Remove links to children.
2298 fall_through = NullBasicBlockId;
2299 taken = NullBasicBlockId;
2300 successor_block_list_type = kNotUsed;
2301
2302 if (kIsDebugBuild) {
2303 if (catch_entry) {
2304 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2305 mir_graph->catches_.erase(start_offset);
2306 }
2307 }
2308}
2309
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002310bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2311 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2312 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2313 // then it is not live out of this BB.
2314 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2315
2316 int last_ssa_reg = -1;
2317
2318 // Walk through the MIRs backwards.
2319 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2320 // Get ssa rep.
2321 SSARepresentation *ssa_rep = mir->ssa_rep;
2322
2323 // Go through the defines for this MIR.
2324 for (int i = 0; i < ssa_rep->num_defs; i++) {
2325 DCHECK(ssa_rep->defs != nullptr);
2326
2327 // Get the ssa reg.
2328 int def_ssa_reg = ssa_rep->defs[i];
2329
2330 // Get dalvik reg.
2331 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2332
2333 // Compare dalvik regs.
2334 if (dalvik_reg == def_dalvik_reg) {
2335 // We found a def of the register that we are being asked about.
2336 // Remember it.
2337 last_ssa_reg = def_ssa_reg;
2338 }
2339 }
2340 }
2341
2342 if (last_ssa_reg == -1) {
2343 // If we get to this point we couldn't find a define of register user asked about.
2344 // Let's assume the user knows what he's doing so we can be safe and say that if we
2345 // couldn't find a def, it is live out.
2346 return true;
2347 }
2348
2349 // If it is not -1, we found a match, is it ssa_reg?
2350 return (ssa_reg == last_ssa_reg);
2351}
2352
2353bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2354 // We need to check taken, fall_through, and successor_blocks to replace.
2355 bool found = false;
2356 if (taken == old_bb) {
2357 taken = new_bb;
2358 found = true;
2359 }
2360
2361 if (fall_through == old_bb) {
2362 fall_through = new_bb;
2363 found = true;
2364 }
2365
2366 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002367 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002368 if (successor_block_info->block == old_bb) {
2369 successor_block_info->block = new_bb;
2370 found = true;
2371 }
2372 }
2373 }
2374
2375 return found;
2376}
2377
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002378void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2379 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2380 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002381 // It's faster to move the back() to *pos than erase(pos).
2382 *pos = predecessors.back();
2383 predecessors.pop_back();
2384 size_t idx = std::distance(predecessors.begin(), pos);
2385 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2386 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2387 break;
2388 }
2389 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2390 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2391 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2392 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2393 mir->ssa_rep->num_uses = predecessors.size();
2394 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002395}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002396
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002397void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2398 DCHECK_NE(new_pred, NullBasicBlockId);
2399 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002400 DCHECK(pos != predecessors.end());
2401 *pos = new_pred;
2402 size_t idx = std::distance(predecessors.begin(), pos);
2403 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2404 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2405 break;
2406 }
2407 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2408 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002409 }
2410}
2411
2412// Create a new basic block with block_id as num_blocks_ that is
2413// post-incremented.
2414BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2415 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002416 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002417 return res;
2418}
2419
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002420void MIRGraph::CalculateBasicBlockInformation() {
2421 PassDriverMEPostOpt driver(cu_);
2422 driver.Launch();
2423}
2424
2425void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002426 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002427}
2428
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002429int MIR::DecodedInstruction::FlagsOf() const {
2430 // Calculate new index.
2431 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2432
2433 // Check if it is an extended or not.
2434 if (idx < 0) {
2435 return Instruction::FlagsOf(opcode);
2436 }
2437
2438 // For extended, we use a switch.
2439 switch (static_cast<int>(opcode)) {
2440 case kMirOpPhi:
2441 return Instruction::kContinue;
2442 case kMirOpCopy:
2443 return Instruction::kContinue;
2444 case kMirOpFusedCmplFloat:
2445 return Instruction::kContinue | Instruction::kBranch;
2446 case kMirOpFusedCmpgFloat:
2447 return Instruction::kContinue | Instruction::kBranch;
2448 case kMirOpFusedCmplDouble:
2449 return Instruction::kContinue | Instruction::kBranch;
2450 case kMirOpFusedCmpgDouble:
2451 return Instruction::kContinue | Instruction::kBranch;
2452 case kMirOpFusedCmpLong:
2453 return Instruction::kContinue | Instruction::kBranch;
2454 case kMirOpNop:
2455 return Instruction::kContinue;
2456 case kMirOpNullCheck:
2457 return Instruction::kContinue | Instruction::kThrow;
2458 case kMirOpRangeCheck:
2459 return Instruction::kContinue | Instruction::kThrow;
2460 case kMirOpDivZeroCheck:
2461 return Instruction::kContinue | Instruction::kThrow;
2462 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002463 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002464 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002465 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002466 case kMirOpSelect:
2467 return Instruction::kContinue;
2468 case kMirOpConstVector:
2469 return Instruction::kContinue;
2470 case kMirOpMoveVector:
2471 return Instruction::kContinue;
2472 case kMirOpPackedMultiply:
2473 return Instruction::kContinue;
2474 case kMirOpPackedAddition:
2475 return Instruction::kContinue;
2476 case kMirOpPackedSubtract:
2477 return Instruction::kContinue;
2478 case kMirOpPackedShiftLeft:
2479 return Instruction::kContinue;
2480 case kMirOpPackedSignedShiftRight:
2481 return Instruction::kContinue;
2482 case kMirOpPackedUnsignedShiftRight:
2483 return Instruction::kContinue;
2484 case kMirOpPackedAnd:
2485 return Instruction::kContinue;
2486 case kMirOpPackedOr:
2487 return Instruction::kContinue;
2488 case kMirOpPackedXor:
2489 return Instruction::kContinue;
2490 case kMirOpPackedAddReduce:
2491 return Instruction::kContinue;
2492 case kMirOpPackedReduce:
2493 return Instruction::kContinue;
2494 case kMirOpPackedSet:
2495 return Instruction::kContinue;
2496 case kMirOpReserveVectorRegisters:
2497 return Instruction::kContinue;
2498 case kMirOpReturnVectorRegisters:
2499 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002500 case kMirOpMemBarrier:
2501 return Instruction::kContinue;
2502 case kMirOpPackedArrayGet:
2503 return Instruction::kContinue | Instruction::kThrow;
2504 case kMirOpPackedArrayPut:
2505 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002506 default:
2507 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2508 return 0;
2509 }
2510}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002511} // namespace art