blob: 312a6ebcd6c8f44f13499879c10588969f426089 [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",
Ningsheng Jiana262f772014-11-25 16:48:07 +080073 "MaddInt",
74 "MsubInt",
75 "MaddLong",
76 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070077};
78
buzbee862a7602013-04-05 10:58:54 -070079MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070080 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010081 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070082 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010083 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
84 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Vladimir Marko1c6ea442014-12-19 18:11:35 +000085 vreg_to_ssa_map_(NULL),
86 ssa_last_defs_(NULL),
buzbee311ca162013-02-28 15:56:43 -080087 is_constant_v_(NULL),
88 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010089 use_counts_(arena->Adapter()),
90 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080091 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070092 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010093 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000094 domination_up_to_date_(false),
95 mir_ssa_rep_up_to_date_(false),
96 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010097 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
98 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
99 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
100 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
101 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
102 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
103 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100104 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800105 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000106 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100107 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800108 try_block_addr_(NULL),
109 entry_block_(NULL),
110 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800111 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100112 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100113 m_units_(arena->Adapter()),
114 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800115 current_method_(kInvalidEntry),
116 current_offset_(kInvalidEntry),
117 def_count_(0),
118 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700119 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100120 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700121 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700122 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
123 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700124 arena_(arena),
125 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800126 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800127 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700128 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
129 requested_backend_temp_(false),
130 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000131 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000132 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100133 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
134 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
135 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000136 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000137 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100138 use_counts_.reserve(256);
139 raw_use_counts_.reserve(256);
140 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700141 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700142
143
144 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
145 // X86 requires a temp to keep track of the method address.
146 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
147 // this needs to be updated to reserve 0 temps for BE.
148 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
149 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
150 } else {
151 // Other architectures do not have a known lower bound for non-special temps.
152 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
153 max_available_non_special_compiler_temps_ = 0;
154 reserved_temps_for_backend_ = 0;
155 }
buzbee311ca162013-02-28 15:56:43 -0800156}
157
Ian Rogers6282dc12013-04-18 15:54:02 -0700158MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100159 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700160 STLDeleteElements(&m_units_);
161}
162
buzbee311ca162013-02-28 15:56:43 -0800163/*
164 * Parse an instruction, return the length of the instruction
165 */
Ian Rogers29a26482014-05-02 15:27:29 -0700166int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
167 const Instruction* inst = Instruction::At(code_ptr);
168 decoded_instruction->opcode = inst->Opcode();
169 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
170 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
171 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
172 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
173 if (inst->HasVarArgs()) {
174 inst->GetVarArgs(decoded_instruction->arg);
175 }
176 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800177}
178
179
180/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700181BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700182 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700183 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800184 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400185 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800186 while (insn) {
187 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700188 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800189 insn = insn->next;
190 }
191 if (insn == NULL) {
192 LOG(FATAL) << "Break split failed";
193 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400194 // Now insn is at the instruction where we want to split, namely
195 // insn will be the first instruction of the "bottom" block.
196 // Similarly, prev will be the last instruction of the "top" block
197
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100198 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800199
200 bottom_block->start_offset = code_offset;
201 bottom_block->first_mir_insn = insn;
202 bottom_block->last_mir_insn = orig_block->last_mir_insn;
203
Junmo Park90223cc2014-08-04 18:51:21 +0900204 /* If this block was terminated by a return, conditional branch or throw,
205 * the flag needs to go with the bottom block
206 */
buzbee311ca162013-02-28 15:56:43 -0800207 bottom_block->terminated_by_return = orig_block->terminated_by_return;
208 orig_block->terminated_by_return = false;
209
Junmo Park90223cc2014-08-04 18:51:21 +0900210 bottom_block->conditional_branch = orig_block->conditional_branch;
211 orig_block->conditional_branch = false;
212
213 bottom_block->explicit_throw = orig_block->explicit_throw;
214 orig_block->explicit_throw = false;
215
buzbee311ca162013-02-28 15:56:43 -0800216 /* Handle the taken path */
217 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700218 if (bottom_block->taken != NullBasicBlockId) {
219 orig_block->taken = NullBasicBlockId;
220 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100221 bb_taken->ErasePredecessor(orig_block->id);
222 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800223 }
224
225 /* Handle the fallthrough path */
226 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700227 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100228 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700229 if (bottom_block->fall_through != NullBasicBlockId) {
230 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100231 bb_fall_through->ErasePredecessor(orig_block->id);
232 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800233 }
234
235 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700236 if (orig_block->successor_block_list_type != kNotUsed) {
237 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700239 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100240 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
241 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700242 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700243 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100244 bb->ErasePredecessor(orig_block->id);
245 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700246 }
buzbee311ca162013-02-28 15:56:43 -0800247 }
248 }
249
buzbee0d829482013-10-11 15:24:55 -0700250 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700251 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800252
buzbee311ca162013-02-28 15:56:43 -0800253 /*
254 * Update the immediate predecessor block pointer so that outgoing edges
255 * can be applied to the proper block.
256 */
257 if (immed_pred_block_p) {
258 DCHECK_EQ(*immed_pred_block_p, orig_block);
259 *immed_pred_block_p = bottom_block;
260 }
buzbeeb48819d2013-09-14 16:15:25 -0700261
262 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000263 DCHECK(insn != nullptr);
264 DCHECK(insn != orig_block->first_mir_insn);
265 DCHECK(insn == bottom_block->first_mir_insn);
266 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100267 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400268 // Scan the "bottom" instructions, remapping them to the
269 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000270 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400271 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100272 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000273 while (p != bottom_block->last_mir_insn) {
274 p = p->next;
275 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700276 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700277 int opcode = p->dalvikInsn.opcode;
278 /*
279 * Some messiness here to ensure that we only enter real opcodes and only the
280 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000281 * CHECK and work portions. Since the 2nd half of a split operation is always
282 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700283 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700284 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400285 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
286 // At first glance the instructions should all be mapped to orig_block.
287 // However, multiple instructions may correspond to the same dex, hence an earlier
288 // instruction may have already moved the mapping for dex to bottom_block.
289 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100290 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700291 }
buzbeeb48819d2013-09-14 16:15:25 -0700292 }
293
buzbee311ca162013-02-28 15:56:43 -0800294 return bottom_block;
295}
296
297/*
298 * Given a code offset, find out the block that starts with it. If the offset
299 * is in the middle of an existing block, split it into two. If immed_pred_block_p
300 * is not non-null and is the block being split, update *immed_pred_block_p to
301 * point to the bottom block so that outgoing edges can be set up properly
302 * (by the caller)
303 * Utilizes a map for fast lookup of the typical cases.
304 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700305BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700306 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700307 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700308 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800309 }
buzbeeb48819d2013-09-14 16:15:25 -0700310
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100311 int block_id = dex_pc_to_block_map_[code_offset];
312 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700313
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700314 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700315 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700316 return bb;
317 }
buzbee311ca162013-02-28 15:56:43 -0800318
buzbeeb48819d2013-09-14 16:15:25 -0700319 // No direct hit.
320 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700321 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800322 }
323
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700324 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700325 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700326 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700327 }
328
329 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100330 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800331 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100332 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800333 return bb;
334}
335
buzbeeb48819d2013-09-14 16:15:25 -0700336
buzbee311ca162013-02-28 15:56:43 -0800337/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700338void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800339 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700340 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800341
342 if (tries_size == 0) {
343 return;
344 }
345
346 for (int i = 0; i < tries_size; i++) {
347 const DexFile::TryItem* pTry =
348 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700349 DexOffset start_offset = pTry->start_addr_;
350 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800351 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700352 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800353 }
354 }
355
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700356 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700357 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800358 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
359 for (uint32_t idx = 0; idx < handlers_size; idx++) {
360 CatchHandlerIterator iterator(handlers_ptr);
361 for (; iterator.HasNext(); iterator.Next()) {
362 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700363 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800364 }
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);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700468 BasicBlock* taken_block = FindBlock(target, /* 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 /* create */
477 true,
478 /* immed_pred_block_p */
479 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700480 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100481 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800482 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700483 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800484 }
485 return cur_block;
486}
487
488/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800489BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
490 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700491 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800492 const uint16_t* switch_data =
493 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
494 int size;
495 const int* keyTable;
496 const int* target_table;
497 int i;
498 int first_key;
499
500 /*
501 * Packed switch data format:
502 * ushort ident = 0x0100 magic value
503 * ushort size number of entries in the table
504 * int first_key first (and lowest) switch case value
505 * int targets[size] branch targets, relative to switch opcode
506 *
507 * Total size is (4+size*2) 16-bit code units.
508 */
509 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
510 DCHECK_EQ(static_cast<int>(switch_data[0]),
511 static_cast<int>(Instruction::kPackedSwitchSignature));
512 size = switch_data[1];
513 first_key = switch_data[2] | (switch_data[3] << 16);
514 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700515 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800516 /*
517 * Sparse switch data format:
518 * ushort ident = 0x0200 magic value
519 * ushort size number of entries in the table; > 0
520 * int keys[size] keys, sorted low-to-high; 32-bit aligned
521 * int targets[size] branch targets, relative to switch opcode
522 *
523 * Total size is (2+size*4) 16-bit code units.
524 */
525 } else {
526 DCHECK_EQ(static_cast<int>(switch_data[0]),
527 static_cast<int>(Instruction::kSparseSwitchSignature));
528 size = switch_data[1];
529 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
530 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700531 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800532 }
533
buzbee0d829482013-10-11 15:24:55 -0700534 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800535 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700536 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800537 }
buzbee0d829482013-10-11 15:24:55 -0700538 cur_block->successor_block_list_type =
539 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100540 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800541
542 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700543 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
544 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700545 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700546 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000547 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700548 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800549 successor_block_info->key =
550 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
551 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100552 cur_block->successor_blocks.push_back(successor_block_info);
553 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800554 }
555
556 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700557 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
558 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700559 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100560 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800561 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800562}
563
564/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700565BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
566 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700567 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700568 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700569 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800570 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800571
572 /* In try block */
573 if (in_try_block) {
574 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
575
buzbee0d829482013-10-11 15:24:55 -0700576 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800577 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
578 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700579 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800580 }
581
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700582 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700583 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
584 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100585 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
586 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
587 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
588 continue;
589 }
590 if (cur_block->successor_block_list_type == kNotUsed) {
591 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100592 }
buzbee311ca162013-02-28 15:56:43 -0800593 catch_block->catch_entry = true;
594 if (kIsDebugBuild) {
595 catches_.insert(catch_block->start_offset);
596 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700597 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000598 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700599 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800600 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100601 cur_block->successor_blocks.push_back(successor_block_info);
602 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800603 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100604 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
605 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100606 bool build_all_edges =
607 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100608 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100609 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700610 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800611 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100612 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800613 }
614
buzbee17189ac2013-11-08 11:07:02 -0800615 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800616 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700617 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700618 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700619 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800620 }
621 if (!in_try_block) {
622 // Don't split a THROW that can't rethrow - we're done.
623 return cur_block;
624 }
625 }
626
buzbee17189ac2013-11-08 11:07:02 -0800627 if (!build_all_edges) {
628 /*
629 * Even though there is an exception edge here, control cannot return to this
630 * method. Thus, for the purposes of dataflow analysis and optimization, we can
631 * ignore the edge. Doing this reduces compile time, and increases the scope
632 * of the basic-block level optimization pass.
633 */
634 return cur_block;
635 }
636
buzbee311ca162013-02-28 15:56:43 -0800637 /*
638 * Split the potentially-throwing instruction into two parts.
639 * The first half will be a pseudo-op that captures the exception
640 * edges and terminates the basic block. It always falls through.
641 * Then, create a new basic block that begins with the throwing instruction
642 * (minus exceptions). Note: this new basic block must NOT be entered into
643 * the block_map. If the potentially-throwing instruction is the target of a
644 * future branch, we need to find the check psuedo half. The new
645 * basic block containing the work portion of the instruction should
646 * only be entered via fallthrough from the block containing the
647 * pseudo exception edge MIR. Note also that this new block is
648 * not automatically terminated after the work portion, and may
649 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700650 *
651 * Note also that the dex_pc_to_block_map_ entry for the potentially
652 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800653 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100654 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800655 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700656 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100657 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700658 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800659 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700660 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700661 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800662 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700663 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800664 return new_block;
665}
666
667/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
668void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700669 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700670 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800671 current_code_item_ = code_item;
672 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
673 current_method_ = m_units_.size();
674 current_offset_ = 0;
675 // TODO: will need to snapshot stack image and use that as the mir context identification.
676 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000677 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
678 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800679 const uint16_t* code_ptr = current_code_item_->insns_;
680 const uint16_t* code_end =
681 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
682
683 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700684 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100685 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
686 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 -0700687
buzbee311ca162013-02-28 15:56:43 -0800688 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700689 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
690 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800691
692 // If this is the first method, set up default entry and exit blocks.
693 if (current_method_ == 0) {
694 DCHECK(entry_block_ == NULL);
695 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000696 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700697 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100698 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700699 DCHECK_EQ(null_block->id, NullBasicBlockId);
700 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100701 entry_block_ = CreateNewBB(kEntryBlock);
702 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800703 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
704 cu_->dex_file = &dex_file;
705 cu_->class_def_idx = class_def_idx;
706 cu_->method_idx = method_idx;
707 cu_->access_flags = access_flags;
708 cu_->invoke_type = invoke_type;
709 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800710 } else {
711 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
712 /*
713 * Will need to manage storage for ins & outs, push prevous state and update
714 * insert point.
715 */
716 }
717
718 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100719 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700720 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800721 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700722 // TODO: for inlining support, insert at the insert point rather than entry block.
723 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100724 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800725
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000726 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800727 ProcessTryCatchBlocks();
728
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000729 uint64_t merged_df_flags = 0u;
730
buzbee311ca162013-02-28 15:56:43 -0800731 /* Parse all instructions and put them into containing basic blocks */
732 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700733 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800734 insn->offset = current_offset_;
735 insn->m_unit_index = current_method_;
736 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800737 Instruction::Code opcode = insn->dalvikInsn.opcode;
738 if (opcode_count_ != NULL) {
739 opcode_count_[static_cast<int>(opcode)]++;
740 }
741
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700742 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800743 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800744
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700745 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000746 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800747
748 if (df_flags & DF_HAS_DEFS) {
749 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
750 }
751
buzbee1da1e2f2013-11-15 13:37:01 -0800752 if (df_flags & DF_LVN) {
753 cur_block->use_lvn = true; // Run local value numbering on this basic block.
754 }
755
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700756 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700757 if (opcode == Instruction::NOP) {
758 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
759 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
760 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
761 uint16_t following_raw_instruction = code_ptr[1];
762 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
763 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
764 (following_raw_instruction == Instruction::kArrayDataSignature)) {
765 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
766 }
767 }
768 if (width == 1) {
769 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700770 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700771 } else {
buzbee0d829482013-10-11 15:24:55 -0700772 DCHECK(cur_block->fall_through == NullBasicBlockId);
773 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800774 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700775 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800776 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700777 }
778 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700779 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700780 }
781
buzbeeb48819d2013-09-14 16:15:25 -0700782 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100783 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700784
buzbee27247762013-07-28 12:03:58 -0700785 code_ptr += width;
786
buzbee311ca162013-02-28 15:56:43 -0800787 if (flags & Instruction::kBranch) {
788 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
789 width, flags, code_ptr, code_end);
790 } else if (flags & Instruction::kReturn) {
791 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700792 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100793 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800794 /*
795 * Terminate the current block if there are instructions
796 * afterwards.
797 */
798 if (code_ptr < code_end) {
799 /*
800 * Create a fallthrough block for real instructions
801 * (incl. NOP).
802 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700803 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800804 }
805 } else if (flags & Instruction::kThrow) {
806 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
807 code_ptr, code_end);
808 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800809 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800810 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700811 if (verify_flags & Instruction::kVerifyVarArgRange ||
812 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800813 /*
814 * The Quick backend's runtime model includes a gap between a method's
815 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
816 * which spans the gap is somewhat complicated, and should not happen
817 * in normal usage of dx. Punt to the interpreter.
818 */
819 int first_reg_in_range = insn->dalvikInsn.vC;
820 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
821 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
822 punt_to_interpreter_ = true;
823 }
824 }
buzbee311ca162013-02-28 15:56:43 -0800825 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700826 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
827 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800828 if (next_block) {
829 /*
830 * The next instruction could be the target of a previously parsed
831 * forward branch so a block is already created. If the current
832 * instruction is not an unconditional branch, connect them through
833 * the fall-through link.
834 */
buzbee0d829482013-10-11 15:24:55 -0700835 DCHECK(cur_block->fall_through == NullBasicBlockId ||
836 GetBasicBlock(cur_block->fall_through) == next_block ||
837 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800838
buzbee0d829482013-10-11 15:24:55 -0700839 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
840 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100841 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800842 }
843 cur_block = next_block;
844 }
845 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000846 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000847
buzbee311ca162013-02-28 15:56:43 -0800848 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
849 DumpCFG("/sdcard/1_post_parse_cfg/", true);
850 }
851
852 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700853 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800854 }
855}
856
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700857void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800858 DCHECK(opcode_count_ != NULL);
859 LOG(INFO) << "Opcode Count";
860 for (int i = 0; i < kNumPackedOpcodes; i++) {
861 if (opcode_count_[i] != 0) {
862 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
863 << " " << opcode_count_[i];
864 }
865 }
866}
867
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700868uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
869 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
870 return oat_data_flow_attributes_[opcode];
871}
872
873uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
874 DCHECK(mir != nullptr);
875 Instruction::Code opcode = mir->dalvikInsn.opcode;
876 return GetDataFlowAttributes(opcode);
877}
878
buzbee311ca162013-02-28 15:56:43 -0800879// TODO: use a configurable base prefix, and adjust callers to supply pass name.
880/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800881void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800882 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700883 static AtomicInteger cnt(0);
884
885 // Increment counter to get a unique file number.
886 cnt++;
887
buzbee311ca162013-02-28 15:56:43 -0800888 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
889 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700890 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800891 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700892 suffix == nullptr ? "" : suffix,
893 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800894 file = fopen(fname.c_str(), "w");
895 if (file == NULL) {
896 return;
897 }
898 fprintf(file, "digraph G {\n");
899
900 fprintf(file, " rankdir=TB\n");
901
902 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
903 int idx;
904
905 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100906 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700907 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700908 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800909 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700910 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800911 if (bb->block_type == kEntryBlock) {
912 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
913 } else if (bb->block_type == kExitBlock) {
914 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
915 } else if (bb->block_type == kDalvikByteCode) {
916 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
917 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700918 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800919 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
920 bb->first_mir_insn ? " | " : " ");
921 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
922 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800923 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400924 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700925 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
926 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400927 extended_mir_op_names_[opcode - kMirOpFirst],
928 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
929 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700930 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700931 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700932 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100933 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
934 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800935 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400936 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800937 }
938 fprintf(file, " }\"];\n\n");
939 } else if (bb->block_type == kExceptionHandling) {
940 char block_name[BLOCK_NAME_LEN];
941
942 GetBlockName(bb, block_name);
943 fprintf(file, " %s [shape=invhouse];\n", block_name);
944 }
945
946 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
947
buzbee0d829482013-10-11 15:24:55 -0700948 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800949 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700950 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800951 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
952 block_name1, block_name2);
953 }
buzbee0d829482013-10-11 15:24:55 -0700954 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800955 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700956 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800957 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
958 }
959
buzbee0d829482013-10-11 15:24:55 -0700960 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800961 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
962 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700963 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800964
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100965 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800966 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100967 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700968 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800969 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100970 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800971 successor_block_info->key,
972 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100973 (succ_id != last_succ_id) ? " | " : " ");
974 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800975 }
976 fprintf(file, " }\"];\n\n");
977
978 GetBlockName(bb, block_name1);
979 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
980 block_name1, bb->start_offset, bb->id);
981
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700982 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100984 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800986
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700987 GetBlockName(dest_block, block_name2);
988 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
989 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800990 }
991 }
992 fprintf(file, "\n");
993
994 if (cu_->verbose) {
995 /* Display the dominator tree */
996 GetBlockName(bb, block_name1);
997 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
998 block_name1, block_name1);
999 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001000 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001001 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1002 }
1003 }
1004 }
1005 fprintf(file, "}\n");
1006 fclose(file);
1007}
1008
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001009/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001010void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001011 // Insert it after the last MIR.
1012 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001013}
1014
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001015void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1016 // Insert it after the last MIR.
1017 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1018}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001019
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001020void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1021 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1022 MIR* new_mir = *it;
1023
1024 // Add a copy of each MIR.
1025 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1026 }
buzbee1fd33462013-03-25 13:40:45 -07001027}
1028
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001029/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001030void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001031 InsertMIRListAfter(current_mir, new_mir, new_mir);
1032}
buzbee1fd33462013-03-25 13:40:45 -07001033
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001034void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1035 // If no MIR, we are done.
1036 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1037 return;
buzbee1fd33462013-03-25 13:40:45 -07001038 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001039
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001040 // If insert_after is null, assume BB is empty.
1041 if (insert_after == nullptr) {
1042 first_mir_insn = first_list_mir;
1043 last_mir_insn = last_list_mir;
1044 last_list_mir->next = nullptr;
1045 } else {
1046 MIR* after_list = insert_after->next;
1047 insert_after->next = first_list_mir;
1048 last_list_mir->next = after_list;
1049 if (after_list == nullptr) {
1050 last_mir_insn = last_list_mir;
1051 }
1052 }
1053
1054 // Set this BB to be the basic block of the MIRs.
1055 MIR* last = last_list_mir->next;
1056 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1057 mir->bb = id;
1058 }
1059}
1060
1061/* Insert an MIR instruction to the head of a basic block. */
1062void BasicBlock::PrependMIR(MIR* mir) {
1063 InsertMIRListBefore(first_mir_insn, mir, mir);
1064}
1065
1066void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1067 // Insert it before the first MIR.
1068 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1069}
1070
1071void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1072 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1073 MIR* mir = *it;
1074
1075 InsertMIRListBefore(first_mir_insn, mir, mir);
1076 }
1077}
1078
1079/* Insert a MIR instruction before the specified MIR. */
1080void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1081 // Insert as a single element list.
1082 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001083}
1084
1085MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1086 MIR* current = first_mir_insn;
1087
1088 while (current != nullptr) {
1089 MIR* next = current->next;
1090
1091 if (next == mir) {
1092 return current;
1093 }
1094
1095 current = next;
1096 }
1097
1098 return nullptr;
1099}
1100
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001101void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1102 // If no MIR, we are done.
1103 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1104 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001105 }
1106
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001107 // If insert_before is null, assume BB is empty.
1108 if (insert_before == nullptr) {
1109 first_mir_insn = first_list_mir;
1110 last_mir_insn = last_list_mir;
1111 last_list_mir->next = nullptr;
1112 } else {
1113 if (first_mir_insn == insert_before) {
1114 last_list_mir->next = first_mir_insn;
1115 first_mir_insn = first_list_mir;
1116 } else {
1117 // Find the preceding MIR.
1118 MIR* before_list = FindPreviousMIR(insert_before);
1119 DCHECK(before_list != nullptr);
1120 before_list->next = first_list_mir;
1121 last_list_mir->next = insert_before;
1122 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001123 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001124
1125 // Set this BB to be the basic block of the MIRs.
1126 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1127 mir->bb = id;
1128 }
1129}
1130
1131bool BasicBlock::RemoveMIR(MIR* mir) {
1132 // Remove as a single element list.
1133 return RemoveMIRList(mir, mir);
1134}
1135
1136bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1137 if (first_list_mir == nullptr) {
1138 return false;
1139 }
1140
1141 // Try to find the MIR.
1142 MIR* before_list = nullptr;
1143 MIR* after_list = nullptr;
1144
1145 // If we are removing from the beginning of the MIR list.
1146 if (first_mir_insn == first_list_mir) {
1147 before_list = nullptr;
1148 } else {
1149 before_list = FindPreviousMIR(first_list_mir);
1150 if (before_list == nullptr) {
1151 // We did not find the mir.
1152 return false;
1153 }
1154 }
1155
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001156 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001157 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001158 mir->bb = NullBasicBlockId;
1159 }
1160
1161 after_list = last_list_mir->next;
1162
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001163 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001164 if (before_list == nullptr) {
1165 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001166 } else {
1167 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001168 }
1169
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001170 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001171 if (after_list == nullptr) {
1172 last_mir_insn = before_list;
1173 }
1174
1175 return true;
buzbee1fd33462013-03-25 13:40:45 -07001176}
1177
Vladimir Marko26e7d452014-11-24 14:09:46 +00001178MIR* BasicBlock::GetFirstNonPhiInsn() {
1179 MIR* mir = first_mir_insn;
1180 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1181 mir = mir->next;
1182 }
1183 return mir;
1184}
1185
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001186MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001187 MIR* next_mir = nullptr;
1188
1189 if (current != nullptr) {
1190 next_mir = current->next;
1191 }
1192
1193 if (next_mir == nullptr) {
1194 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001195 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1196 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001197 }
1198 }
1199
1200 return next_mir;
1201}
1202
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001203static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1204 DCHECK(decoded_mir != nullptr);
1205 OpSize type = static_cast<OpSize>(type_size >> 16);
1206 uint16_t vect_size = (type_size & 0xFFFF);
1207
1208 // Now print the type and vector size.
1209 std::stringstream ss;
1210 ss << " (type:";
1211 ss << type;
1212 ss << " vectsize:";
1213 ss << vect_size;
1214 ss << ")";
1215
1216 decoded_mir->append(ss.str());
1217}
1218
1219void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1220 DCHECK(decoded_mir != nullptr);
1221 int opcode = mir->dalvikInsn.opcode;
1222 SSARepresentation* ssa_rep = mir->ssa_rep;
1223 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1224 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1225
Vladimirf41b92c2014-10-13 13:41:38 +07001226 if (opcode < kMirOpFirst) {
1227 return; // It is not an extended instruction.
1228 }
1229
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001230 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1231
1232 switch (opcode) {
1233 case kMirOpPhi: {
1234 if (defs > 0 && uses > 0) {
1235 BasicBlockId* incoming = mir->meta.phi_incoming;
1236 decoded_mir->append(StringPrintf(" %s = (%s",
1237 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1238 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1239 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1240 for (int i = 1; i < uses; i++) {
1241 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1242 }
1243 decoded_mir->append(")");
1244 }
1245 break;
1246 }
1247 case kMirOpCopy:
1248 if (ssa_rep != nullptr) {
1249 decoded_mir->append(" ");
1250 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1251 if (defs > 1) {
1252 decoded_mir->append(", ");
1253 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1254 }
1255 decoded_mir->append(" = ");
1256 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1257 if (uses > 1) {
1258 decoded_mir->append(", ");
1259 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1260 }
1261 } else {
1262 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1263 }
1264 break;
1265 case kMirOpFusedCmplFloat:
1266 case kMirOpFusedCmpgFloat:
1267 case kMirOpFusedCmplDouble:
1268 case kMirOpFusedCmpgDouble:
1269 case kMirOpFusedCmpLong:
1270 if (ssa_rep != nullptr) {
1271 decoded_mir->append(" ");
1272 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1273 for (int i = 1; i < uses; i++) {
1274 decoded_mir->append(", ");
1275 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1276 }
1277 } else {
1278 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1279 }
1280 break;
1281 case kMirOpMoveVector:
1282 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1283 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1284 break;
1285 case kMirOpPackedAddition:
1286 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1287 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1288 break;
1289 case kMirOpPackedMultiply:
1290 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1291 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1292 break;
1293 case kMirOpPackedSubtract:
1294 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1295 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1296 break;
1297 case kMirOpPackedAnd:
1298 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1299 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1300 break;
1301 case kMirOpPackedOr:
1302 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1303 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1304 break;
1305 case kMirOpPackedXor:
1306 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1307 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1308 break;
1309 case kMirOpPackedShiftLeft:
1310 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1311 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1312 break;
1313 case kMirOpPackedUnsignedShiftRight:
1314 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1315 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1316 break;
1317 case kMirOpPackedSignedShiftRight:
1318 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1319 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1320 break;
1321 case kMirOpConstVector:
1322 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1323 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1324 break;
1325 case kMirOpPackedSet:
1326 if (ssa_rep != nullptr) {
1327 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1328 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1329 if (uses > 1) {
1330 decoded_mir->append(", ");
1331 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1332 }
1333 } else {
1334 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1335 }
1336 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1337 break;
1338 case kMirOpPackedAddReduce:
1339 if (ssa_rep != nullptr) {
1340 decoded_mir->append(" ");
1341 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1342 if (defs > 1) {
1343 decoded_mir->append(", ");
1344 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1345 }
1346 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1347 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1348 if (uses > 1) {
1349 decoded_mir->append(", ");
1350 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1351 }
1352 } else {
1353 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1354 }
1355 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1356 break;
1357 case kMirOpPackedReduce:
1358 if (ssa_rep != nullptr) {
1359 decoded_mir->append(" ");
1360 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1361 if (defs > 1) {
1362 decoded_mir->append(", ");
1363 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1364 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001365 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001366 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001367 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1368 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001369 }
1370 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1371 break;
1372 case kMirOpReserveVectorRegisters:
1373 case kMirOpReturnVectorRegisters:
1374 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1375 break;
1376 case kMirOpMemBarrier: {
1377 decoded_mir->append(" type:");
1378 std::stringstream ss;
1379 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1380 decoded_mir->append(ss.str());
1381 break;
1382 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001383 case kMirOpPackedArrayGet:
1384 case kMirOpPackedArrayPut:
1385 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1386 if (ssa_rep != nullptr) {
1387 decoded_mir->append(StringPrintf(", %s[%s]",
1388 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1389 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1390 } else {
1391 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1392 }
1393 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1394 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001395 case kMirOpMaddInt:
1396 case kMirOpMsubInt:
1397 case kMirOpMaddLong:
1398 case kMirOpMsubLong:
1399 if (ssa_rep != nullptr) {
1400 decoded_mir->append(" ");
1401 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1402 if (defs > 1) {
1403 decoded_mir->append(", ");
1404 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1405 }
1406 for (int i = 0; i < uses; i++) {
1407 decoded_mir->append(", ");
1408 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1409 }
1410 } else {
1411 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1412 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1413 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1414 }
1415 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001416 default:
1417 break;
1418 }
1419}
1420
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001421char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001422 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001423 std::string str;
1424 int flags = 0;
1425 int opcode = insn.opcode;
1426 char* ret;
1427 bool nop = false;
1428 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001429 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001430
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001431 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001432 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1433 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1434 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001435 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001436 insn = mir->meta.throw_insn->dalvikInsn;
1437 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001438 opcode = insn.opcode;
1439 } else if (opcode == kMirOpNop) {
1440 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001441 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1442 // Recover original opcode.
1443 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1444 opcode = insn.opcode;
1445 }
buzbee1fd33462013-03-25 13:40:45 -07001446 nop = true;
1447 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001448 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1449 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001450
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001451 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001452 // Note that this does not check the MIR's opcode in all cases. In cases where it
1453 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1454 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001455 } else {
1456 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001457 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001458 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001459
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001460 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001461 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1462 (dalvik_format == Instruction::k3rc));
1463 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001464 str.append(" ");
1465 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1466 if (defs > 1) {
1467 str.append(", ");
1468 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1469 }
buzbee1fd33462013-03-25 13:40:45 -07001470 if (uses != 0) {
1471 str.append(", ");
1472 }
1473 }
1474 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001475 str.append(" ");
1476 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001477 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1478 // For the listing, skip the high sreg.
1479 i++;
1480 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001481 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001482 str.append(",");
1483 }
1484 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001485
buzbee1fd33462013-03-25 13:40:45 -07001486 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001487 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001488 case Instruction::k21s:
1489 case Instruction::k31i:
1490 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001491 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001492 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001493 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001494 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001495 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001496 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001497 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001498 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001499 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001500 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001501 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001502 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001503 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001504 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001505 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001506 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001507 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001508 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001509 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001510 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001511
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001512 if ((flags & Instruction::kBranch) != 0) {
1513 // For branches, decode the instructions to print out the branch targets.
1514 int offset = 0;
1515 switch (dalvik_format) {
1516 case Instruction::k21t:
1517 offset = insn.vB;
1518 break;
1519 case Instruction::k22t:
1520 offset = insn.vC;
1521 break;
1522 case Instruction::k10t:
1523 case Instruction::k20t:
1524 case Instruction::k30t:
1525 offset = insn.vA;
1526 break;
1527 default:
1528 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001529 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001530 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001531 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001532 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1533 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001534
1535 if (nop) {
1536 str.append("]--optimized away");
1537 }
buzbee1fd33462013-03-25 13:40:45 -07001538 }
1539 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001540 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001541 strncpy(ret, str.c_str(), length);
1542 return ret;
1543}
1544
1545/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001546void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001547 static const struct { const char before; const char after; } match[] = {
1548 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1549 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1550 };
buzbee1fd33462013-03-25 13:40:45 -07001551 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1552 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1553 }
1554}
1555
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001556std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001557 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1558 // the arena. We should be smarter and just place straight into the arena, or compute the
1559 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001560 int vreg = SRegToVReg(ssa_reg);
1561 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1562 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1563 } else {
1564 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1565 }
buzbee1fd33462013-03-25 13:40:45 -07001566}
1567
1568// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001569std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001570 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001571 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001572 return GetSSAName(ssa_reg);
1573 }
1574 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001575 if (!singles_only && reg_location_[ssa_reg].wide &&
1576 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001577 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001578 ConstantValueWide(reg_location_[ssa_reg]));
1579 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001580 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001581 ConstantValue(reg_location_[ssa_reg]));
1582 }
1583 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001584 int vreg = SRegToVReg(ssa_reg);
1585 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1586 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1587 } else {
1588 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1589 }
buzbee1fd33462013-03-25 13:40:45 -07001590 }
1591}
1592
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001593void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001594 switch (bb->block_type) {
1595 case kEntryBlock:
1596 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1597 break;
1598 case kExitBlock:
1599 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1600 break;
1601 case kDalvikByteCode:
1602 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1603 break;
1604 case kExceptionHandling:
1605 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1606 bb->id);
1607 break;
1608 default:
1609 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1610 break;
1611 }
1612}
1613
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001614const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001615 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001616 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1617 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1618}
1619
Serguei Katkov717a3e42014-11-13 17:19:42 +06001620const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1621 const DexFile::MethodId& method_id =
1622 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1623 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1624}
1625
buzbee1fd33462013-03-25 13:40:45 -07001626/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001627void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001628 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001629 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001630 "Entry Block",
1631 "Code Block",
1632 "Exit Block",
1633 "Exception Handling",
1634 "Catch Block"
1635 };
1636
1637 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001638 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001639 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001640
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001641 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001642 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1643 bb->id,
1644 block_type_names[bb->block_type],
1645 bb->start_offset,
1646 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1647 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001648 if (bb->taken != NullBasicBlockId) {
1649 LOG(INFO) << " Taken branch: block " << bb->taken
1650 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001651 }
buzbee0d829482013-10-11 15:24:55 -07001652 if (bb->fall_through != NullBasicBlockId) {
1653 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1654 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001655 }
1656 }
1657}
1658
1659/*
1660 * Build an array of location records for the incoming arguments.
1661 * Note: one location record per word of arguments, with dummy
1662 * high-word loc for wide arguments. Also pull up any following
1663 * MOVE_RESULT and incorporate it into the invoke.
1664 */
1665CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001666 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001667 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001668 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001669 MIR* move_result_mir = FindMoveResult(bb, mir);
1670 if (move_result_mir == NULL) {
1671 info->result.location = kLocInvalid;
1672 } else {
1673 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001674 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1675 }
1676 info->num_arg_words = mir->ssa_rep->num_uses;
1677 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001678 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001679 for (int i = 0; i < info->num_arg_words; i++) {
1680 info->args[i] = GetRawSrc(mir, i);
1681 }
1682 info->opt_flags = mir->optimization_flags;
1683 info->type = type;
1684 info->is_range = is_range;
1685 info->index = mir->dalvikInsn.vB;
1686 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001687 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001688 return info;
1689}
1690
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001691// Allocate a new MIR.
1692MIR* MIRGraph::NewMIR() {
1693 MIR* mir = new (arena_) MIR();
1694 return mir;
1695}
1696
buzbee862a7602013-04-05 10:58:54 -07001697// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001698BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001699 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001700
buzbee862a7602013-04-05 10:58:54 -07001701 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001702 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001703 block_id_map_.Put(block_id, block_id);
1704 return bb;
1705}
buzbee1fd33462013-03-25 13:40:45 -07001706
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001707void MIRGraph::InitializeConstantPropagation() {
1708 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001709 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001710}
1711
1712void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001713 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001714 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001715 use_counts_.clear();
1716 use_counts_.reserve(num_ssa_regs + 32);
1717 use_counts_.resize(num_ssa_regs, 0u);
1718 raw_use_counts_.clear();
1719 raw_use_counts_.reserve(num_ssa_regs + 32);
1720 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001721}
1722
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001723void MIRGraph::SSATransformationStart() {
1724 DCHECK(temp_scoped_alloc_.get() == nullptr);
1725 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001726 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1727 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1728 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001729}
1730
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001731void MIRGraph::SSATransformationEnd() {
1732 // Verify the dataflow information after the pass.
1733 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1734 VerifyDataflow();
1735 }
1736
Vladimir Markof585e542014-11-21 13:41:32 +00001737 temp_.ssa.num_vregs = 0u;
1738 temp_.ssa.work_live_vregs = nullptr;
1739 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001740 DCHECK(temp_scoped_alloc_.get() != nullptr);
1741 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001742
1743 // Update the maximum number of reachable blocks.
1744 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001745
1746 // Mark MIR SSA representations as up to date.
1747 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001748}
1749
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001750size_t MIRGraph::GetNumDalvikInsns() const {
1751 size_t cumulative_size = 0u;
1752 bool counted_current_item = false;
1753 const uint8_t size_for_null_code_item = 2u;
1754
1755 for (auto it : m_units_) {
1756 const DexFile::CodeItem* code_item = it->GetCodeItem();
1757 // Even if the code item is null, we still count non-zero value so that
1758 // each m_unit is counted as having impact.
1759 cumulative_size += (code_item == nullptr ?
1760 size_for_null_code_item : code_item->insns_size_in_code_units_);
1761 if (code_item == current_code_item_) {
1762 counted_current_item = true;
1763 }
1764 }
1765
1766 // If the current code item was not counted yet, count it now.
1767 // This can happen for example in unit tests where some fields like m_units_
1768 // are not initialized.
1769 if (counted_current_item == false) {
1770 cumulative_size += (current_code_item_ == nullptr ?
1771 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1772 }
1773
1774 return cumulative_size;
1775}
1776
Vladimir Marko55fff042014-07-10 12:42:52 +01001777static BasicBlock* SelectTopologicalSortOrderFallBack(
1778 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1779 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1780 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1781 // No true loop head has been found but there may be true loop heads after the mess we need
1782 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1783 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1784 BasicBlock* fall_back = nullptr;
1785 size_t fall_back_num_reachable = 0u;
1786 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1787 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1788 AllNodesIterator iter(mir_graph);
1789 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1790 if (candidate->hidden || // Hidden, or
1791 candidate->visited || // already processed, or
1792 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1793 (current_loop != nullptr && // outside current loop.
1794 !current_loop->IsBitSet(candidate->id))) {
1795 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001796 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001797 DCHECK(tmp_stack->empty());
1798 tmp_stack->push_back(candidate->id);
1799 candidate_reachable.ClearAllBits();
1800 size_t num_reachable = 0u;
1801 while (!tmp_stack->empty()) {
1802 BasicBlockId current_id = tmp_stack->back();
1803 tmp_stack->pop_back();
1804 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1805 DCHECK(current_bb != nullptr);
1806 ChildBlockIterator child_iter(current_bb, mir_graph);
1807 BasicBlock* child_bb = child_iter.Next();
1808 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1809 DCHECK(!child_bb->hidden);
1810 if (child_bb->visited || // Already processed, or
1811 (current_loop != nullptr && // outside current loop.
1812 !current_loop->IsBitSet(child_bb->id))) {
1813 continue;
1814 }
1815 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1816 candidate_reachable.SetBit(child_bb->id);
1817 tmp_stack->push_back(child_bb->id);
1818 num_reachable += 1u;
1819 }
1820 }
1821 }
1822 if (fall_back_num_reachable < num_reachable) {
1823 fall_back_num_reachable = num_reachable;
1824 fall_back = candidate;
1825 }
1826 }
1827 return fall_back;
1828}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001829
Vladimir Marko55fff042014-07-10 12:42:52 +01001830// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1831static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1832 ArenaBitVector* reachable,
1833 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1834 // NOTE: Loop heads indicated by the "visited" flag.
1835 DCHECK(tmp_stack->empty());
1836 reachable->ClearAllBits();
1837 tmp_stack->push_back(bb_id);
1838 while (!tmp_stack->empty()) {
1839 BasicBlockId current_id = tmp_stack->back();
1840 tmp_stack->pop_back();
1841 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1842 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001843 for (BasicBlockId pred_id : current_bb->predecessors) {
1844 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1845 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001846 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1847 reachable->SetBit(pred_bb->id);
1848 tmp_stack->push_back(pred_bb->id);
1849 }
1850 }
1851 }
1852}
1853
1854void MIRGraph::ComputeTopologicalSortOrder() {
1855 ScopedArenaAllocator allocator(&cu_->arena_stack);
1856 unsigned int num_blocks = GetNumBlocks();
1857
1858 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1859 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1860 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1861 size_t max_nested_loops = 0u;
1862 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1863 loop_exit_blocks.ClearAllBits();
1864
1865 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001866 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001867 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001868 if (bb->hidden == true) {
1869 continue;
1870 }
1871
Vladimir Marko55fff042014-07-10 12:42:52 +01001872 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001873
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001874 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001875 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001876 q.push(bb);
1877 }
1878 }
1879
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001880 // Clear the topological order arrays.
1881 topological_order_.clear();
1882 topological_order_.reserve(num_blocks);
1883 topological_order_loop_ends_.clear();
1884 topological_order_loop_ends_.resize(num_blocks, 0u);
1885 topological_order_indexes_.clear();
1886 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001887
1888 // Mark all blocks as unvisited.
1889 ClearAllVisitedFlags();
1890
1891 // For loop heads, keep track from which blocks they are reachable not going through other
1892 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1893 // in this set go into the loop body, the other children are jumping over the loop.
1894 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1895 loop_head_reachable_from.resize(num_blocks, nullptr);
1896 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1897 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1898
1899 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001900 BasicBlock* bb = nullptr;
1901 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001902 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001903 // Get top.
1904 bb = q.front();
1905 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001906 if (bb->visited) {
1907 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1908 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001909 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1910 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001911 DCHECK_EQ(loop_head_stack.back(), bb->id);
1912 loop_head_stack.pop_back();
1913 ArenaBitVector* reachable =
1914 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1915 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1916 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1917 q.push(GetBasicBlock(candidate_id));
1918 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1919 // so clearing the bit has no effect on the iterator.
1920 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001921 }
1922 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001923 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001924 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001925 } else {
1926 // Find the new loop head.
1927 AllNodesIterator iter(this);
1928 while (true) {
1929 BasicBlock* candidate = iter.Next();
1930 if (candidate == nullptr) {
1931 // We did not find a true loop head, fall back to a reachable block in any loop.
1932 ArenaBitVector* current_loop =
1933 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1934 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1935 &allocator, &tmp_stack);
1936 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1937 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1938 LOG(INFO) << "Topological sort order: Using fall-back in "
1939 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1940 << " @0x" << std::hex << bb->start_offset
1941 << ", num_blocks = " << std::dec << num_blocks;
1942 }
1943 break;
1944 }
1945 if (candidate->hidden || // Hidden, or
1946 candidate->visited || // already processed, or
1947 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1948 (!loop_head_stack.empty() && // outside current loop.
1949 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1950 continue;
1951 }
1952
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001953 for (BasicBlockId pred_id : candidate->predecessors) {
1954 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1955 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001956 if (pred_bb != candidate && !pred_bb->visited &&
1957 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001958 candidate = nullptr; // Set candidate to null to indicate failure.
1959 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001960 }
1961 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001962 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001963 bb = candidate;
1964 break;
1965 }
1966 }
1967 // Compute blocks from which the loop head is reachable and process those blocks first.
1968 ArenaBitVector* reachable =
1969 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1970 loop_head_reachable_from[bb->id] = reachable;
1971 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1972 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1973 loop_head_stack.push_back(bb->id);
1974 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001975 }
1976
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001977 DCHECK_EQ(bb->hidden, false);
1978 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001979 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00001980 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001981
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001982 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001983 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1984 topological_order_indexes_[bb->id] = idx;
1985 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001986
Vladimir Marko55fff042014-07-10 12:42:52 +01001987 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001988 ChildBlockIterator succIter(bb, this);
1989 BasicBlock* successor = succIter.Next();
1990 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001991 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001992 continue;
1993 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001994
Vladimir Marko55fff042014-07-10 12:42:52 +01001995 // One more predecessor was visited.
1996 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001997 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001998 if (loop_head_stack.empty() ||
1999 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2000 q.push(successor);
2001 } else {
2002 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2003 loop_exit_blocks.SetBit(successor->id);
2004 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002005 }
2006 }
2007 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002008
2009 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002010 topological_order_loop_head_stack_.clear();
2011 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002012 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002013 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002014}
2015
2016bool BasicBlock::IsExceptionBlock() const {
2017 if (block_type == kExceptionHandling) {
2018 return true;
2019 }
2020 return false;
2021}
2022
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002023ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2024 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2025 visited_taken_(false), have_successors_(false) {
2026 // Check if we actually do have successors.
2027 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2028 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002029 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002030 }
2031}
2032
2033BasicBlock* ChildBlockIterator::Next() {
2034 // We check if we have a basic block. If we don't we cannot get next child.
2035 if (basic_block_ == nullptr) {
2036 return nullptr;
2037 }
2038
2039 // If we haven't visited fallthrough, return that.
2040 if (visited_fallthrough_ == false) {
2041 visited_fallthrough_ = true;
2042
2043 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2044 if (result != nullptr) {
2045 return result;
2046 }
2047 }
2048
2049 // If we haven't visited taken, return that.
2050 if (visited_taken_ == false) {
2051 visited_taken_ = true;
2052
2053 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2054 if (result != nullptr) {
2055 return result;
2056 }
2057 }
2058
2059 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2060 if (have_successors_ == true) {
2061 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002062 auto end = basic_block_->successor_blocks.cend();
2063 while (successor_iter_ != end) {
2064 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2065 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002066 // If block was replaced by zero block, take next one.
2067 if (successor_block_info->block != NullBasicBlockId) {
2068 return mir_graph_->GetBasicBlock(successor_block_info->block);
2069 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002070 }
2071 }
2072
2073 // We do not have anything.
2074 return nullptr;
2075}
2076
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002077BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2078 MIRGraph* mir_graph = c_unit->mir_graph.get();
2079 return Copy(mir_graph);
2080}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002081
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002082BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2083 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002084
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002085 // We don't do a memcpy style copy here because it would lead to a lot of things
2086 // to clean up. Let us do it by hand instead.
2087 // Copy in taken and fallthrough.
2088 result_bb->fall_through = fall_through;
2089 result_bb->taken = taken;
2090
2091 // Copy successor links if needed.
2092 ArenaAllocator* arena = mir_graph->GetArena();
2093
2094 result_bb->successor_block_list_type = successor_block_list_type;
2095 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002096 result_bb->successor_blocks.reserve(successor_blocks.size());
2097 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2098 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2099 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002100 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002101 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002102 }
2103 }
2104
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002105 // Copy offset, method.
2106 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002107
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002108 // Now copy instructions.
2109 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2110 // Get a copy first.
2111 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002112
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002113 // Append it.
2114 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002115 }
2116
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002117 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002118}
2119
2120MIR* MIR::Copy(MIRGraph* mir_graph) {
2121 MIR* res = mir_graph->NewMIR();
2122 *res = *this;
2123
2124 // Remove links
2125 res->next = nullptr;
2126 res->bb = NullBasicBlockId;
2127 res->ssa_rep = nullptr;
2128
2129 return res;
2130}
2131
2132MIR* MIR::Copy(CompilationUnit* c_unit) {
2133 return Copy(c_unit->mir_graph.get());
2134}
2135
2136uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2137 // Default result.
2138 int res = 0;
2139
2140 // We are basically setting the iputs to their igets counterparts.
2141 switch (opcode) {
2142 case Instruction::IPUT:
2143 case Instruction::IPUT_OBJECT:
2144 case Instruction::IPUT_BOOLEAN:
2145 case Instruction::IPUT_BYTE:
2146 case Instruction::IPUT_CHAR:
2147 case Instruction::IPUT_SHORT:
2148 case Instruction::IPUT_QUICK:
2149 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002150 case Instruction::IPUT_BOOLEAN_QUICK:
2151 case Instruction::IPUT_BYTE_QUICK:
2152 case Instruction::IPUT_CHAR_QUICK:
2153 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002154 case Instruction::APUT:
2155 case Instruction::APUT_OBJECT:
2156 case Instruction::APUT_BOOLEAN:
2157 case Instruction::APUT_BYTE:
2158 case Instruction::APUT_CHAR:
2159 case Instruction::APUT_SHORT:
2160 case Instruction::SPUT:
2161 case Instruction::SPUT_OBJECT:
2162 case Instruction::SPUT_BOOLEAN:
2163 case Instruction::SPUT_BYTE:
2164 case Instruction::SPUT_CHAR:
2165 case Instruction::SPUT_SHORT:
2166 // Skip the VR containing what to store.
2167 res = 1;
2168 break;
2169 case Instruction::IPUT_WIDE:
2170 case Instruction::IPUT_WIDE_QUICK:
2171 case Instruction::APUT_WIDE:
2172 case Instruction::SPUT_WIDE:
2173 // Skip the two VRs containing what to store.
2174 res = 2;
2175 break;
2176 default:
2177 // Do nothing in the general case.
2178 break;
2179 }
2180
2181 return res;
2182}
2183
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002184/**
2185 * @brief Given a decoded instruction, it checks whether the instruction
2186 * sets a constant and if it does, more information is provided about the
2187 * constant being set.
2188 * @param ptr_value pointer to a 64-bit holder for the constant.
2189 * @param wide Updated by function whether a wide constant is being set by bytecode.
2190 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2191 */
2192bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2193 bool sets_const = true;
2194 int64_t value = vB;
2195
2196 DCHECK(ptr_value != nullptr);
2197 DCHECK(wide != nullptr);
2198
2199 switch (opcode) {
2200 case Instruction::CONST_4:
2201 case Instruction::CONST_16:
2202 case Instruction::CONST:
2203 *wide = false;
2204 value <<= 32; // In order to get the sign extend.
2205 value >>= 32;
2206 break;
2207 case Instruction::CONST_HIGH16:
2208 *wide = false;
2209 value <<= 48; // In order to get the sign extend.
2210 value >>= 32;
2211 break;
2212 case Instruction::CONST_WIDE_16:
2213 case Instruction::CONST_WIDE_32:
2214 *wide = true;
2215 value <<= 32; // In order to get the sign extend.
2216 value >>= 32;
2217 break;
2218 case Instruction::CONST_WIDE:
2219 *wide = true;
2220 value = vB_wide;
2221 break;
2222 case Instruction::CONST_WIDE_HIGH16:
2223 *wide = true;
2224 value <<= 48; // In order to get the sign extend.
2225 break;
2226 default:
2227 sets_const = false;
2228 break;
2229 }
2230
2231 if (sets_const) {
2232 *ptr_value = value;
2233 }
2234
2235 return sets_const;
2236}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002237
2238void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2239 // Reset flags for all MIRs in bb.
2240 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2241 mir->optimization_flags &= (~reset_flags);
2242 }
2243}
2244
Vladimir Markocb873d82014-12-08 15:16:54 +00002245void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002246 for (BasicBlockId pred_id : predecessors) {
2247 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2248 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002249
2250 // Sadly we have to go through the children by hand here.
2251 pred_bb->ReplaceChild(id, NullBasicBlockId);
2252 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002253 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002254
Vladimir Marko312eb252014-10-07 15:01:57 +01002255 // Mark as dead and hidden.
2256 block_type = kDead;
2257 hidden = true;
2258
2259 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2260 // are updated to know that they no longer have a parent.
2261 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2262 mir->bb = NullBasicBlockId;
2263 }
2264 first_mir_insn = nullptr;
2265 last_mir_insn = nullptr;
2266
2267 data_flow_info = nullptr;
2268
2269 // Erase this bb from all children's predecessors and kill unreachable children.
2270 ChildBlockIterator iter(this, mir_graph);
2271 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2272 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002273 }
2274
2275 // Remove links to children.
2276 fall_through = NullBasicBlockId;
2277 taken = NullBasicBlockId;
2278 successor_block_list_type = kNotUsed;
2279
2280 if (kIsDebugBuild) {
2281 if (catch_entry) {
2282 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2283 mir_graph->catches_.erase(start_offset);
2284 }
2285 }
2286}
2287
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002288bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2289 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2290 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2291 // then it is not live out of this BB.
2292 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2293
2294 int last_ssa_reg = -1;
2295
2296 // Walk through the MIRs backwards.
2297 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2298 // Get ssa rep.
2299 SSARepresentation *ssa_rep = mir->ssa_rep;
2300
2301 // Go through the defines for this MIR.
2302 for (int i = 0; i < ssa_rep->num_defs; i++) {
2303 DCHECK(ssa_rep->defs != nullptr);
2304
2305 // Get the ssa reg.
2306 int def_ssa_reg = ssa_rep->defs[i];
2307
2308 // Get dalvik reg.
2309 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2310
2311 // Compare dalvik regs.
2312 if (dalvik_reg == def_dalvik_reg) {
2313 // We found a def of the register that we are being asked about.
2314 // Remember it.
2315 last_ssa_reg = def_ssa_reg;
2316 }
2317 }
2318 }
2319
2320 if (last_ssa_reg == -1) {
2321 // If we get to this point we couldn't find a define of register user asked about.
2322 // Let's assume the user knows what he's doing so we can be safe and say that if we
2323 // couldn't find a def, it is live out.
2324 return true;
2325 }
2326
2327 // If it is not -1, we found a match, is it ssa_reg?
2328 return (ssa_reg == last_ssa_reg);
2329}
2330
2331bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2332 // We need to check taken, fall_through, and successor_blocks to replace.
2333 bool found = false;
2334 if (taken == old_bb) {
2335 taken = new_bb;
2336 found = true;
2337 }
2338
2339 if (fall_through == old_bb) {
2340 fall_through = new_bb;
2341 found = true;
2342 }
2343
2344 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002345 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002346 if (successor_block_info->block == old_bb) {
2347 successor_block_info->block = new_bb;
2348 found = true;
2349 }
2350 }
2351 }
2352
2353 return found;
2354}
2355
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002356void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2357 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2358 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002359 // It's faster to move the back() to *pos than erase(pos).
2360 *pos = predecessors.back();
2361 predecessors.pop_back();
2362 size_t idx = std::distance(predecessors.begin(), pos);
2363 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2364 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2365 break;
2366 }
2367 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2368 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2369 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2370 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2371 mir->ssa_rep->num_uses = predecessors.size();
2372 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002373}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002374
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002375void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2376 DCHECK_NE(new_pred, NullBasicBlockId);
2377 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002378 DCHECK(pos != predecessors.end());
2379 *pos = new_pred;
2380 size_t idx = std::distance(predecessors.begin(), pos);
2381 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2382 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2383 break;
2384 }
2385 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2386 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002387 }
2388}
2389
2390// Create a new basic block with block_id as num_blocks_ that is
2391// post-incremented.
2392BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002393 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2394 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002395 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002396 return res;
2397}
2398
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002399void MIRGraph::CalculateBasicBlockInformation() {
2400 PassDriverMEPostOpt driver(cu_);
2401 driver.Launch();
2402}
2403
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002404int MIR::DecodedInstruction::FlagsOf() const {
2405 // Calculate new index.
2406 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2407
2408 // Check if it is an extended or not.
2409 if (idx < 0) {
2410 return Instruction::FlagsOf(opcode);
2411 }
2412
2413 // For extended, we use a switch.
2414 switch (static_cast<int>(opcode)) {
2415 case kMirOpPhi:
2416 return Instruction::kContinue;
2417 case kMirOpCopy:
2418 return Instruction::kContinue;
2419 case kMirOpFusedCmplFloat:
2420 return Instruction::kContinue | Instruction::kBranch;
2421 case kMirOpFusedCmpgFloat:
2422 return Instruction::kContinue | Instruction::kBranch;
2423 case kMirOpFusedCmplDouble:
2424 return Instruction::kContinue | Instruction::kBranch;
2425 case kMirOpFusedCmpgDouble:
2426 return Instruction::kContinue | Instruction::kBranch;
2427 case kMirOpFusedCmpLong:
2428 return Instruction::kContinue | Instruction::kBranch;
2429 case kMirOpNop:
2430 return Instruction::kContinue;
2431 case kMirOpNullCheck:
2432 return Instruction::kContinue | Instruction::kThrow;
2433 case kMirOpRangeCheck:
2434 return Instruction::kContinue | Instruction::kThrow;
2435 case kMirOpDivZeroCheck:
2436 return Instruction::kContinue | Instruction::kThrow;
2437 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002438 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002439 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002440 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002441 case kMirOpSelect:
2442 return Instruction::kContinue;
2443 case kMirOpConstVector:
2444 return Instruction::kContinue;
2445 case kMirOpMoveVector:
2446 return Instruction::kContinue;
2447 case kMirOpPackedMultiply:
2448 return Instruction::kContinue;
2449 case kMirOpPackedAddition:
2450 return Instruction::kContinue;
2451 case kMirOpPackedSubtract:
2452 return Instruction::kContinue;
2453 case kMirOpPackedShiftLeft:
2454 return Instruction::kContinue;
2455 case kMirOpPackedSignedShiftRight:
2456 return Instruction::kContinue;
2457 case kMirOpPackedUnsignedShiftRight:
2458 return Instruction::kContinue;
2459 case kMirOpPackedAnd:
2460 return Instruction::kContinue;
2461 case kMirOpPackedOr:
2462 return Instruction::kContinue;
2463 case kMirOpPackedXor:
2464 return Instruction::kContinue;
2465 case kMirOpPackedAddReduce:
2466 return Instruction::kContinue;
2467 case kMirOpPackedReduce:
2468 return Instruction::kContinue;
2469 case kMirOpPackedSet:
2470 return Instruction::kContinue;
2471 case kMirOpReserveVectorRegisters:
2472 return Instruction::kContinue;
2473 case kMirOpReturnVectorRegisters:
2474 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002475 case kMirOpMemBarrier:
2476 return Instruction::kContinue;
2477 case kMirOpPackedArrayGet:
2478 return Instruction::kContinue | Instruction::kThrow;
2479 case kMirOpPackedArrayPut:
2480 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002481 case kMirOpMaddInt:
2482 case kMirOpMsubInt:
2483 case kMirOpMaddLong:
2484 case kMirOpMsubLong:
2485 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002486 default:
2487 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2488 return 0;
2489 }
2490}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002491} // namespace art