blob: 3fa80b9c0b88e22c40149be7bfeadd24bca11879 [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;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700937 fprintf(file, " {%04x %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" : " ",
947 (mir->optimization_flags & MIR_IGNORE_CLINIT_CHECK) != 0 ? " no_clinit" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400948 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800949 }
950 fprintf(file, " }\"];\n\n");
951 } else if (bb->block_type == kExceptionHandling) {
952 char block_name[BLOCK_NAME_LEN];
953
954 GetBlockName(bb, block_name);
955 fprintf(file, " %s [shape=invhouse];\n", block_name);
956 }
957
958 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
959
buzbee0d829482013-10-11 15:24:55 -0700960 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800961 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700962 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800963 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
964 block_name1, block_name2);
965 }
buzbee0d829482013-10-11 15:24:55 -0700966 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800967 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700968 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800969 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
970 }
971
buzbee0d829482013-10-11 15:24:55 -0700972 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800973 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
974 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700975 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800976
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100977 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800978 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100979 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700980 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800981 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100982 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800983 successor_block_info->key,
984 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100985 (succ_id != last_succ_id) ? " | " : " ");
986 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800987 }
988 fprintf(file, " }\"];\n\n");
989
990 GetBlockName(bb, block_name1);
991 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
992 block_name1, bb->start_offset, bb->id);
993
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700994 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700995 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100996 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700997 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800998
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700999 GetBlockName(dest_block, block_name2);
1000 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1001 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001002 }
1003 }
1004 fprintf(file, "\n");
1005
1006 if (cu_->verbose) {
1007 /* Display the dominator tree */
1008 GetBlockName(bb, block_name1);
1009 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1010 block_name1, block_name1);
1011 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001012 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001013 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1014 }
1015 }
1016 }
1017 fprintf(file, "}\n");
1018 fclose(file);
1019}
1020
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001021/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001022void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001023 // Insert it after the last MIR.
1024 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001025}
1026
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001027void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1028 // Insert it after the last MIR.
1029 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1030}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001031
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001032void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1033 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1034 MIR* new_mir = *it;
1035
1036 // Add a copy of each MIR.
1037 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1038 }
buzbee1fd33462013-03-25 13:40:45 -07001039}
1040
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001041/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001042void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001043 InsertMIRListAfter(current_mir, new_mir, new_mir);
1044}
buzbee1fd33462013-03-25 13:40:45 -07001045
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001046void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1047 // If no MIR, we are done.
1048 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1049 return;
buzbee1fd33462013-03-25 13:40:45 -07001050 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001051
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001052 // If insert_after is null, assume BB is empty.
1053 if (insert_after == nullptr) {
1054 first_mir_insn = first_list_mir;
1055 last_mir_insn = last_list_mir;
1056 last_list_mir->next = nullptr;
1057 } else {
1058 MIR* after_list = insert_after->next;
1059 insert_after->next = first_list_mir;
1060 last_list_mir->next = after_list;
1061 if (after_list == nullptr) {
1062 last_mir_insn = last_list_mir;
1063 }
1064 }
1065
1066 // Set this BB to be the basic block of the MIRs.
1067 MIR* last = last_list_mir->next;
1068 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1069 mir->bb = id;
1070 }
1071}
1072
1073/* Insert an MIR instruction to the head of a basic block. */
1074void BasicBlock::PrependMIR(MIR* mir) {
1075 InsertMIRListBefore(first_mir_insn, mir, mir);
1076}
1077
1078void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1079 // Insert it before the first MIR.
1080 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1081}
1082
1083void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1084 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1085 MIR* mir = *it;
1086
1087 InsertMIRListBefore(first_mir_insn, mir, mir);
1088 }
1089}
1090
1091/* Insert a MIR instruction before the specified MIR. */
1092void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1093 // Insert as a single element list.
1094 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001095}
1096
1097MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1098 MIR* current = first_mir_insn;
1099
1100 while (current != nullptr) {
1101 MIR* next = current->next;
1102
1103 if (next == mir) {
1104 return current;
1105 }
1106
1107 current = next;
1108 }
1109
1110 return nullptr;
1111}
1112
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001113void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1114 // If no MIR, we are done.
1115 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1116 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001117 }
1118
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001119 // If insert_before is null, assume BB is empty.
1120 if (insert_before == nullptr) {
1121 first_mir_insn = first_list_mir;
1122 last_mir_insn = last_list_mir;
1123 last_list_mir->next = nullptr;
1124 } else {
1125 if (first_mir_insn == insert_before) {
1126 last_list_mir->next = first_mir_insn;
1127 first_mir_insn = first_list_mir;
1128 } else {
1129 // Find the preceding MIR.
1130 MIR* before_list = FindPreviousMIR(insert_before);
1131 DCHECK(before_list != nullptr);
1132 before_list->next = first_list_mir;
1133 last_list_mir->next = insert_before;
1134 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001135 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001136
1137 // Set this BB to be the basic block of the MIRs.
1138 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1139 mir->bb = id;
1140 }
1141}
1142
1143bool BasicBlock::RemoveMIR(MIR* mir) {
1144 // Remove as a single element list.
1145 return RemoveMIRList(mir, mir);
1146}
1147
1148bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1149 if (first_list_mir == nullptr) {
1150 return false;
1151 }
1152
1153 // Try to find the MIR.
1154 MIR* before_list = nullptr;
1155 MIR* after_list = nullptr;
1156
1157 // If we are removing from the beginning of the MIR list.
1158 if (first_mir_insn == first_list_mir) {
1159 before_list = nullptr;
1160 } else {
1161 before_list = FindPreviousMIR(first_list_mir);
1162 if (before_list == nullptr) {
1163 // We did not find the mir.
1164 return false;
1165 }
1166 }
1167
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001168 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001169 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001170 mir->bb = NullBasicBlockId;
1171 }
1172
1173 after_list = last_list_mir->next;
1174
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001175 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001176 if (before_list == nullptr) {
1177 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001178 } else {
1179 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001180 }
1181
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001182 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001183 if (after_list == nullptr) {
1184 last_mir_insn = before_list;
1185 }
1186
1187 return true;
buzbee1fd33462013-03-25 13:40:45 -07001188}
1189
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001190MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001191 MIR* next_mir = nullptr;
1192
1193 if (current != nullptr) {
1194 next_mir = current->next;
1195 }
1196
1197 if (next_mir == nullptr) {
1198 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001199 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1200 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001201 }
1202 }
1203
1204 return next_mir;
1205}
1206
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001207static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1208 DCHECK(decoded_mir != nullptr);
1209 OpSize type = static_cast<OpSize>(type_size >> 16);
1210 uint16_t vect_size = (type_size & 0xFFFF);
1211
1212 // Now print the type and vector size.
1213 std::stringstream ss;
1214 ss << " (type:";
1215 ss << type;
1216 ss << " vectsize:";
1217 ss << vect_size;
1218 ss << ")";
1219
1220 decoded_mir->append(ss.str());
1221}
1222
1223void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1224 DCHECK(decoded_mir != nullptr);
1225 int opcode = mir->dalvikInsn.opcode;
1226 SSARepresentation* ssa_rep = mir->ssa_rep;
1227 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1228 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1229
1230 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1231
1232 switch (opcode) {
1233 case kMirOpPhi: {
1234 if (defs > 0 && uses > 0) {
1235 BasicBlockId* incoming = mir->meta.phi_incoming;
1236 decoded_mir->append(StringPrintf(" %s = (%s",
1237 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1238 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1239 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1240 for (int i = 1; i < uses; i++) {
1241 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1242 }
1243 decoded_mir->append(")");
1244 }
1245 break;
1246 }
1247 case kMirOpCopy:
1248 if (ssa_rep != nullptr) {
1249 decoded_mir->append(" ");
1250 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1251 if (defs > 1) {
1252 decoded_mir->append(", ");
1253 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1254 }
1255 decoded_mir->append(" = ");
1256 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1257 if (uses > 1) {
1258 decoded_mir->append(", ");
1259 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1260 }
1261 } else {
1262 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1263 }
1264 break;
1265 case kMirOpFusedCmplFloat:
1266 case kMirOpFusedCmpgFloat:
1267 case kMirOpFusedCmplDouble:
1268 case kMirOpFusedCmpgDouble:
1269 case kMirOpFusedCmpLong:
1270 if (ssa_rep != nullptr) {
1271 decoded_mir->append(" ");
1272 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1273 for (int i = 1; i < uses; i++) {
1274 decoded_mir->append(", ");
1275 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1276 }
1277 } else {
1278 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1279 }
1280 break;
1281 case kMirOpMoveVector:
1282 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1283 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1284 break;
1285 case kMirOpPackedAddition:
1286 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1287 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1288 break;
1289 case kMirOpPackedMultiply:
1290 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1291 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1292 break;
1293 case kMirOpPackedSubtract:
1294 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1295 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1296 break;
1297 case kMirOpPackedAnd:
1298 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1299 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1300 break;
1301 case kMirOpPackedOr:
1302 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1303 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1304 break;
1305 case kMirOpPackedXor:
1306 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1307 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1308 break;
1309 case kMirOpPackedShiftLeft:
1310 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1311 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1312 break;
1313 case kMirOpPackedUnsignedShiftRight:
1314 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1315 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1316 break;
1317 case kMirOpPackedSignedShiftRight:
1318 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1319 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1320 break;
1321 case kMirOpConstVector:
1322 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1323 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1324 break;
1325 case kMirOpPackedSet:
1326 if (ssa_rep != nullptr) {
1327 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1328 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1329 if (uses > 1) {
1330 decoded_mir->append(", ");
1331 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1332 }
1333 } else {
1334 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1335 }
1336 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1337 break;
1338 case kMirOpPackedAddReduce:
1339 if (ssa_rep != nullptr) {
1340 decoded_mir->append(" ");
1341 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1342 if (defs > 1) {
1343 decoded_mir->append(", ");
1344 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1345 }
1346 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1347 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1348 if (uses > 1) {
1349 decoded_mir->append(", ");
1350 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1351 }
1352 } else {
1353 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1354 }
1355 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1356 break;
1357 case kMirOpPackedReduce:
1358 if (ssa_rep != nullptr) {
1359 decoded_mir->append(" ");
1360 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1361 if (defs > 1) {
1362 decoded_mir->append(", ");
1363 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1364 }
1365 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1366 } else {
1367 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1368 }
1369 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1370 break;
1371 case kMirOpReserveVectorRegisters:
1372 case kMirOpReturnVectorRegisters:
1373 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1374 break;
1375 case kMirOpMemBarrier: {
1376 decoded_mir->append(" type:");
1377 std::stringstream ss;
1378 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1379 decoded_mir->append(ss.str());
1380 break;
1381 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001382 case kMirOpPackedArrayGet:
1383 case kMirOpPackedArrayPut:
1384 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1385 if (ssa_rep != nullptr) {
1386 decoded_mir->append(StringPrintf(", %s[%s]",
1387 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1388 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1389 } else {
1390 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1391 }
1392 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1393 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001394 default:
1395 break;
1396 }
1397}
1398
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001399char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001400 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001401 std::string str;
1402 int flags = 0;
1403 int opcode = insn.opcode;
1404 char* ret;
1405 bool nop = false;
1406 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001407 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001408
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001409 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001410 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1411 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1412 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001413 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001414 insn = mir->meta.throw_insn->dalvikInsn;
1415 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001416 opcode = insn.opcode;
1417 } else if (opcode == kMirOpNop) {
1418 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001419 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1420 // Recover original opcode.
1421 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1422 opcode = insn.opcode;
1423 }
buzbee1fd33462013-03-25 13:40:45 -07001424 nop = true;
1425 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001426 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1427 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001428
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001429 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001430 // Note that this does not check the MIR's opcode in all cases. In cases where it
1431 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1432 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001433 } else {
1434 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001435 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001436 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001437
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001438 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001439 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1440 (dalvik_format == Instruction::k3rc));
1441 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001442 str.append(" ");
1443 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1444 if (defs > 1) {
1445 str.append(", ");
1446 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1447 }
buzbee1fd33462013-03-25 13:40:45 -07001448 if (uses != 0) {
1449 str.append(", ");
1450 }
1451 }
1452 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001453 str.append(" ");
1454 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001455 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1456 // For the listing, skip the high sreg.
1457 i++;
1458 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001459 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001460 str.append(",");
1461 }
1462 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001463
buzbee1fd33462013-03-25 13:40:45 -07001464 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001465 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001466 case Instruction::k21s:
1467 case Instruction::k31i:
1468 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001469 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001470 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001471 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001472 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001473 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001474 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001475 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001476 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001477 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001478 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001479 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001480 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001481 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001482 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001483 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001484 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001485 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001486 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001487 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001488 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001489
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001490 if ((flags & Instruction::kBranch) != 0) {
1491 // For branches, decode the instructions to print out the branch targets.
1492 int offset = 0;
1493 switch (dalvik_format) {
1494 case Instruction::k21t:
1495 offset = insn.vB;
1496 break;
1497 case Instruction::k22t:
1498 offset = insn.vC;
1499 break;
1500 case Instruction::k10t:
1501 case Instruction::k20t:
1502 case Instruction::k30t:
1503 offset = insn.vA;
1504 break;
1505 default:
1506 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001507 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001508 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001509 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001510 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1511 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001512
1513 if (nop) {
1514 str.append("]--optimized away");
1515 }
buzbee1fd33462013-03-25 13:40:45 -07001516 }
1517 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001518 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001519 strncpy(ret, str.c_str(), length);
1520 return ret;
1521}
1522
1523/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001524void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001525 static const struct { const char before; const char after; } match[] = {
1526 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1527 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1528 };
buzbee1fd33462013-03-25 13:40:45 -07001529 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1530 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1531 }
1532}
1533
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001534std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001535 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1536 // the arena. We should be smarter and just place straight into the arena, or compute the
1537 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001538 int vreg = SRegToVReg(ssa_reg);
1539 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1540 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1541 } else {
1542 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1543 }
buzbee1fd33462013-03-25 13:40:45 -07001544}
1545
1546// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001547std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001548 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001549 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001550 return GetSSAName(ssa_reg);
1551 }
1552 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001553 if (!singles_only && reg_location_[ssa_reg].wide &&
1554 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001555 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001556 ConstantValueWide(reg_location_[ssa_reg]));
1557 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001558 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001559 ConstantValue(reg_location_[ssa_reg]));
1560 }
1561 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001562 int vreg = SRegToVReg(ssa_reg);
1563 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1564 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1565 } else {
1566 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1567 }
buzbee1fd33462013-03-25 13:40:45 -07001568 }
1569}
1570
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001571void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001572 switch (bb->block_type) {
1573 case kEntryBlock:
1574 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1575 break;
1576 case kExitBlock:
1577 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1578 break;
1579 case kDalvikByteCode:
1580 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1581 break;
1582 case kExceptionHandling:
1583 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1584 bb->id);
1585 break;
1586 default:
1587 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1588 break;
1589 }
1590}
1591
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001592const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001593 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001594 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1595 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1596}
1597
1598/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001599void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001600 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001601 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001602 "Entry Block",
1603 "Code Block",
1604 "Exit Block",
1605 "Exception Handling",
1606 "Catch Block"
1607 };
1608
1609 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001610 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001611 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001612
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001613 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001614 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1615 bb->id,
1616 block_type_names[bb->block_type],
1617 bb->start_offset,
1618 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1619 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001620 if (bb->taken != NullBasicBlockId) {
1621 LOG(INFO) << " Taken branch: block " << bb->taken
1622 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001623 }
buzbee0d829482013-10-11 15:24:55 -07001624 if (bb->fall_through != NullBasicBlockId) {
1625 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1626 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001627 }
1628 }
1629}
1630
1631/*
1632 * Build an array of location records for the incoming arguments.
1633 * Note: one location record per word of arguments, with dummy
1634 * high-word loc for wide arguments. Also pull up any following
1635 * MOVE_RESULT and incorporate it into the invoke.
1636 */
1637CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001638 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001639 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001640 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001641 MIR* move_result_mir = FindMoveResult(bb, mir);
1642 if (move_result_mir == NULL) {
1643 info->result.location = kLocInvalid;
1644 } else {
1645 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001646 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1647 }
1648 info->num_arg_words = mir->ssa_rep->num_uses;
1649 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001650 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001651 for (int i = 0; i < info->num_arg_words; i++) {
1652 info->args[i] = GetRawSrc(mir, i);
1653 }
1654 info->opt_flags = mir->optimization_flags;
1655 info->type = type;
1656 info->is_range = is_range;
1657 info->index = mir->dalvikInsn.vB;
1658 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001659 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001660 return info;
1661}
1662
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001663// Allocate a new MIR.
1664MIR* MIRGraph::NewMIR() {
1665 MIR* mir = new (arena_) MIR();
1666 return mir;
1667}
1668
buzbee862a7602013-04-05 10:58:54 -07001669// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001670BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001671 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001672
buzbee862a7602013-04-05 10:58:54 -07001673 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001674 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001675 block_id_map_.Put(block_id, block_id);
1676 return bb;
1677}
buzbee1fd33462013-03-25 13:40:45 -07001678
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001679void MIRGraph::InitializeConstantPropagation() {
1680 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001681 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001682}
1683
1684void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001685 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001686 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001687 use_counts_.clear();
1688 use_counts_.reserve(num_ssa_regs + 32);
1689 use_counts_.resize(num_ssa_regs, 0u);
1690 raw_use_counts_.clear();
1691 raw_use_counts_.reserve(num_ssa_regs + 32);
1692 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001693}
1694
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001695void MIRGraph::SSATransformationStart() {
1696 DCHECK(temp_scoped_alloc_.get() == nullptr);
1697 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001698 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001699 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1700 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001701}
1702
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001703void MIRGraph::SSATransformationEnd() {
1704 // Verify the dataflow information after the pass.
1705 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1706 VerifyDataflow();
1707 }
1708
1709 temp_bit_vector_size_ = 0u;
1710 temp_bit_vector_ = nullptr;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001711 temp_bit_matrix_ = nullptr; // Def block matrix.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001712 DCHECK(temp_scoped_alloc_.get() != nullptr);
1713 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001714
1715 // Update the maximum number of reachable blocks.
1716 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001717}
1718
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001719size_t MIRGraph::GetNumDalvikInsns() const {
1720 size_t cumulative_size = 0u;
1721 bool counted_current_item = false;
1722 const uint8_t size_for_null_code_item = 2u;
1723
1724 for (auto it : m_units_) {
1725 const DexFile::CodeItem* code_item = it->GetCodeItem();
1726 // Even if the code item is null, we still count non-zero value so that
1727 // each m_unit is counted as having impact.
1728 cumulative_size += (code_item == nullptr ?
1729 size_for_null_code_item : code_item->insns_size_in_code_units_);
1730 if (code_item == current_code_item_) {
1731 counted_current_item = true;
1732 }
1733 }
1734
1735 // If the current code item was not counted yet, count it now.
1736 // This can happen for example in unit tests where some fields like m_units_
1737 // are not initialized.
1738 if (counted_current_item == false) {
1739 cumulative_size += (current_code_item_ == nullptr ?
1740 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1741 }
1742
1743 return cumulative_size;
1744}
1745
Vladimir Marko55fff042014-07-10 12:42:52 +01001746static BasicBlock* SelectTopologicalSortOrderFallBack(
1747 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1748 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1749 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1750 // No true loop head has been found but there may be true loop heads after the mess we need
1751 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1752 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1753 BasicBlock* fall_back = nullptr;
1754 size_t fall_back_num_reachable = 0u;
1755 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1756 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1757 AllNodesIterator iter(mir_graph);
1758 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1759 if (candidate->hidden || // Hidden, or
1760 candidate->visited || // already processed, or
1761 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1762 (current_loop != nullptr && // outside current loop.
1763 !current_loop->IsBitSet(candidate->id))) {
1764 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001765 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001766 DCHECK(tmp_stack->empty());
1767 tmp_stack->push_back(candidate->id);
1768 candidate_reachable.ClearAllBits();
1769 size_t num_reachable = 0u;
1770 while (!tmp_stack->empty()) {
1771 BasicBlockId current_id = tmp_stack->back();
1772 tmp_stack->pop_back();
1773 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1774 DCHECK(current_bb != nullptr);
1775 ChildBlockIterator child_iter(current_bb, mir_graph);
1776 BasicBlock* child_bb = child_iter.Next();
1777 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1778 DCHECK(!child_bb->hidden);
1779 if (child_bb->visited || // Already processed, or
1780 (current_loop != nullptr && // outside current loop.
1781 !current_loop->IsBitSet(child_bb->id))) {
1782 continue;
1783 }
1784 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1785 candidate_reachable.SetBit(child_bb->id);
1786 tmp_stack->push_back(child_bb->id);
1787 num_reachable += 1u;
1788 }
1789 }
1790 }
1791 if (fall_back_num_reachable < num_reachable) {
1792 fall_back_num_reachable = num_reachable;
1793 fall_back = candidate;
1794 }
1795 }
1796 return fall_back;
1797}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001798
Vladimir Marko55fff042014-07-10 12:42:52 +01001799// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1800static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1801 ArenaBitVector* reachable,
1802 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1803 // NOTE: Loop heads indicated by the "visited" flag.
1804 DCHECK(tmp_stack->empty());
1805 reachable->ClearAllBits();
1806 tmp_stack->push_back(bb_id);
1807 while (!tmp_stack->empty()) {
1808 BasicBlockId current_id = tmp_stack->back();
1809 tmp_stack->pop_back();
1810 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1811 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001812 for (BasicBlockId pred_id : current_bb->predecessors) {
1813 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1814 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001815 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1816 reachable->SetBit(pred_bb->id);
1817 tmp_stack->push_back(pred_bb->id);
1818 }
1819 }
1820 }
1821}
1822
1823void MIRGraph::ComputeTopologicalSortOrder() {
1824 ScopedArenaAllocator allocator(&cu_->arena_stack);
1825 unsigned int num_blocks = GetNumBlocks();
1826
1827 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1828 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1829 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1830 size_t max_nested_loops = 0u;
1831 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1832 loop_exit_blocks.ClearAllBits();
1833
1834 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001835 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001836 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001837 if (bb->hidden == true) {
1838 continue;
1839 }
1840
Vladimir Marko55fff042014-07-10 12:42:52 +01001841 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001842
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001843 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001844 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001845 q.push(bb);
1846 }
1847 }
1848
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001849 // Clear the topological order arrays.
1850 topological_order_.clear();
1851 topological_order_.reserve(num_blocks);
1852 topological_order_loop_ends_.clear();
1853 topological_order_loop_ends_.resize(num_blocks, 0u);
1854 topological_order_indexes_.clear();
1855 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001856
1857 // Mark all blocks as unvisited.
1858 ClearAllVisitedFlags();
1859
1860 // For loop heads, keep track from which blocks they are reachable not going through other
1861 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1862 // in this set go into the loop body, the other children are jumping over the loop.
1863 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1864 loop_head_reachable_from.resize(num_blocks, nullptr);
1865 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1866 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1867
1868 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001869 BasicBlock* bb = nullptr;
1870 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001871 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001872 // Get top.
1873 bb = q.front();
1874 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001875 if (bb->visited) {
1876 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1877 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001878 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1879 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001880 DCHECK_EQ(loop_head_stack.back(), bb->id);
1881 loop_head_stack.pop_back();
1882 ArenaBitVector* reachable =
1883 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1884 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1885 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1886 q.push(GetBasicBlock(candidate_id));
1887 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1888 // so clearing the bit has no effect on the iterator.
1889 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001890 }
1891 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001892 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001893 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001894 } else {
1895 // Find the new loop head.
1896 AllNodesIterator iter(this);
1897 while (true) {
1898 BasicBlock* candidate = iter.Next();
1899 if (candidate == nullptr) {
1900 // We did not find a true loop head, fall back to a reachable block in any loop.
1901 ArenaBitVector* current_loop =
1902 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1903 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1904 &allocator, &tmp_stack);
1905 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1906 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1907 LOG(INFO) << "Topological sort order: Using fall-back in "
1908 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1909 << " @0x" << std::hex << bb->start_offset
1910 << ", num_blocks = " << std::dec << num_blocks;
1911 }
1912 break;
1913 }
1914 if (candidate->hidden || // Hidden, or
1915 candidate->visited || // already processed, or
1916 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1917 (!loop_head_stack.empty() && // outside current loop.
1918 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1919 continue;
1920 }
1921
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001922 for (BasicBlockId pred_id : candidate->predecessors) {
1923 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1924 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001925 if (pred_bb != candidate && !pred_bb->visited &&
1926 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001927 candidate = nullptr; // Set candidate to null to indicate failure.
1928 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001929 }
1930 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001931 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001932 bb = candidate;
1933 break;
1934 }
1935 }
1936 // Compute blocks from which the loop head is reachable and process those blocks first.
1937 ArenaBitVector* reachable =
1938 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1939 loop_head_reachable_from[bb->id] = reachable;
1940 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1941 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1942 loop_head_stack.push_back(bb->id);
1943 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001944 }
1945
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001946 DCHECK_EQ(bb->hidden, false);
1947 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001948 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001949
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001950 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001951 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1952 topological_order_indexes_[bb->id] = idx;
1953 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001954
Vladimir Marko55fff042014-07-10 12:42:52 +01001955 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001956 ChildBlockIterator succIter(bb, this);
1957 BasicBlock* successor = succIter.Next();
1958 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001959 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001960 continue;
1961 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001962
Vladimir Marko55fff042014-07-10 12:42:52 +01001963 // One more predecessor was visited.
1964 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001965 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001966 if (loop_head_stack.empty() ||
1967 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1968 q.push(successor);
1969 } else {
1970 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1971 loop_exit_blocks.SetBit(successor->id);
1972 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001973 }
1974 }
1975 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001976
1977 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001978 topological_order_loop_head_stack_.clear();
1979 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01001980 max_nested_loops_ = max_nested_loops;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001981}
1982
1983bool BasicBlock::IsExceptionBlock() const {
1984 if (block_type == kExceptionHandling) {
1985 return true;
1986 }
1987 return false;
1988}
1989
Wei Jin04f4d8a2014-05-29 18:04:29 -07001990bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1991 BasicBlock* target = GetBasicBlock(target_id);
1992
1993 if (source == nullptr || target == nullptr)
1994 return false;
1995
1996 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001997 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1998 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001999 if (bb == source)
2000 return true; // The block has been inserted by a suspend check before.
2001 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
2002 return true;
2003 }
2004
2005 return false;
2006}
2007
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002008ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2009 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2010 visited_taken_(false), have_successors_(false) {
2011 // Check if we actually do have successors.
2012 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2013 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002014 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002015 }
2016}
2017
2018BasicBlock* ChildBlockIterator::Next() {
2019 // We check if we have a basic block. If we don't we cannot get next child.
2020 if (basic_block_ == nullptr) {
2021 return nullptr;
2022 }
2023
2024 // If we haven't visited fallthrough, return that.
2025 if (visited_fallthrough_ == false) {
2026 visited_fallthrough_ = true;
2027
2028 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2029 if (result != nullptr) {
2030 return result;
2031 }
2032 }
2033
2034 // If we haven't visited taken, return that.
2035 if (visited_taken_ == false) {
2036 visited_taken_ = true;
2037
2038 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2039 if (result != nullptr) {
2040 return result;
2041 }
2042 }
2043
2044 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2045 if (have_successors_ == true) {
2046 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002047 auto end = basic_block_->successor_blocks.cend();
2048 while (successor_iter_ != end) {
2049 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2050 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002051 // If block was replaced by zero block, take next one.
2052 if (successor_block_info->block != NullBasicBlockId) {
2053 return mir_graph_->GetBasicBlock(successor_block_info->block);
2054 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002055 }
2056 }
2057
2058 // We do not have anything.
2059 return nullptr;
2060}
2061
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002062BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2063 MIRGraph* mir_graph = c_unit->mir_graph.get();
2064 return Copy(mir_graph);
2065}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002066
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002067BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2068 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002069
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002070 // We don't do a memcpy style copy here because it would lead to a lot of things
2071 // to clean up. Let us do it by hand instead.
2072 // Copy in taken and fallthrough.
2073 result_bb->fall_through = fall_through;
2074 result_bb->taken = taken;
2075
2076 // Copy successor links if needed.
2077 ArenaAllocator* arena = mir_graph->GetArena();
2078
2079 result_bb->successor_block_list_type = successor_block_list_type;
2080 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002081 result_bb->successor_blocks.reserve(successor_blocks.size());
2082 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2083 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2084 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002085 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002086 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002087 }
2088 }
2089
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002090 // Copy offset, method.
2091 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002092
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002093 // Now copy instructions.
2094 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2095 // Get a copy first.
2096 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002097
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002098 // Append it.
2099 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002100 }
2101
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002102 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002103}
2104
2105MIR* MIR::Copy(MIRGraph* mir_graph) {
2106 MIR* res = mir_graph->NewMIR();
2107 *res = *this;
2108
2109 // Remove links
2110 res->next = nullptr;
2111 res->bb = NullBasicBlockId;
2112 res->ssa_rep = nullptr;
2113
2114 return res;
2115}
2116
2117MIR* MIR::Copy(CompilationUnit* c_unit) {
2118 return Copy(c_unit->mir_graph.get());
2119}
2120
2121uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2122 // Default result.
2123 int res = 0;
2124
2125 // We are basically setting the iputs to their igets counterparts.
2126 switch (opcode) {
2127 case Instruction::IPUT:
2128 case Instruction::IPUT_OBJECT:
2129 case Instruction::IPUT_BOOLEAN:
2130 case Instruction::IPUT_BYTE:
2131 case Instruction::IPUT_CHAR:
2132 case Instruction::IPUT_SHORT:
2133 case Instruction::IPUT_QUICK:
2134 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002135 case Instruction::IPUT_BOOLEAN_QUICK:
2136 case Instruction::IPUT_BYTE_QUICK:
2137 case Instruction::IPUT_CHAR_QUICK:
2138 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002139 case Instruction::APUT:
2140 case Instruction::APUT_OBJECT:
2141 case Instruction::APUT_BOOLEAN:
2142 case Instruction::APUT_BYTE:
2143 case Instruction::APUT_CHAR:
2144 case Instruction::APUT_SHORT:
2145 case Instruction::SPUT:
2146 case Instruction::SPUT_OBJECT:
2147 case Instruction::SPUT_BOOLEAN:
2148 case Instruction::SPUT_BYTE:
2149 case Instruction::SPUT_CHAR:
2150 case Instruction::SPUT_SHORT:
2151 // Skip the VR containing what to store.
2152 res = 1;
2153 break;
2154 case Instruction::IPUT_WIDE:
2155 case Instruction::IPUT_WIDE_QUICK:
2156 case Instruction::APUT_WIDE:
2157 case Instruction::SPUT_WIDE:
2158 // Skip the two VRs containing what to store.
2159 res = 2;
2160 break;
2161 default:
2162 // Do nothing in the general case.
2163 break;
2164 }
2165
2166 return res;
2167}
2168
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002169/**
2170 * @brief Given a decoded instruction, it checks whether the instruction
2171 * sets a constant and if it does, more information is provided about the
2172 * constant being set.
2173 * @param ptr_value pointer to a 64-bit holder for the constant.
2174 * @param wide Updated by function whether a wide constant is being set by bytecode.
2175 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2176 */
2177bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2178 bool sets_const = true;
2179 int64_t value = vB;
2180
2181 DCHECK(ptr_value != nullptr);
2182 DCHECK(wide != nullptr);
2183
2184 switch (opcode) {
2185 case Instruction::CONST_4:
2186 case Instruction::CONST_16:
2187 case Instruction::CONST:
2188 *wide = false;
2189 value <<= 32; // In order to get the sign extend.
2190 value >>= 32;
2191 break;
2192 case Instruction::CONST_HIGH16:
2193 *wide = false;
2194 value <<= 48; // In order to get the sign extend.
2195 value >>= 32;
2196 break;
2197 case Instruction::CONST_WIDE_16:
2198 case Instruction::CONST_WIDE_32:
2199 *wide = true;
2200 value <<= 32; // In order to get the sign extend.
2201 value >>= 32;
2202 break;
2203 case Instruction::CONST_WIDE:
2204 *wide = true;
2205 value = vB_wide;
2206 break;
2207 case Instruction::CONST_WIDE_HIGH16:
2208 *wide = true;
2209 value <<= 48; // In order to get the sign extend.
2210 break;
2211 default:
2212 sets_const = false;
2213 break;
2214 }
2215
2216 if (sets_const) {
2217 *ptr_value = value;
2218 }
2219
2220 return sets_const;
2221}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002222
2223void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2224 // Reset flags for all MIRs in bb.
2225 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2226 mir->optimization_flags &= (~reset_flags);
2227 }
2228}
2229
Vladimir Marko312eb252014-10-07 15:01:57 +01002230void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002231 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2232 block_type = kDalvikByteCode;
2233
2234 // Mark it as hidden.
2235 hidden = true;
2236
2237 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2238 // are updated to know that they no longer have a parent.
2239 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2240 mir->bb = NullBasicBlockId;
2241 }
2242 first_mir_insn = nullptr;
2243 last_mir_insn = nullptr;
2244
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002245 for (BasicBlockId pred_id : predecessors) {
2246 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2247 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002248
2249 // Sadly we have to go through the children by hand here.
2250 pred_bb->ReplaceChild(id, NullBasicBlockId);
2251 }
2252
2253 // Iterate through children of bb we are hiding.
2254 ChildBlockIterator successorChildIter(this, mir_graph);
2255
2256 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002257 // Erase this predecessor from child.
2258 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002259 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002260
2261 // Remove link to children.
2262 taken = NullBasicBlockId;
2263 fall_through = NullBasicBlockId;
2264 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002265}
2266
Vladimir Marko312eb252014-10-07 15:01:57 +01002267/*
2268 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2269 */
2270void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2271 DCHECK(predecessors.empty()); // Unreachable.
2272
2273 // Mark as dead and hidden.
2274 block_type = kDead;
2275 hidden = true;
2276
2277 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2278 // are updated to know that they no longer have a parent.
2279 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2280 mir->bb = NullBasicBlockId;
2281 }
2282 first_mir_insn = nullptr;
2283 last_mir_insn = nullptr;
2284
2285 data_flow_info = nullptr;
2286
2287 // Erase this bb from all children's predecessors and kill unreachable children.
2288 ChildBlockIterator iter(this, mir_graph);
2289 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2290 succ_bb->ErasePredecessor(id);
2291 if (succ_bb->predecessors.empty()) {
2292 succ_bb->KillUnreachable(mir_graph);
2293 }
2294 }
2295
2296 // Remove links to children.
2297 fall_through = NullBasicBlockId;
2298 taken = NullBasicBlockId;
2299 successor_block_list_type = kNotUsed;
2300
2301 if (kIsDebugBuild) {
2302 if (catch_entry) {
2303 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2304 mir_graph->catches_.erase(start_offset);
2305 }
2306 }
2307}
2308
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002309bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2310 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2311 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2312 // then it is not live out of this BB.
2313 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2314
2315 int last_ssa_reg = -1;
2316
2317 // Walk through the MIRs backwards.
2318 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2319 // Get ssa rep.
2320 SSARepresentation *ssa_rep = mir->ssa_rep;
2321
2322 // Go through the defines for this MIR.
2323 for (int i = 0; i < ssa_rep->num_defs; i++) {
2324 DCHECK(ssa_rep->defs != nullptr);
2325
2326 // Get the ssa reg.
2327 int def_ssa_reg = ssa_rep->defs[i];
2328
2329 // Get dalvik reg.
2330 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2331
2332 // Compare dalvik regs.
2333 if (dalvik_reg == def_dalvik_reg) {
2334 // We found a def of the register that we are being asked about.
2335 // Remember it.
2336 last_ssa_reg = def_ssa_reg;
2337 }
2338 }
2339 }
2340
2341 if (last_ssa_reg == -1) {
2342 // If we get to this point we couldn't find a define of register user asked about.
2343 // Let's assume the user knows what he's doing so we can be safe and say that if we
2344 // couldn't find a def, it is live out.
2345 return true;
2346 }
2347
2348 // If it is not -1, we found a match, is it ssa_reg?
2349 return (ssa_reg == last_ssa_reg);
2350}
2351
2352bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2353 // We need to check taken, fall_through, and successor_blocks to replace.
2354 bool found = false;
2355 if (taken == old_bb) {
2356 taken = new_bb;
2357 found = true;
2358 }
2359
2360 if (fall_through == old_bb) {
2361 fall_through = new_bb;
2362 found = true;
2363 }
2364
2365 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002366 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002367 if (successor_block_info->block == old_bb) {
2368 successor_block_info->block = new_bb;
2369 found = true;
2370 }
2371 }
2372 }
2373
2374 return found;
2375}
2376
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002377void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2378 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2379 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002380 // It's faster to move the back() to *pos than erase(pos).
2381 *pos = predecessors.back();
2382 predecessors.pop_back();
2383 size_t idx = std::distance(predecessors.begin(), pos);
2384 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2385 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2386 break;
2387 }
2388 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2389 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2390 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2391 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2392 mir->ssa_rep->num_uses = predecessors.size();
2393 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002394}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002395
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002396void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2397 DCHECK_NE(new_pred, NullBasicBlockId);
2398 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002399 DCHECK(pos != predecessors.end());
2400 *pos = new_pred;
2401 size_t idx = std::distance(predecessors.begin(), pos);
2402 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2403 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2404 break;
2405 }
2406 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2407 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002408 }
2409}
2410
2411// Create a new basic block with block_id as num_blocks_ that is
2412// post-incremented.
2413BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2414 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002415 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002416 return res;
2417}
2418
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002419void MIRGraph::CalculateBasicBlockInformation() {
2420 PassDriverMEPostOpt driver(cu_);
2421 driver.Launch();
2422}
2423
2424void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002425 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002426}
2427
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002428int MIR::DecodedInstruction::FlagsOf() const {
2429 // Calculate new index.
2430 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2431
2432 // Check if it is an extended or not.
2433 if (idx < 0) {
2434 return Instruction::FlagsOf(opcode);
2435 }
2436
2437 // For extended, we use a switch.
2438 switch (static_cast<int>(opcode)) {
2439 case kMirOpPhi:
2440 return Instruction::kContinue;
2441 case kMirOpCopy:
2442 return Instruction::kContinue;
2443 case kMirOpFusedCmplFloat:
2444 return Instruction::kContinue | Instruction::kBranch;
2445 case kMirOpFusedCmpgFloat:
2446 return Instruction::kContinue | Instruction::kBranch;
2447 case kMirOpFusedCmplDouble:
2448 return Instruction::kContinue | Instruction::kBranch;
2449 case kMirOpFusedCmpgDouble:
2450 return Instruction::kContinue | Instruction::kBranch;
2451 case kMirOpFusedCmpLong:
2452 return Instruction::kContinue | Instruction::kBranch;
2453 case kMirOpNop:
2454 return Instruction::kContinue;
2455 case kMirOpNullCheck:
2456 return Instruction::kContinue | Instruction::kThrow;
2457 case kMirOpRangeCheck:
2458 return Instruction::kContinue | Instruction::kThrow;
2459 case kMirOpDivZeroCheck:
2460 return Instruction::kContinue | Instruction::kThrow;
2461 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002462 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002463 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002464 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002465 case kMirOpSelect:
2466 return Instruction::kContinue;
2467 case kMirOpConstVector:
2468 return Instruction::kContinue;
2469 case kMirOpMoveVector:
2470 return Instruction::kContinue;
2471 case kMirOpPackedMultiply:
2472 return Instruction::kContinue;
2473 case kMirOpPackedAddition:
2474 return Instruction::kContinue;
2475 case kMirOpPackedSubtract:
2476 return Instruction::kContinue;
2477 case kMirOpPackedShiftLeft:
2478 return Instruction::kContinue;
2479 case kMirOpPackedSignedShiftRight:
2480 return Instruction::kContinue;
2481 case kMirOpPackedUnsignedShiftRight:
2482 return Instruction::kContinue;
2483 case kMirOpPackedAnd:
2484 return Instruction::kContinue;
2485 case kMirOpPackedOr:
2486 return Instruction::kContinue;
2487 case kMirOpPackedXor:
2488 return Instruction::kContinue;
2489 case kMirOpPackedAddReduce:
2490 return Instruction::kContinue;
2491 case kMirOpPackedReduce:
2492 return Instruction::kContinue;
2493 case kMirOpPackedSet:
2494 return Instruction::kContinue;
2495 case kMirOpReserveVectorRegisters:
2496 return Instruction::kContinue;
2497 case kMirOpReturnVectorRegisters:
2498 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002499 case kMirOpMemBarrier:
2500 return Instruction::kContinue;
2501 case kMirOpPackedArrayGet:
2502 return Instruction::kContinue | Instruction::kThrow;
2503 case kMirOpPackedArrayPut:
2504 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002505 default:
2506 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2507 return 0;
2508 }
2509}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002510} // namespace art