blob: 8dded79aa2be0b32ca9a62b766d2ed0c64a2dc4d [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)),
buzbee311ca162013-02-28 15:56:43 -080097 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000098 temp_scoped_alloc_(),
99 temp_insn_data_(nullptr),
100 temp_bit_vector_size_(0u),
101 temp_bit_vector_(nullptr),
Vladimir Marko5229cf12014-10-09 14:57:59 +0100102 temp_bit_matrix_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100103 temp_gvn_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100104 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800105 try_block_addr_(NULL),
106 entry_block_(NULL),
107 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800108 num_blocks_(0),
109 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100110 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100111 m_units_(arena->Adapter()),
112 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800113 current_method_(kInvalidEntry),
114 current_offset_(kInvalidEntry),
115 def_count_(0),
116 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700117 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100118 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700119 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700120 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
121 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700122 arena_(arena),
123 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800124 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800125 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700126 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
127 requested_backend_temp_(false),
128 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000129 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000130 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100131 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
132 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
133 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
134 gen_suspend_test_list_(arena->Adapter()) {
135 use_counts_.reserve(256);
136 raw_use_counts_.reserve(256);
137 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700138 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700139
140
141 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
142 // X86 requires a temp to keep track of the method address.
143 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
144 // this needs to be updated to reserve 0 temps for BE.
145 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
146 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
147 } else {
148 // Other architectures do not have a known lower bound for non-special temps.
149 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
150 max_available_non_special_compiler_temps_ = 0;
151 reserved_temps_for_backend_ = 0;
152 }
buzbee311ca162013-02-28 15:56:43 -0800153}
154
Ian Rogers6282dc12013-04-18 15:54:02 -0700155MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100156 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700157 STLDeleteElements(&m_units_);
158}
159
buzbee311ca162013-02-28 15:56:43 -0800160/*
161 * Parse an instruction, return the length of the instruction
162 */
Ian Rogers29a26482014-05-02 15:27:29 -0700163int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
164 const Instruction* inst = Instruction::At(code_ptr);
165 decoded_instruction->opcode = inst->Opcode();
166 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
167 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
168 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
169 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
170 if (inst->HasVarArgs()) {
171 inst->GetVarArgs(decoded_instruction->arg);
172 }
173 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800174}
175
176
177/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700178BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700179 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700180 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800181 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400182 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800183 while (insn) {
184 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700185 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800186 insn = insn->next;
187 }
188 if (insn == NULL) {
189 LOG(FATAL) << "Break split failed";
190 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400191 // Now insn is at the instruction where we want to split, namely
192 // insn will be the first instruction of the "bottom" block.
193 // Similarly, prev will be the last instruction of the "top" block
194
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100195 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800196
197 bottom_block->start_offset = code_offset;
198 bottom_block->first_mir_insn = insn;
199 bottom_block->last_mir_insn = orig_block->last_mir_insn;
200
Junmo Park90223cc2014-08-04 18:51:21 +0900201 /* If this block was terminated by a return, conditional branch or throw,
202 * the flag needs to go with the bottom block
203 */
buzbee311ca162013-02-28 15:56:43 -0800204 bottom_block->terminated_by_return = orig_block->terminated_by_return;
205 orig_block->terminated_by_return = false;
206
Junmo Park90223cc2014-08-04 18:51:21 +0900207 bottom_block->conditional_branch = orig_block->conditional_branch;
208 orig_block->conditional_branch = false;
209
210 bottom_block->explicit_throw = orig_block->explicit_throw;
211 orig_block->explicit_throw = false;
212
buzbee311ca162013-02-28 15:56:43 -0800213 /* Handle the taken path */
214 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700215 if (bottom_block->taken != NullBasicBlockId) {
216 orig_block->taken = NullBasicBlockId;
217 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100218 bb_taken->ErasePredecessor(orig_block->id);
219 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800220 }
221
222 /* Handle the fallthrough path */
223 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700224 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100225 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700226 if (bottom_block->fall_through != NullBasicBlockId) {
227 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100228 bb_fall_through->ErasePredecessor(orig_block->id);
229 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800230 }
231
232 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700233 if (orig_block->successor_block_list_type != kNotUsed) {
234 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100235 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700236 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100237 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
238 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700239 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700240 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100241 bb->ErasePredecessor(orig_block->id);
242 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700243 }
buzbee311ca162013-02-28 15:56:43 -0800244 }
245 }
246
buzbee0d829482013-10-11 15:24:55 -0700247 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700248 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800249
buzbee311ca162013-02-28 15:56:43 -0800250 /*
251 * Update the immediate predecessor block pointer so that outgoing edges
252 * can be applied to the proper block.
253 */
254 if (immed_pred_block_p) {
255 DCHECK_EQ(*immed_pred_block_p, orig_block);
256 *immed_pred_block_p = bottom_block;
257 }
buzbeeb48819d2013-09-14 16:15:25 -0700258
259 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000260 DCHECK(insn != nullptr);
261 DCHECK(insn != orig_block->first_mir_insn);
262 DCHECK(insn == bottom_block->first_mir_insn);
263 DCHECK_EQ(insn->offset, bottom_block->start_offset);
264 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700265 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100266 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400267 // Scan the "bottom" instructions, remapping them to the
268 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000269 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400270 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100271 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000272 while (p != bottom_block->last_mir_insn) {
273 p = p->next;
274 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700275 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700276 int opcode = p->dalvikInsn.opcode;
277 /*
278 * Some messiness here to ensure that we only enter real opcodes and only the
279 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000280 * CHECK and work portions. Since the 2nd half of a split operation is always
281 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700282 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700283 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400284 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
285 // At first glance the instructions should all be mapped to orig_block.
286 // However, multiple instructions may correspond to the same dex, hence an earlier
287 // instruction may have already moved the mapping for dex to bottom_block.
288 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100289 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700290 }
buzbeeb48819d2013-09-14 16:15:25 -0700291 }
292
buzbee311ca162013-02-28 15:56:43 -0800293 return bottom_block;
294}
295
296/*
297 * Given a code offset, find out the block that starts with it. If the offset
298 * is in the middle of an existing block, split it into two. If immed_pred_block_p
299 * is not non-null and is the block being split, update *immed_pred_block_p to
300 * point to the bottom block so that outgoing edges can be set up properly
301 * (by the caller)
302 * Utilizes a map for fast lookup of the typical cases.
303 */
buzbee0d829482013-10-11 15:24:55 -0700304BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700305 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700306 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800307 return NULL;
308 }
buzbeeb48819d2013-09-14 16:15:25 -0700309
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100310 int block_id = dex_pc_to_block_map_[code_offset];
311 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700312
313 if ((bb != NULL) && (bb->start_offset == code_offset)) {
314 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700315 return bb;
316 }
buzbee311ca162013-02-28 15:56:43 -0800317
buzbeeb48819d2013-09-14 16:15:25 -0700318 // No direct hit.
319 if (!create) {
320 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800321 }
322
buzbeeb48819d2013-09-14 16:15:25 -0700323 if (bb != NULL) {
324 // The target exists somewhere in an existing block.
325 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
326 }
327
328 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100329 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800330 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100331 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800332 return bb;
333}
334
buzbeeb48819d2013-09-14 16:15:25 -0700335
buzbee311ca162013-02-28 15:56:43 -0800336/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700337void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800338 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700339 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800340
341 if (tries_size == 0) {
342 return;
343 }
344
345 for (int i = 0; i < tries_size; i++) {
346 const DexFile::TryItem* pTry =
347 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700348 DexOffset start_offset = pTry->start_addr_;
349 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800350 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700351 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800352 }
353 }
354
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700355 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700356 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800357 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
358 for (uint32_t idx = 0; idx < handlers_size; idx++) {
359 CatchHandlerIterator iterator(handlers_ptr);
360 for (; iterator.HasNext(); iterator.Next()) {
361 uint32_t address = iterator.GetHandlerAddress();
362 FindBlock(address, false /* split */, true /*create*/,
363 /* immed_pred_block_p */ NULL);
364 }
365 handlers_ptr = iterator.EndDataPointer();
366 }
367}
368
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100369bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
370 NarrowDexOffset catch_offset) {
371 // Catches for monitor-exit during stack unwinding have the pattern
372 // move-exception (move)* (goto)? monitor-exit throw
373 // In the currently generated dex bytecode we see these catching a bytecode range including
374 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
375 // it's the case for a given monitor-exit and catch block so that we can ignore it.
376 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
377 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
378 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700379 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100380 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
381 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700382 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100383 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
384 if (check_insn->VRegA_11x() == monitor_reg) {
385 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
386 return false;
387 }
388 check_insn = check_insn->Next();
389 while (true) {
390 int dest = -1;
391 bool wide = false;
392 switch (check_insn->Opcode()) {
393 case Instruction::MOVE_WIDE:
394 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700395 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100396 case Instruction::MOVE_OBJECT:
397 case Instruction::MOVE:
398 dest = check_insn->VRegA_12x();
399 break;
400
401 case Instruction::MOVE_WIDE_FROM16:
402 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700403 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100404 case Instruction::MOVE_OBJECT_FROM16:
405 case Instruction::MOVE_FROM16:
406 dest = check_insn->VRegA_22x();
407 break;
408
409 case Instruction::MOVE_WIDE_16:
410 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700411 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100412 case Instruction::MOVE_OBJECT_16:
413 case Instruction::MOVE_16:
414 dest = check_insn->VRegA_32x();
415 break;
416
417 case Instruction::GOTO:
418 case Instruction::GOTO_16:
419 case Instruction::GOTO_32:
420 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700421 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100422 default:
423 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
424 check_insn->VRegA_11x() == monitor_reg;
425 }
426
427 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
428 return false;
429 }
430
431 check_insn = check_insn->Next();
432 }
433}
434
buzbee311ca162013-02-28 15:56:43 -0800435/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700436BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
437 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700438 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700439 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800440 switch (insn->dalvikInsn.opcode) {
441 case Instruction::GOTO:
442 case Instruction::GOTO_16:
443 case Instruction::GOTO_32:
444 target += insn->dalvikInsn.vA;
445 break;
446 case Instruction::IF_EQ:
447 case Instruction::IF_NE:
448 case Instruction::IF_LT:
449 case Instruction::IF_GE:
450 case Instruction::IF_GT:
451 case Instruction::IF_LE:
452 cur_block->conditional_branch = true;
453 target += insn->dalvikInsn.vC;
454 break;
455 case Instruction::IF_EQZ:
456 case Instruction::IF_NEZ:
457 case Instruction::IF_LTZ:
458 case Instruction::IF_GEZ:
459 case Instruction::IF_GTZ:
460 case Instruction::IF_LEZ:
461 cur_block->conditional_branch = true;
462 target += insn->dalvikInsn.vB;
463 break;
464 default:
465 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
466 }
buzbeeb48819d2013-09-14 16:15:25 -0700467 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700468 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800469 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700470 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100471 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800472
473 /* Always terminate the current block for conditional branches */
474 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700475 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800476 /*
477 * If the method is processed
478 * in sequential order from the
479 * beginning, we don't need to
480 * specify split for continue
481 * blocks. However, this
482 * routine can be called by
483 * compileLoop, which starts
484 * parsing the method from an
485 * arbitrary address in the
486 * method body.
487 */
488 true,
489 /* create */
490 true,
491 /* immed_pred_block_p */
492 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700493 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100494 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800495 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700496 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800497 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800498 }
499 return cur_block;
500}
501
502/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800503BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
504 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800505 const uint16_t* switch_data =
506 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
507 int size;
508 const int* keyTable;
509 const int* target_table;
510 int i;
511 int first_key;
512
513 /*
514 * Packed switch data format:
515 * ushort ident = 0x0100 magic value
516 * ushort size number of entries in the table
517 * int first_key first (and lowest) switch case value
518 * int targets[size] branch targets, relative to switch opcode
519 *
520 * Total size is (4+size*2) 16-bit code units.
521 */
522 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
523 DCHECK_EQ(static_cast<int>(switch_data[0]),
524 static_cast<int>(Instruction::kPackedSwitchSignature));
525 size = switch_data[1];
526 first_key = switch_data[2] | (switch_data[3] << 16);
527 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700528 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800529 /*
530 * Sparse switch data format:
531 * ushort ident = 0x0200 magic value
532 * ushort size number of entries in the table; > 0
533 * int keys[size] keys, sorted low-to-high; 32-bit aligned
534 * int targets[size] branch targets, relative to switch opcode
535 *
536 * Total size is (2+size*4) 16-bit code units.
537 */
538 } else {
539 DCHECK_EQ(static_cast<int>(switch_data[0]),
540 static_cast<int>(Instruction::kSparseSwitchSignature));
541 size = switch_data[1];
542 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
543 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700544 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800545 }
546
buzbee0d829482013-10-11 15:24:55 -0700547 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800548 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700549 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800550 }
buzbee0d829482013-10-11 15:24:55 -0700551 cur_block->successor_block_list_type =
552 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100553 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800554
555 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700556 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800557 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700558 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700559 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000560 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700561 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800562 successor_block_info->key =
563 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
564 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100565 cur_block->successor_blocks.push_back(successor_block_info);
566 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800567 }
568
569 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700570 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
571 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700572 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100573 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800574 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800575}
576
577/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700578BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
579 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700580 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700581 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800582 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800583
584 /* In try block */
585 if (in_try_block) {
586 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
587
buzbee0d829482013-10-11 15:24:55 -0700588 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800589 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
590 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700591 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800592 }
593
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700594 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700595 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800596 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100597 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
598 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
599 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
600 continue;
601 }
602 if (cur_block->successor_block_list_type == kNotUsed) {
603 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100604 }
buzbee311ca162013-02-28 15:56:43 -0800605 catch_block->catch_entry = true;
606 if (kIsDebugBuild) {
607 catches_.insert(catch_block->start_offset);
608 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700609 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000610 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700611 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800612 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100613 cur_block->successor_blocks.push_back(successor_block_info);
614 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800615 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100616 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
617 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100618 bool build_all_edges =
619 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100620 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100621 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700622 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800623 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100624 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800625 }
626
buzbee17189ac2013-11-08 11:07:02 -0800627 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800628 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700629 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700630 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800631 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
632 /* immed_pred_block_p */ NULL);
633 }
634 if (!in_try_block) {
635 // Don't split a THROW that can't rethrow - we're done.
636 return cur_block;
637 }
638 }
639
buzbee17189ac2013-11-08 11:07:02 -0800640 if (!build_all_edges) {
641 /*
642 * Even though there is an exception edge here, control cannot return to this
643 * method. Thus, for the purposes of dataflow analysis and optimization, we can
644 * ignore the edge. Doing this reduces compile time, and increases the scope
645 * of the basic-block level optimization pass.
646 */
647 return cur_block;
648 }
649
buzbee311ca162013-02-28 15:56:43 -0800650 /*
651 * Split the potentially-throwing instruction into two parts.
652 * The first half will be a pseudo-op that captures the exception
653 * edges and terminates the basic block. It always falls through.
654 * Then, create a new basic block that begins with the throwing instruction
655 * (minus exceptions). Note: this new basic block must NOT be entered into
656 * the block_map. If the potentially-throwing instruction is the target of a
657 * future branch, we need to find the check psuedo half. The new
658 * basic block containing the work portion of the instruction should
659 * only be entered via fallthrough from the block containing the
660 * pseudo exception edge MIR. Note also that this new block is
661 * not automatically terminated after the work portion, and may
662 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700663 *
664 * Note also that the dex_pc_to_block_map_ entry for the potentially
665 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800666 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100667 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800668 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700669 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100670 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700671 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800672 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700673 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700674 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800675 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700676 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800677 return new_block;
678}
679
680/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
681void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700682 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700683 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800684 current_code_item_ = code_item;
685 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
686 current_method_ = m_units_.size();
687 current_offset_ = 0;
688 // TODO: will need to snapshot stack image and use that as the mir context identification.
689 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000690 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
691 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800692 const uint16_t* code_ptr = current_code_item_->insns_;
693 const uint16_t* code_end =
694 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
695
696 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700697 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100698 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
699 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 -0700700
buzbee311ca162013-02-28 15:56:43 -0800701 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700702 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
703 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800704
705 // If this is the first method, set up default entry and exit blocks.
706 if (current_method_ == 0) {
707 DCHECK(entry_block_ == NULL);
708 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700709 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700710 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100711 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700712 DCHECK_EQ(null_block->id, NullBasicBlockId);
713 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100714 entry_block_ = CreateNewBB(kEntryBlock);
715 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800716 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
717 cu_->dex_file = &dex_file;
718 cu_->class_def_idx = class_def_idx;
719 cu_->method_idx = method_idx;
720 cu_->access_flags = access_flags;
721 cu_->invoke_type = invoke_type;
722 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800723 } else {
724 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
725 /*
726 * Will need to manage storage for ins & outs, push prevous state and update
727 * insert point.
728 */
729 }
730
731 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100732 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700733 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800734 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700735 // TODO: for inlining support, insert at the insert point rather than entry block.
736 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100737 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800738
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000739 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800740 ProcessTryCatchBlocks();
741
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000742 uint64_t merged_df_flags = 0u;
743
buzbee311ca162013-02-28 15:56:43 -0800744 /* Parse all instructions and put them into containing basic blocks */
745 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700746 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800747 insn->offset = current_offset_;
748 insn->m_unit_index = current_method_;
749 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800750 Instruction::Code opcode = insn->dalvikInsn.opcode;
751 if (opcode_count_ != NULL) {
752 opcode_count_[static_cast<int>(opcode)]++;
753 }
754
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700755 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800756 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800757
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700758 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000759 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800760
761 if (df_flags & DF_HAS_DEFS) {
762 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
763 }
764
buzbee1da1e2f2013-11-15 13:37:01 -0800765 if (df_flags & DF_LVN) {
766 cur_block->use_lvn = true; // Run local value numbering on this basic block.
767 }
768
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700769 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700770 if (opcode == Instruction::NOP) {
771 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
772 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
773 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
774 uint16_t following_raw_instruction = code_ptr[1];
775 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
776 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
777 (following_raw_instruction == Instruction::kArrayDataSignature)) {
778 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
779 }
780 }
781 if (width == 1) {
782 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700783 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700784 } else {
buzbee0d829482013-10-11 15:24:55 -0700785 DCHECK(cur_block->fall_through == NullBasicBlockId);
786 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700787 // Unreachable instruction, mark for no continuation.
788 flags &= ~Instruction::kContinue;
789 }
790 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700791 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700792 }
793
buzbeeb48819d2013-09-14 16:15:25 -0700794 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100795 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700796
buzbee27247762013-07-28 12:03:58 -0700797 code_ptr += width;
798
buzbee311ca162013-02-28 15:56:43 -0800799 if (flags & Instruction::kBranch) {
800 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
801 width, flags, code_ptr, code_end);
802 } else if (flags & Instruction::kReturn) {
803 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700804 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100805 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800806 /*
807 * Terminate the current block if there are instructions
808 * afterwards.
809 */
810 if (code_ptr < code_end) {
811 /*
812 * Create a fallthrough block for real instructions
813 * (incl. NOP).
814 */
buzbee27247762013-07-28 12:03:58 -0700815 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
816 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800817 }
818 } else if (flags & Instruction::kThrow) {
819 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
820 code_ptr, code_end);
821 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800822 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800823 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700824 if (verify_flags & Instruction::kVerifyVarArgRange ||
825 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800826 /*
827 * The Quick backend's runtime model includes a gap between a method's
828 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
829 * which spans the gap is somewhat complicated, and should not happen
830 * in normal usage of dx. Punt to the interpreter.
831 */
832 int first_reg_in_range = insn->dalvikInsn.vC;
833 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
834 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
835 punt_to_interpreter_ = true;
836 }
837 }
buzbee311ca162013-02-28 15:56:43 -0800838 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700839 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800840 false, /* immed_pred_block_p */ NULL);
841 if (next_block) {
842 /*
843 * The next instruction could be the target of a previously parsed
844 * forward branch so a block is already created. If the current
845 * instruction is not an unconditional branch, connect them through
846 * the fall-through link.
847 */
buzbee0d829482013-10-11 15:24:55 -0700848 DCHECK(cur_block->fall_through == NullBasicBlockId ||
849 GetBasicBlock(cur_block->fall_through) == next_block ||
850 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800851
buzbee0d829482013-10-11 15:24:55 -0700852 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
853 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100854 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800855 }
856 cur_block = next_block;
857 }
858 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000859 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000860
buzbee311ca162013-02-28 15:56:43 -0800861 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
862 DumpCFG("/sdcard/1_post_parse_cfg/", true);
863 }
864
865 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700866 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800867 }
868}
869
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700870void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800871 DCHECK(opcode_count_ != NULL);
872 LOG(INFO) << "Opcode Count";
873 for (int i = 0; i < kNumPackedOpcodes; i++) {
874 if (opcode_count_[i] != 0) {
875 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
876 << " " << opcode_count_[i];
877 }
878 }
879}
880
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700881uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
882 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
883 return oat_data_flow_attributes_[opcode];
884}
885
886uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
887 DCHECK(mir != nullptr);
888 Instruction::Code opcode = mir->dalvikInsn.opcode;
889 return GetDataFlowAttributes(opcode);
890}
891
buzbee311ca162013-02-28 15:56:43 -0800892// TODO: use a configurable base prefix, and adjust callers to supply pass name.
893/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800894void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800895 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700896 static AtomicInteger cnt(0);
897
898 // Increment counter to get a unique file number.
899 cnt++;
900
buzbee311ca162013-02-28 15:56:43 -0800901 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
902 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700903 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800904 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700905 suffix == nullptr ? "" : suffix,
906 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800907 file = fopen(fname.c_str(), "w");
908 if (file == NULL) {
909 return;
910 }
911 fprintf(file, "digraph G {\n");
912
913 fprintf(file, " rankdir=TB\n");
914
915 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
916 int idx;
917
918 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100919 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700920 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700921 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800922 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700923 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800924 if (bb->block_type == kEntryBlock) {
925 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
926 } else if (bb->block_type == kExitBlock) {
927 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
928 } else if (bb->block_type == kDalvikByteCode) {
929 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
930 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700931 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800932 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
933 bb->first_mir_insn ? " | " : " ");
934 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
935 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700936 fprintf(file, " {%04x %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400937 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700938 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
939 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400940 extended_mir_op_names_[opcode - kMirOpFirst],
941 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
942 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700943 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700944 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700945 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
946 (mir->optimization_flags & MIR_IGNORE_CLINIT_CHECK) != 0 ? " no_clinit" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400947 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800948 }
949 fprintf(file, " }\"];\n\n");
950 } else if (bb->block_type == kExceptionHandling) {
951 char block_name[BLOCK_NAME_LEN];
952
953 GetBlockName(bb, block_name);
954 fprintf(file, " %s [shape=invhouse];\n", block_name);
955 }
956
957 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
958
buzbee0d829482013-10-11 15:24:55 -0700959 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800960 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700961 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800962 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
963 block_name1, block_name2);
964 }
buzbee0d829482013-10-11 15:24:55 -0700965 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800966 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700967 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800968 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
969 }
970
buzbee0d829482013-10-11 15:24:55 -0700971 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800972 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
973 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700974 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800975
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100976 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800977 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100978 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700979 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800980 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100981 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800982 successor_block_info->key,
983 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100984 (succ_id != last_succ_id) ? " | " : " ");
985 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800986 }
987 fprintf(file, " }\"];\n\n");
988
989 GetBlockName(bb, block_name1);
990 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
991 block_name1, bb->start_offset, bb->id);
992
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700993 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700994 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100995 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700996 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800997
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700998 GetBlockName(dest_block, block_name2);
999 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1000 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001001 }
1002 }
1003 fprintf(file, "\n");
1004
1005 if (cu_->verbose) {
1006 /* Display the dominator tree */
1007 GetBlockName(bb, block_name1);
1008 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1009 block_name1, block_name1);
1010 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001011 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001012 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1013 }
1014 }
1015 }
1016 fprintf(file, "}\n");
1017 fclose(file);
1018}
1019
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001020/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001021void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001022 // Insert it after the last MIR.
1023 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001024}
1025
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001026void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1027 // Insert it after the last MIR.
1028 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1029}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001030
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001031void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1032 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1033 MIR* new_mir = *it;
1034
1035 // Add a copy of each MIR.
1036 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1037 }
buzbee1fd33462013-03-25 13:40:45 -07001038}
1039
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001040/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001041void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001042 InsertMIRListAfter(current_mir, new_mir, new_mir);
1043}
buzbee1fd33462013-03-25 13:40:45 -07001044
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001045void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1046 // If no MIR, we are done.
1047 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1048 return;
buzbee1fd33462013-03-25 13:40:45 -07001049 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001050
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001051 // If insert_after is null, assume BB is empty.
1052 if (insert_after == nullptr) {
1053 first_mir_insn = first_list_mir;
1054 last_mir_insn = last_list_mir;
1055 last_list_mir->next = nullptr;
1056 } else {
1057 MIR* after_list = insert_after->next;
1058 insert_after->next = first_list_mir;
1059 last_list_mir->next = after_list;
1060 if (after_list == nullptr) {
1061 last_mir_insn = last_list_mir;
1062 }
1063 }
1064
1065 // Set this BB to be the basic block of the MIRs.
1066 MIR* last = last_list_mir->next;
1067 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1068 mir->bb = id;
1069 }
1070}
1071
1072/* Insert an MIR instruction to the head of a basic block. */
1073void BasicBlock::PrependMIR(MIR* mir) {
1074 InsertMIRListBefore(first_mir_insn, mir, mir);
1075}
1076
1077void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1078 // Insert it before the first MIR.
1079 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1080}
1081
1082void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1083 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1084 MIR* mir = *it;
1085
1086 InsertMIRListBefore(first_mir_insn, mir, mir);
1087 }
1088}
1089
1090/* Insert a MIR instruction before the specified MIR. */
1091void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1092 // Insert as a single element list.
1093 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001094}
1095
1096MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1097 MIR* current = first_mir_insn;
1098
1099 while (current != nullptr) {
1100 MIR* next = current->next;
1101
1102 if (next == mir) {
1103 return current;
1104 }
1105
1106 current = next;
1107 }
1108
1109 return nullptr;
1110}
1111
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001112void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1113 // If no MIR, we are done.
1114 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1115 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001116 }
1117
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001118 // If insert_before is null, assume BB is empty.
1119 if (insert_before == nullptr) {
1120 first_mir_insn = first_list_mir;
1121 last_mir_insn = last_list_mir;
1122 last_list_mir->next = nullptr;
1123 } else {
1124 if (first_mir_insn == insert_before) {
1125 last_list_mir->next = first_mir_insn;
1126 first_mir_insn = first_list_mir;
1127 } else {
1128 // Find the preceding MIR.
1129 MIR* before_list = FindPreviousMIR(insert_before);
1130 DCHECK(before_list != nullptr);
1131 before_list->next = first_list_mir;
1132 last_list_mir->next = insert_before;
1133 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001134 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001135
1136 // Set this BB to be the basic block of the MIRs.
1137 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1138 mir->bb = id;
1139 }
1140}
1141
1142bool BasicBlock::RemoveMIR(MIR* mir) {
1143 // Remove as a single element list.
1144 return RemoveMIRList(mir, mir);
1145}
1146
1147bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1148 if (first_list_mir == nullptr) {
1149 return false;
1150 }
1151
1152 // Try to find the MIR.
1153 MIR* before_list = nullptr;
1154 MIR* after_list = nullptr;
1155
1156 // If we are removing from the beginning of the MIR list.
1157 if (first_mir_insn == first_list_mir) {
1158 before_list = nullptr;
1159 } else {
1160 before_list = FindPreviousMIR(first_list_mir);
1161 if (before_list == nullptr) {
1162 // We did not find the mir.
1163 return false;
1164 }
1165 }
1166
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001167 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001168 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001169 mir->bb = NullBasicBlockId;
1170 }
1171
1172 after_list = last_list_mir->next;
1173
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001174 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001175 if (before_list == nullptr) {
1176 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001177 } else {
1178 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001179 }
1180
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001181 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001182 if (after_list == nullptr) {
1183 last_mir_insn = before_list;
1184 }
1185
1186 return true;
buzbee1fd33462013-03-25 13:40:45 -07001187}
1188
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001189MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001190 MIR* next_mir = nullptr;
1191
1192 if (current != nullptr) {
1193 next_mir = current->next;
1194 }
1195
1196 if (next_mir == nullptr) {
1197 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001198 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1199 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001200 }
1201 }
1202
1203 return next_mir;
1204}
1205
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001206static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1207 DCHECK(decoded_mir != nullptr);
1208 OpSize type = static_cast<OpSize>(type_size >> 16);
1209 uint16_t vect_size = (type_size & 0xFFFF);
1210
1211 // Now print the type and vector size.
1212 std::stringstream ss;
1213 ss << " (type:";
1214 ss << type;
1215 ss << " vectsize:";
1216 ss << vect_size;
1217 ss << ")";
1218
1219 decoded_mir->append(ss.str());
1220}
1221
1222void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1223 DCHECK(decoded_mir != nullptr);
1224 int opcode = mir->dalvikInsn.opcode;
1225 SSARepresentation* ssa_rep = mir->ssa_rep;
1226 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1227 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1228
1229 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1230
1231 switch (opcode) {
1232 case kMirOpPhi: {
1233 if (defs > 0 && uses > 0) {
1234 BasicBlockId* incoming = mir->meta.phi_incoming;
1235 decoded_mir->append(StringPrintf(" %s = (%s",
1236 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1237 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1238 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1239 for (int i = 1; i < uses; i++) {
1240 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1241 }
1242 decoded_mir->append(")");
1243 }
1244 break;
1245 }
1246 case kMirOpCopy:
1247 if (ssa_rep != nullptr) {
1248 decoded_mir->append(" ");
1249 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1250 if (defs > 1) {
1251 decoded_mir->append(", ");
1252 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1253 }
1254 decoded_mir->append(" = ");
1255 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1256 if (uses > 1) {
1257 decoded_mir->append(", ");
1258 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1259 }
1260 } else {
1261 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1262 }
1263 break;
1264 case kMirOpFusedCmplFloat:
1265 case kMirOpFusedCmpgFloat:
1266 case kMirOpFusedCmplDouble:
1267 case kMirOpFusedCmpgDouble:
1268 case kMirOpFusedCmpLong:
1269 if (ssa_rep != nullptr) {
1270 decoded_mir->append(" ");
1271 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1272 for (int i = 1; i < uses; i++) {
1273 decoded_mir->append(", ");
1274 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1275 }
1276 } else {
1277 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1278 }
1279 break;
1280 case kMirOpMoveVector:
1281 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1282 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1283 break;
1284 case kMirOpPackedAddition:
1285 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1286 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1287 break;
1288 case kMirOpPackedMultiply:
1289 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1290 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1291 break;
1292 case kMirOpPackedSubtract:
1293 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1294 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1295 break;
1296 case kMirOpPackedAnd:
1297 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1298 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1299 break;
1300 case kMirOpPackedOr:
1301 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1302 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1303 break;
1304 case kMirOpPackedXor:
1305 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1306 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1307 break;
1308 case kMirOpPackedShiftLeft:
1309 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1310 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1311 break;
1312 case kMirOpPackedUnsignedShiftRight:
1313 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1314 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1315 break;
1316 case kMirOpPackedSignedShiftRight:
1317 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1318 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1319 break;
1320 case kMirOpConstVector:
1321 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1322 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1323 break;
1324 case kMirOpPackedSet:
1325 if (ssa_rep != nullptr) {
1326 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1327 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1328 if (uses > 1) {
1329 decoded_mir->append(", ");
1330 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1331 }
1332 } else {
1333 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1334 }
1335 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1336 break;
1337 case kMirOpPackedAddReduce:
1338 if (ssa_rep != nullptr) {
1339 decoded_mir->append(" ");
1340 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1341 if (defs > 1) {
1342 decoded_mir->append(", ");
1343 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1344 }
1345 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1346 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1347 if (uses > 1) {
1348 decoded_mir->append(", ");
1349 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1350 }
1351 } else {
1352 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1353 }
1354 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1355 break;
1356 case kMirOpPackedReduce:
1357 if (ssa_rep != nullptr) {
1358 decoded_mir->append(" ");
1359 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1360 if (defs > 1) {
1361 decoded_mir->append(", ");
1362 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1363 }
1364 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1365 } else {
1366 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1367 }
1368 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1369 break;
1370 case kMirOpReserveVectorRegisters:
1371 case kMirOpReturnVectorRegisters:
1372 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1373 break;
1374 case kMirOpMemBarrier: {
1375 decoded_mir->append(" type:");
1376 std::stringstream ss;
1377 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1378 decoded_mir->append(ss.str());
1379 break;
1380 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001381 case kMirOpPackedArrayGet:
1382 case kMirOpPackedArrayPut:
1383 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1384 if (ssa_rep != nullptr) {
1385 decoded_mir->append(StringPrintf(", %s[%s]",
1386 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1387 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1388 } else {
1389 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1390 }
1391 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1392 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001393 default:
1394 break;
1395 }
1396}
1397
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001398char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001399 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001400 std::string str;
1401 int flags = 0;
1402 int opcode = insn.opcode;
1403 char* ret;
1404 bool nop = false;
1405 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001406 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001407
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001408 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001409 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1410 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1411 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001412 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001413 insn = mir->meta.throw_insn->dalvikInsn;
1414 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001415 opcode = insn.opcode;
1416 } else if (opcode == kMirOpNop) {
1417 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001418 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1419 // Recover original opcode.
1420 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1421 opcode = insn.opcode;
1422 }
buzbee1fd33462013-03-25 13:40:45 -07001423 nop = true;
1424 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001425 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1426 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001427
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001428 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001429 // Note that this does not check the MIR's opcode in all cases. In cases where it
1430 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1431 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001432 } else {
1433 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001434 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001435 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001436
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001437 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001438 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1439 (dalvik_format == Instruction::k3rc));
1440 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001441 str.append(" ");
1442 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1443 if (defs > 1) {
1444 str.append(", ");
1445 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1446 }
buzbee1fd33462013-03-25 13:40:45 -07001447 if (uses != 0) {
1448 str.append(", ");
1449 }
1450 }
1451 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001452 str.append(" ");
1453 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001454 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1455 // For the listing, skip the high sreg.
1456 i++;
1457 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001458 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001459 str.append(",");
1460 }
1461 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001462
buzbee1fd33462013-03-25 13:40:45 -07001463 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001464 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001465 case Instruction::k21s:
1466 case Instruction::k31i:
1467 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001468 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001469 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001470 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001471 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001472 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001473 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001474 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001475 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001476 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001477 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001478 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001479 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001480 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001481 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001482 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001483 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001484 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001485 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001486 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001487 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001488
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001489 if ((flags & Instruction::kBranch) != 0) {
1490 // For branches, decode the instructions to print out the branch targets.
1491 int offset = 0;
1492 switch (dalvik_format) {
1493 case Instruction::k21t:
1494 offset = insn.vB;
1495 break;
1496 case Instruction::k22t:
1497 offset = insn.vC;
1498 break;
1499 case Instruction::k10t:
1500 case Instruction::k20t:
1501 case Instruction::k30t:
1502 offset = insn.vA;
1503 break;
1504 default:
1505 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001506 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001507 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001508 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001509 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1510 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001511
1512 if (nop) {
1513 str.append("]--optimized away");
1514 }
buzbee1fd33462013-03-25 13:40:45 -07001515 }
1516 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001517 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001518 strncpy(ret, str.c_str(), length);
1519 return ret;
1520}
1521
1522/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001523void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001524 static const struct { const char before; const char after; } match[] = {
1525 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1526 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1527 };
buzbee1fd33462013-03-25 13:40:45 -07001528 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1529 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1530 }
1531}
1532
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001533std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001534 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1535 // the arena. We should be smarter and just place straight into the arena, or compute the
1536 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001537 int vreg = SRegToVReg(ssa_reg);
1538 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1539 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1540 } else {
1541 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1542 }
buzbee1fd33462013-03-25 13:40:45 -07001543}
1544
1545// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001546std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001547 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001548 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001549 return GetSSAName(ssa_reg);
1550 }
1551 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001552 if (!singles_only && reg_location_[ssa_reg].wide &&
1553 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001554 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001555 ConstantValueWide(reg_location_[ssa_reg]));
1556 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001557 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001558 ConstantValue(reg_location_[ssa_reg]));
1559 }
1560 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001561 int vreg = SRegToVReg(ssa_reg);
1562 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1563 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1564 } else {
1565 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1566 }
buzbee1fd33462013-03-25 13:40:45 -07001567 }
1568}
1569
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001570void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001571 switch (bb->block_type) {
1572 case kEntryBlock:
1573 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1574 break;
1575 case kExitBlock:
1576 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1577 break;
1578 case kDalvikByteCode:
1579 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1580 break;
1581 case kExceptionHandling:
1582 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1583 bb->id);
1584 break;
1585 default:
1586 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1587 break;
1588 }
1589}
1590
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001591const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001592 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001593 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1594 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1595}
1596
1597/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001598void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001599 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001600 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001601 "Entry Block",
1602 "Code Block",
1603 "Exit Block",
1604 "Exception Handling",
1605 "Catch Block"
1606 };
1607
1608 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001609 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001610 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001611
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001612 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001613 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1614 bb->id,
1615 block_type_names[bb->block_type],
1616 bb->start_offset,
1617 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1618 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001619 if (bb->taken != NullBasicBlockId) {
1620 LOG(INFO) << " Taken branch: block " << bb->taken
1621 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001622 }
buzbee0d829482013-10-11 15:24:55 -07001623 if (bb->fall_through != NullBasicBlockId) {
1624 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1625 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001626 }
1627 }
1628}
1629
1630/*
1631 * Build an array of location records for the incoming arguments.
1632 * Note: one location record per word of arguments, with dummy
1633 * high-word loc for wide arguments. Also pull up any following
1634 * MOVE_RESULT and incorporate it into the invoke.
1635 */
1636CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001637 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001638 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001639 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001640 MIR* move_result_mir = FindMoveResult(bb, mir);
1641 if (move_result_mir == NULL) {
1642 info->result.location = kLocInvalid;
1643 } else {
1644 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001645 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1646 }
1647 info->num_arg_words = mir->ssa_rep->num_uses;
1648 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001649 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001650 for (int i = 0; i < info->num_arg_words; i++) {
1651 info->args[i] = GetRawSrc(mir, i);
1652 }
1653 info->opt_flags = mir->optimization_flags;
1654 info->type = type;
1655 info->is_range = is_range;
1656 info->index = mir->dalvikInsn.vB;
1657 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001658 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001659 return info;
1660}
1661
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001662// Allocate a new MIR.
1663MIR* MIRGraph::NewMIR() {
1664 MIR* mir = new (arena_) MIR();
1665 return mir;
1666}
1667
buzbee862a7602013-04-05 10:58:54 -07001668// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001669BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001670 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001671
buzbee862a7602013-04-05 10:58:54 -07001672 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001673 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001674 block_id_map_.Put(block_id, block_id);
1675 return bb;
1676}
buzbee1fd33462013-03-25 13:40:45 -07001677
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001678void MIRGraph::InitializeConstantPropagation() {
1679 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001680 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001681}
1682
1683void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001684 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001685 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001686 use_counts_.clear();
1687 use_counts_.reserve(num_ssa_regs + 32);
1688 use_counts_.resize(num_ssa_regs, 0u);
1689 raw_use_counts_.clear();
1690 raw_use_counts_.reserve(num_ssa_regs + 32);
1691 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001692}
1693
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001694void MIRGraph::SSATransformationStart() {
1695 DCHECK(temp_scoped_alloc_.get() == nullptr);
1696 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001697 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001698 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1699 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001700}
1701
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001702void MIRGraph::SSATransformationEnd() {
1703 // Verify the dataflow information after the pass.
1704 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1705 VerifyDataflow();
1706 }
1707
1708 temp_bit_vector_size_ = 0u;
1709 temp_bit_vector_ = nullptr;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001710 temp_bit_matrix_ = nullptr; // Def block matrix.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001711 DCHECK(temp_scoped_alloc_.get() != nullptr);
1712 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001713
1714 // Update the maximum number of reachable blocks.
1715 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001716}
1717
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001718size_t MIRGraph::GetNumDalvikInsns() const {
1719 size_t cumulative_size = 0u;
1720 bool counted_current_item = false;
1721 const uint8_t size_for_null_code_item = 2u;
1722
1723 for (auto it : m_units_) {
1724 const DexFile::CodeItem* code_item = it->GetCodeItem();
1725 // Even if the code item is null, we still count non-zero value so that
1726 // each m_unit is counted as having impact.
1727 cumulative_size += (code_item == nullptr ?
1728 size_for_null_code_item : code_item->insns_size_in_code_units_);
1729 if (code_item == current_code_item_) {
1730 counted_current_item = true;
1731 }
1732 }
1733
1734 // If the current code item was not counted yet, count it now.
1735 // This can happen for example in unit tests where some fields like m_units_
1736 // are not initialized.
1737 if (counted_current_item == false) {
1738 cumulative_size += (current_code_item_ == nullptr ?
1739 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1740 }
1741
1742 return cumulative_size;
1743}
1744
Vladimir Marko55fff042014-07-10 12:42:52 +01001745static BasicBlock* SelectTopologicalSortOrderFallBack(
1746 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1747 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1748 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1749 // No true loop head has been found but there may be true loop heads after the mess we need
1750 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1751 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1752 BasicBlock* fall_back = nullptr;
1753 size_t fall_back_num_reachable = 0u;
1754 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1755 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1756 AllNodesIterator iter(mir_graph);
1757 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1758 if (candidate->hidden || // Hidden, or
1759 candidate->visited || // already processed, or
1760 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1761 (current_loop != nullptr && // outside current loop.
1762 !current_loop->IsBitSet(candidate->id))) {
1763 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001764 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001765 DCHECK(tmp_stack->empty());
1766 tmp_stack->push_back(candidate->id);
1767 candidate_reachable.ClearAllBits();
1768 size_t num_reachable = 0u;
1769 while (!tmp_stack->empty()) {
1770 BasicBlockId current_id = tmp_stack->back();
1771 tmp_stack->pop_back();
1772 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1773 DCHECK(current_bb != nullptr);
1774 ChildBlockIterator child_iter(current_bb, mir_graph);
1775 BasicBlock* child_bb = child_iter.Next();
1776 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1777 DCHECK(!child_bb->hidden);
1778 if (child_bb->visited || // Already processed, or
1779 (current_loop != nullptr && // outside current loop.
1780 !current_loop->IsBitSet(child_bb->id))) {
1781 continue;
1782 }
1783 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1784 candidate_reachable.SetBit(child_bb->id);
1785 tmp_stack->push_back(child_bb->id);
1786 num_reachable += 1u;
1787 }
1788 }
1789 }
1790 if (fall_back_num_reachable < num_reachable) {
1791 fall_back_num_reachable = num_reachable;
1792 fall_back = candidate;
1793 }
1794 }
1795 return fall_back;
1796}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001797
Vladimir Marko55fff042014-07-10 12:42:52 +01001798// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1799static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1800 ArenaBitVector* reachable,
1801 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1802 // NOTE: Loop heads indicated by the "visited" flag.
1803 DCHECK(tmp_stack->empty());
1804 reachable->ClearAllBits();
1805 tmp_stack->push_back(bb_id);
1806 while (!tmp_stack->empty()) {
1807 BasicBlockId current_id = tmp_stack->back();
1808 tmp_stack->pop_back();
1809 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1810 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001811 for (BasicBlockId pred_id : current_bb->predecessors) {
1812 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1813 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001814 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1815 reachable->SetBit(pred_bb->id);
1816 tmp_stack->push_back(pred_bb->id);
1817 }
1818 }
1819 }
1820}
1821
1822void MIRGraph::ComputeTopologicalSortOrder() {
1823 ScopedArenaAllocator allocator(&cu_->arena_stack);
1824 unsigned int num_blocks = GetNumBlocks();
1825
1826 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1827 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1828 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1829 size_t max_nested_loops = 0u;
1830 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1831 loop_exit_blocks.ClearAllBits();
1832
1833 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001834 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001835 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001836 if (bb->hidden == true) {
1837 continue;
1838 }
1839
Vladimir Marko55fff042014-07-10 12:42:52 +01001840 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001841
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001842 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001843 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001844 q.push(bb);
1845 }
1846 }
1847
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001848 // Clear the topological order arrays.
1849 topological_order_.clear();
1850 topological_order_.reserve(num_blocks);
1851 topological_order_loop_ends_.clear();
1852 topological_order_loop_ends_.resize(num_blocks, 0u);
1853 topological_order_indexes_.clear();
1854 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001855
1856 // Mark all blocks as unvisited.
1857 ClearAllVisitedFlags();
1858
1859 // For loop heads, keep track from which blocks they are reachable not going through other
1860 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1861 // in this set go into the loop body, the other children are jumping over the loop.
1862 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1863 loop_head_reachable_from.resize(num_blocks, nullptr);
1864 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1865 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1866
1867 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001868 BasicBlock* bb = nullptr;
1869 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001870 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001871 // Get top.
1872 bb = q.front();
1873 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001874 if (bb->visited) {
1875 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1876 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001877 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1878 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001879 DCHECK_EQ(loop_head_stack.back(), bb->id);
1880 loop_head_stack.pop_back();
1881 ArenaBitVector* reachable =
1882 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1883 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1884 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1885 q.push(GetBasicBlock(candidate_id));
1886 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1887 // so clearing the bit has no effect on the iterator.
1888 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001889 }
1890 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001891 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001892 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001893 } else {
1894 // Find the new loop head.
1895 AllNodesIterator iter(this);
1896 while (true) {
1897 BasicBlock* candidate = iter.Next();
1898 if (candidate == nullptr) {
1899 // We did not find a true loop head, fall back to a reachable block in any loop.
1900 ArenaBitVector* current_loop =
1901 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1902 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1903 &allocator, &tmp_stack);
1904 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1905 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1906 LOG(INFO) << "Topological sort order: Using fall-back in "
1907 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1908 << " @0x" << std::hex << bb->start_offset
1909 << ", num_blocks = " << std::dec << num_blocks;
1910 }
1911 break;
1912 }
1913 if (candidate->hidden || // Hidden, or
1914 candidate->visited || // already processed, or
1915 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1916 (!loop_head_stack.empty() && // outside current loop.
1917 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1918 continue;
1919 }
1920
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001921 for (BasicBlockId pred_id : candidate->predecessors) {
1922 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1923 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001924 if (pred_bb != candidate && !pred_bb->visited &&
1925 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001926 candidate = nullptr; // Set candidate to null to indicate failure.
1927 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001928 }
1929 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001930 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001931 bb = candidate;
1932 break;
1933 }
1934 }
1935 // Compute blocks from which the loop head is reachable and process those blocks first.
1936 ArenaBitVector* reachable =
1937 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1938 loop_head_reachable_from[bb->id] = reachable;
1939 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1940 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1941 loop_head_stack.push_back(bb->id);
1942 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001943 }
1944
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001945 DCHECK_EQ(bb->hidden, false);
1946 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001947 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001948
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001949 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001950 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1951 topological_order_indexes_[bb->id] = idx;
1952 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001953
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001955 ChildBlockIterator succIter(bb, this);
1956 BasicBlock* successor = succIter.Next();
1957 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001959 continue;
1960 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001961
Vladimir Marko55fff042014-07-10 12:42:52 +01001962 // One more predecessor was visited.
1963 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001964 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001965 if (loop_head_stack.empty() ||
1966 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1967 q.push(successor);
1968 } else {
1969 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1970 loop_exit_blocks.SetBit(successor->id);
1971 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001972 }
1973 }
1974 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001975
1976 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001977 topological_order_loop_head_stack_.clear();
1978 topological_order_loop_head_stack_.reserve(max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001979}
1980
1981bool BasicBlock::IsExceptionBlock() const {
1982 if (block_type == kExceptionHandling) {
1983 return true;
1984 }
1985 return false;
1986}
1987
Wei Jin04f4d8a2014-05-29 18:04:29 -07001988bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1989 BasicBlock* target = GetBasicBlock(target_id);
1990
1991 if (source == nullptr || target == nullptr)
1992 return false;
1993
1994 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001995 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1996 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001997 if (bb == source)
1998 return true; // The block has been inserted by a suspend check before.
1999 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
2000 return true;
2001 }
2002
2003 return false;
2004}
2005
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002006ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2007 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2008 visited_taken_(false), have_successors_(false) {
2009 // Check if we actually do have successors.
2010 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2011 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002012 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002013 }
2014}
2015
2016BasicBlock* ChildBlockIterator::Next() {
2017 // We check if we have a basic block. If we don't we cannot get next child.
2018 if (basic_block_ == nullptr) {
2019 return nullptr;
2020 }
2021
2022 // If we haven't visited fallthrough, return that.
2023 if (visited_fallthrough_ == false) {
2024 visited_fallthrough_ = true;
2025
2026 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2027 if (result != nullptr) {
2028 return result;
2029 }
2030 }
2031
2032 // If we haven't visited taken, return that.
2033 if (visited_taken_ == false) {
2034 visited_taken_ = true;
2035
2036 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2037 if (result != nullptr) {
2038 return result;
2039 }
2040 }
2041
2042 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2043 if (have_successors_ == true) {
2044 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002045 auto end = basic_block_->successor_blocks.cend();
2046 while (successor_iter_ != end) {
2047 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2048 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002049 // If block was replaced by zero block, take next one.
2050 if (successor_block_info->block != NullBasicBlockId) {
2051 return mir_graph_->GetBasicBlock(successor_block_info->block);
2052 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002053 }
2054 }
2055
2056 // We do not have anything.
2057 return nullptr;
2058}
2059
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002060BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2061 MIRGraph* mir_graph = c_unit->mir_graph.get();
2062 return Copy(mir_graph);
2063}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002064
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002065BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2066 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002067
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002068 // We don't do a memcpy style copy here because it would lead to a lot of things
2069 // to clean up. Let us do it by hand instead.
2070 // Copy in taken and fallthrough.
2071 result_bb->fall_through = fall_through;
2072 result_bb->taken = taken;
2073
2074 // Copy successor links if needed.
2075 ArenaAllocator* arena = mir_graph->GetArena();
2076
2077 result_bb->successor_block_list_type = successor_block_list_type;
2078 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002079 result_bb->successor_blocks.reserve(successor_blocks.size());
2080 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2081 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2082 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002083 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002084 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002085 }
2086 }
2087
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002088 // Copy offset, method.
2089 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002090
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002091 // Now copy instructions.
2092 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2093 // Get a copy first.
2094 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002095
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002096 // Append it.
2097 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002098 }
2099
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002100 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002101}
2102
2103MIR* MIR::Copy(MIRGraph* mir_graph) {
2104 MIR* res = mir_graph->NewMIR();
2105 *res = *this;
2106
2107 // Remove links
2108 res->next = nullptr;
2109 res->bb = NullBasicBlockId;
2110 res->ssa_rep = nullptr;
2111
2112 return res;
2113}
2114
2115MIR* MIR::Copy(CompilationUnit* c_unit) {
2116 return Copy(c_unit->mir_graph.get());
2117}
2118
2119uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2120 // Default result.
2121 int res = 0;
2122
2123 // We are basically setting the iputs to their igets counterparts.
2124 switch (opcode) {
2125 case Instruction::IPUT:
2126 case Instruction::IPUT_OBJECT:
2127 case Instruction::IPUT_BOOLEAN:
2128 case Instruction::IPUT_BYTE:
2129 case Instruction::IPUT_CHAR:
2130 case Instruction::IPUT_SHORT:
2131 case Instruction::IPUT_QUICK:
2132 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002133 case Instruction::IPUT_BOOLEAN_QUICK:
2134 case Instruction::IPUT_BYTE_QUICK:
2135 case Instruction::IPUT_CHAR_QUICK:
2136 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002137 case Instruction::APUT:
2138 case Instruction::APUT_OBJECT:
2139 case Instruction::APUT_BOOLEAN:
2140 case Instruction::APUT_BYTE:
2141 case Instruction::APUT_CHAR:
2142 case Instruction::APUT_SHORT:
2143 case Instruction::SPUT:
2144 case Instruction::SPUT_OBJECT:
2145 case Instruction::SPUT_BOOLEAN:
2146 case Instruction::SPUT_BYTE:
2147 case Instruction::SPUT_CHAR:
2148 case Instruction::SPUT_SHORT:
2149 // Skip the VR containing what to store.
2150 res = 1;
2151 break;
2152 case Instruction::IPUT_WIDE:
2153 case Instruction::IPUT_WIDE_QUICK:
2154 case Instruction::APUT_WIDE:
2155 case Instruction::SPUT_WIDE:
2156 // Skip the two VRs containing what to store.
2157 res = 2;
2158 break;
2159 default:
2160 // Do nothing in the general case.
2161 break;
2162 }
2163
2164 return res;
2165}
2166
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002167/**
2168 * @brief Given a decoded instruction, it checks whether the instruction
2169 * sets a constant and if it does, more information is provided about the
2170 * constant being set.
2171 * @param ptr_value pointer to a 64-bit holder for the constant.
2172 * @param wide Updated by function whether a wide constant is being set by bytecode.
2173 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2174 */
2175bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2176 bool sets_const = true;
2177 int64_t value = vB;
2178
2179 DCHECK(ptr_value != nullptr);
2180 DCHECK(wide != nullptr);
2181
2182 switch (opcode) {
2183 case Instruction::CONST_4:
2184 case Instruction::CONST_16:
2185 case Instruction::CONST:
2186 *wide = false;
2187 value <<= 32; // In order to get the sign extend.
2188 value >>= 32;
2189 break;
2190 case Instruction::CONST_HIGH16:
2191 *wide = false;
2192 value <<= 48; // In order to get the sign extend.
2193 value >>= 32;
2194 break;
2195 case Instruction::CONST_WIDE_16:
2196 case Instruction::CONST_WIDE_32:
2197 *wide = true;
2198 value <<= 32; // In order to get the sign extend.
2199 value >>= 32;
2200 break;
2201 case Instruction::CONST_WIDE:
2202 *wide = true;
2203 value = vB_wide;
2204 break;
2205 case Instruction::CONST_WIDE_HIGH16:
2206 *wide = true;
2207 value <<= 48; // In order to get the sign extend.
2208 break;
2209 default:
2210 sets_const = false;
2211 break;
2212 }
2213
2214 if (sets_const) {
2215 *ptr_value = value;
2216 }
2217
2218 return sets_const;
2219}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002220
2221void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2222 // Reset flags for all MIRs in bb.
2223 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2224 mir->optimization_flags &= (~reset_flags);
2225 }
2226}
2227
Vladimir Marko312eb252014-10-07 15:01:57 +01002228void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002229 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2230 block_type = kDalvikByteCode;
2231
2232 // Mark it as hidden.
2233 hidden = true;
2234
2235 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2236 // are updated to know that they no longer have a parent.
2237 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2238 mir->bb = NullBasicBlockId;
2239 }
2240 first_mir_insn = nullptr;
2241 last_mir_insn = nullptr;
2242
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002243 for (BasicBlockId pred_id : predecessors) {
2244 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2245 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002246
2247 // Sadly we have to go through the children by hand here.
2248 pred_bb->ReplaceChild(id, NullBasicBlockId);
2249 }
2250
2251 // Iterate through children of bb we are hiding.
2252 ChildBlockIterator successorChildIter(this, mir_graph);
2253
2254 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002255 // Erase this predecessor from child.
2256 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002257 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002258
2259 // Remove link to children.
2260 taken = NullBasicBlockId;
2261 fall_through = NullBasicBlockId;
2262 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002263}
2264
Vladimir Marko312eb252014-10-07 15:01:57 +01002265/*
2266 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2267 */
2268void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2269 DCHECK(predecessors.empty()); // Unreachable.
2270
2271 // Mark as dead and hidden.
2272 block_type = kDead;
2273 hidden = true;
2274
2275 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2276 // are updated to know that they no longer have a parent.
2277 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2278 mir->bb = NullBasicBlockId;
2279 }
2280 first_mir_insn = nullptr;
2281 last_mir_insn = nullptr;
2282
2283 data_flow_info = nullptr;
2284
2285 // Erase this bb from all children's predecessors and kill unreachable children.
2286 ChildBlockIterator iter(this, mir_graph);
2287 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2288 succ_bb->ErasePredecessor(id);
2289 if (succ_bb->predecessors.empty()) {
2290 succ_bb->KillUnreachable(mir_graph);
2291 }
2292 }
2293
2294 // Remove links to children.
2295 fall_through = NullBasicBlockId;
2296 taken = NullBasicBlockId;
2297 successor_block_list_type = kNotUsed;
2298
2299 if (kIsDebugBuild) {
2300 if (catch_entry) {
2301 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2302 mir_graph->catches_.erase(start_offset);
2303 }
2304 }
2305}
2306
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002307bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2308 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2309 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2310 // then it is not live out of this BB.
2311 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2312
2313 int last_ssa_reg = -1;
2314
2315 // Walk through the MIRs backwards.
2316 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2317 // Get ssa rep.
2318 SSARepresentation *ssa_rep = mir->ssa_rep;
2319
2320 // Go through the defines for this MIR.
2321 for (int i = 0; i < ssa_rep->num_defs; i++) {
2322 DCHECK(ssa_rep->defs != nullptr);
2323
2324 // Get the ssa reg.
2325 int def_ssa_reg = ssa_rep->defs[i];
2326
2327 // Get dalvik reg.
2328 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2329
2330 // Compare dalvik regs.
2331 if (dalvik_reg == def_dalvik_reg) {
2332 // We found a def of the register that we are being asked about.
2333 // Remember it.
2334 last_ssa_reg = def_ssa_reg;
2335 }
2336 }
2337 }
2338
2339 if (last_ssa_reg == -1) {
2340 // If we get to this point we couldn't find a define of register user asked about.
2341 // Let's assume the user knows what he's doing so we can be safe and say that if we
2342 // couldn't find a def, it is live out.
2343 return true;
2344 }
2345
2346 // If it is not -1, we found a match, is it ssa_reg?
2347 return (ssa_reg == last_ssa_reg);
2348}
2349
2350bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2351 // We need to check taken, fall_through, and successor_blocks to replace.
2352 bool found = false;
2353 if (taken == old_bb) {
2354 taken = new_bb;
2355 found = true;
2356 }
2357
2358 if (fall_through == old_bb) {
2359 fall_through = new_bb;
2360 found = true;
2361 }
2362
2363 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002364 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002365 if (successor_block_info->block == old_bb) {
2366 successor_block_info->block = new_bb;
2367 found = true;
2368 }
2369 }
2370 }
2371
2372 return found;
2373}
2374
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002375void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2376 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2377 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002378 // It's faster to move the back() to *pos than erase(pos).
2379 *pos = predecessors.back();
2380 predecessors.pop_back();
2381 size_t idx = std::distance(predecessors.begin(), pos);
2382 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2383 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2384 break;
2385 }
2386 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2387 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2388 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2389 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2390 mir->ssa_rep->num_uses = predecessors.size();
2391 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002392}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002393
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002394void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2395 DCHECK_NE(new_pred, NullBasicBlockId);
2396 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002397 DCHECK(pos != predecessors.end());
2398 *pos = new_pred;
2399 size_t idx = std::distance(predecessors.begin(), pos);
2400 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2401 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2402 break;
2403 }
2404 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2405 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002406 }
2407}
2408
2409// Create a new basic block with block_id as num_blocks_ that is
2410// post-incremented.
2411BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2412 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002413 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002414 return res;
2415}
2416
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002417void MIRGraph::CalculateBasicBlockInformation() {
2418 PassDriverMEPostOpt driver(cu_);
2419 driver.Launch();
2420}
2421
2422void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002423 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002424}
2425
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002426int MIR::DecodedInstruction::FlagsOf() const {
2427 // Calculate new index.
2428 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2429
2430 // Check if it is an extended or not.
2431 if (idx < 0) {
2432 return Instruction::FlagsOf(opcode);
2433 }
2434
2435 // For extended, we use a switch.
2436 switch (static_cast<int>(opcode)) {
2437 case kMirOpPhi:
2438 return Instruction::kContinue;
2439 case kMirOpCopy:
2440 return Instruction::kContinue;
2441 case kMirOpFusedCmplFloat:
2442 return Instruction::kContinue | Instruction::kBranch;
2443 case kMirOpFusedCmpgFloat:
2444 return Instruction::kContinue | Instruction::kBranch;
2445 case kMirOpFusedCmplDouble:
2446 return Instruction::kContinue | Instruction::kBranch;
2447 case kMirOpFusedCmpgDouble:
2448 return Instruction::kContinue | Instruction::kBranch;
2449 case kMirOpFusedCmpLong:
2450 return Instruction::kContinue | Instruction::kBranch;
2451 case kMirOpNop:
2452 return Instruction::kContinue;
2453 case kMirOpNullCheck:
2454 return Instruction::kContinue | Instruction::kThrow;
2455 case kMirOpRangeCheck:
2456 return Instruction::kContinue | Instruction::kThrow;
2457 case kMirOpDivZeroCheck:
2458 return Instruction::kContinue | Instruction::kThrow;
2459 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002460 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002461 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002462 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002463 case kMirOpSelect:
2464 return Instruction::kContinue;
2465 case kMirOpConstVector:
2466 return Instruction::kContinue;
2467 case kMirOpMoveVector:
2468 return Instruction::kContinue;
2469 case kMirOpPackedMultiply:
2470 return Instruction::kContinue;
2471 case kMirOpPackedAddition:
2472 return Instruction::kContinue;
2473 case kMirOpPackedSubtract:
2474 return Instruction::kContinue;
2475 case kMirOpPackedShiftLeft:
2476 return Instruction::kContinue;
2477 case kMirOpPackedSignedShiftRight:
2478 return Instruction::kContinue;
2479 case kMirOpPackedUnsignedShiftRight:
2480 return Instruction::kContinue;
2481 case kMirOpPackedAnd:
2482 return Instruction::kContinue;
2483 case kMirOpPackedOr:
2484 return Instruction::kContinue;
2485 case kMirOpPackedXor:
2486 return Instruction::kContinue;
2487 case kMirOpPackedAddReduce:
2488 return Instruction::kContinue;
2489 case kMirOpPackedReduce:
2490 return Instruction::kContinue;
2491 case kMirOpPackedSet:
2492 return Instruction::kContinue;
2493 case kMirOpReserveVectorRegisters:
2494 return Instruction::kContinue;
2495 case kMirOpReturnVectorRegisters:
2496 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002497 case kMirOpMemBarrier:
2498 return Instruction::kContinue;
2499 case kMirOpPackedArrayGet:
2500 return Instruction::kContinue | Instruction::kThrow;
2501 case kMirOpPackedArrayPut:
2502 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002503 default:
2504 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2505 return 0;
2506 }
2507}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002508} // namespace art