blob: 0f7d45df79d1f3d56b1cb8a08056f692ef251584 [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>
Andreas Gampecee97e52014-12-19 15:30:11 -080021#include <unistd.h>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000022
Ian Rogerse77493c2014-08-20 15:08:45 -070023#include "base/bit_vector-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080024#include "base/logging.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070025#include "base/stl_util.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080026#include "base/stringprintf.h"
27#include "compiler_ir.h"
buzbee311ca162013-02-28 15:56:43 -080028#include "dex_file-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080029#include "dex_flags.h"
Ian Rogers29a26482014-05-02 15:27:29 -070030#include "dex_instruction-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080031#include "driver/compiler_driver.h"
32#include "driver/dex_compilation_unit.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080033#include "dex/quick/quick_compiler.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000034#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070035#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070036#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010037#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000038
buzbee311ca162013-02-28 15:56:43 -080039namespace art {
40
41#define MAX_PATTERN_LEN 5
42
buzbee1fd33462013-03-25 13:40:45 -070043const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
44 "Phi",
45 "Copy",
46 "FusedCmplFloat",
47 "FusedCmpgFloat",
48 "FusedCmplDouble",
49 "FusedCmpgDouble",
50 "FusedCmpLong",
51 "Nop",
52 "OpNullCheck",
53 "OpRangeCheck",
54 "OpDivZeroCheck",
55 "Check1",
56 "Check2",
57 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040058 "ConstVector",
59 "MoveVector",
60 "PackedMultiply",
61 "PackedAddition",
62 "PackedSubtract",
63 "PackedShiftLeft",
64 "PackedSignedShiftRight",
65 "PackedUnsignedShiftRight",
66 "PackedAnd",
67 "PackedOr",
68 "PackedXor",
69 "PackedAddReduce",
70 "PackedReduce",
71 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070072 "ReserveVectorRegisters",
73 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070074 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070075 "PackedArrayGet",
76 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080077 "MaddInt",
78 "MsubInt",
79 "MaddLong",
80 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070081};
82
buzbee862a7602013-04-05 10:58:54 -070083MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070084 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010085 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070086 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010087 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
88 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Vladimir Marko1c6ea442014-12-19 18:11:35 +000089 vreg_to_ssa_map_(NULL),
90 ssa_last_defs_(NULL),
buzbee311ca162013-02-28 15:56:43 -080091 is_constant_v_(NULL),
92 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010093 use_counts_(arena->Adapter()),
94 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080095 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070096 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010097 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000098 domination_up_to_date_(false),
99 mir_ssa_rep_up_to_date_(false),
100 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100101 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
102 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
103 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
104 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
105 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
106 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
107 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100108 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800109 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000110 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100111 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800112 try_block_addr_(NULL),
113 entry_block_(NULL),
114 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800115 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100116 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100117 m_units_(arena->Adapter()),
118 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800119 current_method_(kInvalidEntry),
120 current_offset_(kInvalidEntry),
121 def_count_(0),
122 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700123 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100124 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700125 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700126 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
127 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700128 arena_(arena),
129 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800130 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800131 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700132 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
133 requested_backend_temp_(false),
134 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000135 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000136 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100137 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
138 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
139 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000140 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000141 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100142 use_counts_.reserve(256);
143 raw_use_counts_.reserve(256);
144 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700145 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700146
147
148 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
149 // X86 requires a temp to keep track of the method address.
150 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
151 // this needs to be updated to reserve 0 temps for BE.
152 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
153 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
154 } else {
155 // Other architectures do not have a known lower bound for non-special temps.
156 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
157 max_available_non_special_compiler_temps_ = 0;
158 reserved_temps_for_backend_ = 0;
159 }
buzbee311ca162013-02-28 15:56:43 -0800160}
161
Ian Rogers6282dc12013-04-18 15:54:02 -0700162MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100163 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700164 STLDeleteElements(&m_units_);
165}
166
buzbee311ca162013-02-28 15:56:43 -0800167/*
168 * Parse an instruction, return the length of the instruction
169 */
Ian Rogers29a26482014-05-02 15:27:29 -0700170int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
171 const Instruction* inst = Instruction::At(code_ptr);
172 decoded_instruction->opcode = inst->Opcode();
173 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
174 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
175 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
176 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
177 if (inst->HasVarArgs()) {
178 inst->GetVarArgs(decoded_instruction->arg);
179 }
180 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800181}
182
183
184/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700185BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700186 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700187 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800188 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400189 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800190 while (insn) {
191 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700192 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800193 insn = insn->next;
194 }
195 if (insn == NULL) {
196 LOG(FATAL) << "Break split failed";
197 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400198 // Now insn is at the instruction where we want to split, namely
199 // insn will be the first instruction of the "bottom" block.
200 // Similarly, prev will be the last instruction of the "top" block
201
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100202 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800203
204 bottom_block->start_offset = code_offset;
205 bottom_block->first_mir_insn = insn;
206 bottom_block->last_mir_insn = orig_block->last_mir_insn;
207
Junmo Park90223cc2014-08-04 18:51:21 +0900208 /* If this block was terminated by a return, conditional branch or throw,
209 * the flag needs to go with the bottom block
210 */
buzbee311ca162013-02-28 15:56:43 -0800211 bottom_block->terminated_by_return = orig_block->terminated_by_return;
212 orig_block->terminated_by_return = false;
213
Junmo Park90223cc2014-08-04 18:51:21 +0900214 bottom_block->conditional_branch = orig_block->conditional_branch;
215 orig_block->conditional_branch = false;
216
217 bottom_block->explicit_throw = orig_block->explicit_throw;
218 orig_block->explicit_throw = false;
219
buzbee311ca162013-02-28 15:56:43 -0800220 /* Handle the taken path */
221 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700222 if (bottom_block->taken != NullBasicBlockId) {
223 orig_block->taken = NullBasicBlockId;
224 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100225 bb_taken->ErasePredecessor(orig_block->id);
226 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800227 }
228
229 /* Handle the fallthrough path */
230 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700231 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100232 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700233 if (bottom_block->fall_through != NullBasicBlockId) {
234 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100235 bb_fall_through->ErasePredecessor(orig_block->id);
236 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800237 }
238
239 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700240 if (orig_block->successor_block_list_type != kNotUsed) {
241 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700243 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100244 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
245 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700246 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700247 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100248 bb->ErasePredecessor(orig_block->id);
249 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700250 }
buzbee311ca162013-02-28 15:56:43 -0800251 }
252 }
253
buzbee0d829482013-10-11 15:24:55 -0700254 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700255 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800256
buzbee311ca162013-02-28 15:56:43 -0800257 /*
258 * Update the immediate predecessor block pointer so that outgoing edges
259 * can be applied to the proper block.
260 */
261 if (immed_pred_block_p) {
262 DCHECK_EQ(*immed_pred_block_p, orig_block);
263 *immed_pred_block_p = bottom_block;
264 }
buzbeeb48819d2013-09-14 16:15:25 -0700265
266 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000267 DCHECK(insn != nullptr);
268 DCHECK(insn != orig_block->first_mir_insn);
269 DCHECK(insn == bottom_block->first_mir_insn);
270 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100271 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400272 // Scan the "bottom" instructions, remapping them to the
273 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000274 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400275 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100276 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000277 while (p != bottom_block->last_mir_insn) {
278 p = p->next;
279 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700280 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700281 int opcode = p->dalvikInsn.opcode;
282 /*
283 * Some messiness here to ensure that we only enter real opcodes and only the
284 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000285 * CHECK and work portions. Since the 2nd half of a split operation is always
286 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700287 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700288 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400289 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
290 // At first glance the instructions should all be mapped to orig_block.
291 // However, multiple instructions may correspond to the same dex, hence an earlier
292 // instruction may have already moved the mapping for dex to bottom_block.
293 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100294 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700295 }
buzbeeb48819d2013-09-14 16:15:25 -0700296 }
297
buzbee311ca162013-02-28 15:56:43 -0800298 return bottom_block;
299}
300
301/*
302 * Given a code offset, find out the block that starts with it. If the offset
303 * is in the middle of an existing block, split it into two. If immed_pred_block_p
304 * is not non-null and is the block being split, update *immed_pred_block_p to
305 * point to the bottom block so that outgoing edges can be set up properly
306 * (by the caller)
307 * Utilizes a map for fast lookup of the typical cases.
308 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700309BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700310 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700311 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700312 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800313 }
buzbeeb48819d2013-09-14 16:15:25 -0700314
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100315 int block_id = dex_pc_to_block_map_[code_offset];
316 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700317
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700318 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700319 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700320 return bb;
321 }
buzbee311ca162013-02-28 15:56:43 -0800322
buzbeeb48819d2013-09-14 16:15:25 -0700323 // No direct hit.
324 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700325 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800326 }
327
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700328 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700329 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700330 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700331 }
332
333 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100334 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800335 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100336 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800337 return bb;
338}
339
buzbeeb48819d2013-09-14 16:15:25 -0700340
buzbee311ca162013-02-28 15:56:43 -0800341/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700342void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800343 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700344 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800345
346 if (tries_size == 0) {
347 return;
348 }
349
350 for (int i = 0; i < tries_size; i++) {
351 const DexFile::TryItem* pTry =
352 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700353 DexOffset start_offset = pTry->start_addr_;
354 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800355 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700356 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800357 }
358 }
359
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700360 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700361 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800362 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
363 for (uint32_t idx = 0; idx < handlers_size; idx++) {
364 CatchHandlerIterator iterator(handlers_ptr);
365 for (; iterator.HasNext(); iterator.Next()) {
366 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700367 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800368 }
369 handlers_ptr = iterator.EndDataPointer();
370 }
371}
372
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100373bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
374 NarrowDexOffset catch_offset) {
375 // Catches for monitor-exit during stack unwinding have the pattern
376 // move-exception (move)* (goto)? monitor-exit throw
377 // In the currently generated dex bytecode we see these catching a bytecode range including
378 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
379 // it's the case for a given monitor-exit and catch block so that we can ignore it.
380 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
381 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
382 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700383 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100384 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
385 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700386 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100387 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
388 if (check_insn->VRegA_11x() == monitor_reg) {
389 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
390 return false;
391 }
392 check_insn = check_insn->Next();
393 while (true) {
394 int dest = -1;
395 bool wide = false;
396 switch (check_insn->Opcode()) {
397 case Instruction::MOVE_WIDE:
398 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700399 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100400 case Instruction::MOVE_OBJECT:
401 case Instruction::MOVE:
402 dest = check_insn->VRegA_12x();
403 break;
404
405 case Instruction::MOVE_WIDE_FROM16:
406 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700407 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100408 case Instruction::MOVE_OBJECT_FROM16:
409 case Instruction::MOVE_FROM16:
410 dest = check_insn->VRegA_22x();
411 break;
412
413 case Instruction::MOVE_WIDE_16:
414 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700415 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100416 case Instruction::MOVE_OBJECT_16:
417 case Instruction::MOVE_16:
418 dest = check_insn->VRegA_32x();
419 break;
420
421 case Instruction::GOTO:
422 case Instruction::GOTO_16:
423 case Instruction::GOTO_32:
424 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700425 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100426 default:
427 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
428 check_insn->VRegA_11x() == monitor_reg;
429 }
430
431 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
432 return false;
433 }
434
435 check_insn = check_insn->Next();
436 }
437}
438
buzbee311ca162013-02-28 15:56:43 -0800439/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700440BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
441 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700442 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700443 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800444 switch (insn->dalvikInsn.opcode) {
445 case Instruction::GOTO:
446 case Instruction::GOTO_16:
447 case Instruction::GOTO_32:
448 target += insn->dalvikInsn.vA;
449 break;
450 case Instruction::IF_EQ:
451 case Instruction::IF_NE:
452 case Instruction::IF_LT:
453 case Instruction::IF_GE:
454 case Instruction::IF_GT:
455 case Instruction::IF_LE:
456 cur_block->conditional_branch = true;
457 target += insn->dalvikInsn.vC;
458 break;
459 case Instruction::IF_EQZ:
460 case Instruction::IF_NEZ:
461 case Instruction::IF_LTZ:
462 case Instruction::IF_GEZ:
463 case Instruction::IF_GTZ:
464 case Instruction::IF_LEZ:
465 cur_block->conditional_branch = true;
466 target += insn->dalvikInsn.vB;
467 break;
468 default:
469 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
470 }
buzbeeb48819d2013-09-14 16:15:25 -0700471 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700472 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800473 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700474 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100475 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800476
477 /* Always terminate the current block for conditional branches */
478 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700479 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800480 /* create */
481 true,
482 /* immed_pred_block_p */
483 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700484 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100485 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800486 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700487 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800488 }
489 return cur_block;
490}
491
492/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800493BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
494 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700495 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800496 const uint16_t* switch_data =
497 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
498 int size;
499 const int* keyTable;
500 const int* target_table;
501 int i;
502 int first_key;
503
504 /*
505 * Packed switch data format:
506 * ushort ident = 0x0100 magic value
507 * ushort size number of entries in the table
508 * int first_key first (and lowest) switch case value
509 * int targets[size] branch targets, relative to switch opcode
510 *
511 * Total size is (4+size*2) 16-bit code units.
512 */
513 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
514 DCHECK_EQ(static_cast<int>(switch_data[0]),
515 static_cast<int>(Instruction::kPackedSwitchSignature));
516 size = switch_data[1];
517 first_key = switch_data[2] | (switch_data[3] << 16);
518 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700519 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800520 /*
521 * Sparse switch data format:
522 * ushort ident = 0x0200 magic value
523 * ushort size number of entries in the table; > 0
524 * int keys[size] keys, sorted low-to-high; 32-bit aligned
525 * int targets[size] branch targets, relative to switch opcode
526 *
527 * Total size is (2+size*4) 16-bit code units.
528 */
529 } else {
530 DCHECK_EQ(static_cast<int>(switch_data[0]),
531 static_cast<int>(Instruction::kSparseSwitchSignature));
532 size = switch_data[1];
533 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
534 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700535 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800536 }
537
buzbee0d829482013-10-11 15:24:55 -0700538 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800539 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700540 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800541 }
buzbee0d829482013-10-11 15:24:55 -0700542 cur_block->successor_block_list_type =
543 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100544 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800545
546 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700547 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
548 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700549 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700550 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000551 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700552 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800553 successor_block_info->key =
554 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
555 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100556 cur_block->successor_blocks.push_back(successor_block_info);
557 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800558 }
559
560 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700561 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
562 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700563 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100564 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800565 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800566}
567
568/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700569BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
570 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700571 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700572 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700573 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800574 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800575
576 /* In try block */
577 if (in_try_block) {
578 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
579
buzbee0d829482013-10-11 15:24:55 -0700580 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800581 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
582 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700583 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800584 }
585
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700586 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700587 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
588 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100589 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
590 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
591 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
592 continue;
593 }
594 if (cur_block->successor_block_list_type == kNotUsed) {
595 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100596 }
buzbee311ca162013-02-28 15:56:43 -0800597 catch_block->catch_entry = true;
598 if (kIsDebugBuild) {
599 catches_.insert(catch_block->start_offset);
600 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700601 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000602 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700603 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800604 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100605 cur_block->successor_blocks.push_back(successor_block_info);
606 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800607 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100608 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
609 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100610 bool build_all_edges =
611 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100612 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100613 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700614 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800615 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100616 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800617 }
618
buzbee17189ac2013-11-08 11:07:02 -0800619 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800620 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700621 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700622 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700623 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800624 }
625 if (!in_try_block) {
626 // Don't split a THROW that can't rethrow - we're done.
627 return cur_block;
628 }
629 }
630
buzbee17189ac2013-11-08 11:07:02 -0800631 if (!build_all_edges) {
632 /*
633 * Even though there is an exception edge here, control cannot return to this
634 * method. Thus, for the purposes of dataflow analysis and optimization, we can
635 * ignore the edge. Doing this reduces compile time, and increases the scope
636 * of the basic-block level optimization pass.
637 */
638 return cur_block;
639 }
640
buzbee311ca162013-02-28 15:56:43 -0800641 /*
642 * Split the potentially-throwing instruction into two parts.
643 * The first half will be a pseudo-op that captures the exception
644 * edges and terminates the basic block. It always falls through.
645 * Then, create a new basic block that begins with the throwing instruction
646 * (minus exceptions). Note: this new basic block must NOT be entered into
647 * the block_map. If the potentially-throwing instruction is the target of a
648 * future branch, we need to find the check psuedo half. The new
649 * basic block containing the work portion of the instruction should
650 * only be entered via fallthrough from the block containing the
651 * pseudo exception edge MIR. Note also that this new block is
652 * not automatically terminated after the work portion, and may
653 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700654 *
655 * Note also that the dex_pc_to_block_map_ entry for the potentially
656 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800657 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100658 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800659 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700660 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100661 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700662 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800663 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700664 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700665 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800666 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700667 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800668 return new_block;
669}
670
671/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
672void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700673 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700674 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800675 current_code_item_ = code_item;
676 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
677 current_method_ = m_units_.size();
678 current_offset_ = 0;
679 // TODO: will need to snapshot stack image and use that as the mir context identification.
680 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000681 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
682 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800683 const uint16_t* code_ptr = current_code_item_->insns_;
684 const uint16_t* code_end =
685 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
686
687 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700688 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100689 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
690 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 -0700691
buzbee311ca162013-02-28 15:56:43 -0800692 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700693 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
694 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800695
696 // If this is the first method, set up default entry and exit blocks.
697 if (current_method_ == 0) {
698 DCHECK(entry_block_ == NULL);
699 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000700 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700701 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100702 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700703 DCHECK_EQ(null_block->id, NullBasicBlockId);
704 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100705 entry_block_ = CreateNewBB(kEntryBlock);
706 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800707 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
708 cu_->dex_file = &dex_file;
709 cu_->class_def_idx = class_def_idx;
710 cu_->method_idx = method_idx;
711 cu_->access_flags = access_flags;
712 cu_->invoke_type = invoke_type;
713 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800714 } else {
715 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
716 /*
717 * Will need to manage storage for ins & outs, push prevous state and update
718 * insert point.
719 */
720 }
721
722 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100723 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700724 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800725 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700726 // TODO: for inlining support, insert at the insert point rather than entry block.
727 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100728 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800729
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000730 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800731 ProcessTryCatchBlocks();
732
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000733 uint64_t merged_df_flags = 0u;
734
buzbee311ca162013-02-28 15:56:43 -0800735 /* Parse all instructions and put them into containing basic blocks */
736 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700737 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800738 insn->offset = current_offset_;
739 insn->m_unit_index = current_method_;
740 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800741 Instruction::Code opcode = insn->dalvikInsn.opcode;
742 if (opcode_count_ != NULL) {
743 opcode_count_[static_cast<int>(opcode)]++;
744 }
745
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700746 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800747 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800748
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700749 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000750 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800751
752 if (df_flags & DF_HAS_DEFS) {
753 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
754 }
755
buzbee1da1e2f2013-11-15 13:37:01 -0800756 if (df_flags & DF_LVN) {
757 cur_block->use_lvn = true; // Run local value numbering on this basic block.
758 }
759
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700760 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700761 if (opcode == Instruction::NOP) {
762 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
763 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
764 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
765 uint16_t following_raw_instruction = code_ptr[1];
766 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
767 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
768 (following_raw_instruction == Instruction::kArrayDataSignature)) {
769 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
770 }
771 }
772 if (width == 1) {
773 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700774 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700775 } else {
buzbee0d829482013-10-11 15:24:55 -0700776 DCHECK(cur_block->fall_through == NullBasicBlockId);
777 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800778 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700779 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800780 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700781 }
782 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700783 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700784 }
785
buzbeeb48819d2013-09-14 16:15:25 -0700786 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100787 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700788
buzbee27247762013-07-28 12:03:58 -0700789 code_ptr += width;
790
buzbee311ca162013-02-28 15:56:43 -0800791 if (flags & Instruction::kBranch) {
792 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
793 width, flags, code_ptr, code_end);
794 } else if (flags & Instruction::kReturn) {
795 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700796 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100797 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800798 /*
799 * Terminate the current block if there are instructions
800 * afterwards.
801 */
802 if (code_ptr < code_end) {
803 /*
804 * Create a fallthrough block for real instructions
805 * (incl. NOP).
806 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700807 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800808 }
809 } else if (flags & Instruction::kThrow) {
810 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
811 code_ptr, code_end);
812 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800813 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800814 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700815 if (verify_flags & Instruction::kVerifyVarArgRange ||
816 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800817 /*
818 * The Quick backend's runtime model includes a gap between a method's
819 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
820 * which spans the gap is somewhat complicated, and should not happen
821 * in normal usage of dx. Punt to the interpreter.
822 */
823 int first_reg_in_range = insn->dalvikInsn.vC;
824 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
825 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
826 punt_to_interpreter_ = true;
827 }
828 }
buzbee311ca162013-02-28 15:56:43 -0800829 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700830 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
831 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800832 if (next_block) {
833 /*
834 * The next instruction could be the target of a previously parsed
835 * forward branch so a block is already created. If the current
836 * instruction is not an unconditional branch, connect them through
837 * the fall-through link.
838 */
buzbee0d829482013-10-11 15:24:55 -0700839 DCHECK(cur_block->fall_through == NullBasicBlockId ||
840 GetBasicBlock(cur_block->fall_through) == next_block ||
841 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800842
buzbee0d829482013-10-11 15:24:55 -0700843 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
844 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100845 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800846 }
847 cur_block = next_block;
848 }
849 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000850 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000851
buzbee311ca162013-02-28 15:56:43 -0800852 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
853 DumpCFG("/sdcard/1_post_parse_cfg/", true);
854 }
855
856 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700857 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800858 }
859}
860
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700861void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800862 DCHECK(opcode_count_ != NULL);
863 LOG(INFO) << "Opcode Count";
864 for (int i = 0; i < kNumPackedOpcodes; i++) {
865 if (opcode_count_[i] != 0) {
866 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
867 << " " << opcode_count_[i];
868 }
869 }
870}
871
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700872uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
873 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
874 return oat_data_flow_attributes_[opcode];
875}
876
877uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
878 DCHECK(mir != nullptr);
879 Instruction::Code opcode = mir->dalvikInsn.opcode;
880 return GetDataFlowAttributes(opcode);
881}
882
Andreas Gampecee97e52014-12-19 15:30:11 -0800883// The path can easily surpass FS limits because of parameters etc. Use pathconf to get FS
884// restrictions here. Note that a successful invocation will return an actual value. If the path
885// is too long for some reason, the return will be ENAMETOOLONG. Then cut off part of the name.
886//
887// It's possible the path is not valid, or some other errors appear. In that case return false.
888static bool CreateDumpFile(std::string& fname, const char* dir_prefix, NarrowDexOffset start_offset,
889 const char *suffix, int nr, std::string* output) {
890 std::string dir = StringPrintf("./%s", dir_prefix);
891 int64_t max_name_length = pathconf(dir.c_str(), _PC_NAME_MAX);
892 if (max_name_length <= 0) {
893 PLOG(ERROR) << "Could not get file name restrictions for " << dir;
894 return false;
895 }
896
897 std::string name = StringPrintf("%s%x%s_%d.dot", fname.c_str(), start_offset,
898 suffix == nullptr ? "" : suffix, nr);
899 std::string fpath;
900 if (static_cast<int64_t>(name.size()) > max_name_length) {
901 std::string suffix_str = StringPrintf("_%d.dot", nr);
902 name = name.substr(0, static_cast<size_t>(max_name_length) - suffix_str.size()) + suffix_str;
903 }
904 // Sanity check.
905 DCHECK_LE(name.size(), static_cast<size_t>(max_name_length));
906
907 *output = StringPrintf("%s%s", dir_prefix, name.c_str());
908 return true;
909}
910
buzbee311ca162013-02-28 15:56:43 -0800911// TODO: use a configurable base prefix, and adjust callers to supply pass name.
912/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800913void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800914 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700915 static AtomicInteger cnt(0);
916
917 // Increment counter to get a unique file number.
918 cnt++;
Andreas Gampecee97e52014-12-19 15:30:11 -0800919 int nr = cnt.LoadRelaxed();
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700920
buzbee311ca162013-02-28 15:56:43 -0800921 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
922 ReplaceSpecialChars(fname);
Andreas Gampecee97e52014-12-19 15:30:11 -0800923 std::string fpath;
924 if (!CreateDumpFile(fname, dir_prefix, GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
925 suffix, nr, &fpath)) {
926 LOG(ERROR) << "Could not create dump file name for " << fname;
927 return;
928 }
929 file = fopen(fpath.c_str(), "w");
buzbee311ca162013-02-28 15:56:43 -0800930 if (file == NULL) {
Andreas Gampecee97e52014-12-19 15:30:11 -0800931 PLOG(ERROR) << "Could not open " << fpath << " for DumpCFG.";
buzbee311ca162013-02-28 15:56:43 -0800932 return;
933 }
934 fprintf(file, "digraph G {\n");
935
936 fprintf(file, " rankdir=TB\n");
937
938 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
939 int idx;
940
941 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100942 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700943 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700944 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800945 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700946 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800947 if (bb->block_type == kEntryBlock) {
948 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
949 } else if (bb->block_type == kExitBlock) {
950 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
951 } else if (bb->block_type == kDalvikByteCode) {
952 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
953 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700954 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800955 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
956 bb->first_mir_insn ? " | " : " ");
957 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
958 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800959 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400960 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700961 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
962 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400963 extended_mir_op_names_[opcode - kMirOpFirst],
964 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
965 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700966 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700967 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700968 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100969 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
970 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800971 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400972 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800973 }
974 fprintf(file, " }\"];\n\n");
975 } else if (bb->block_type == kExceptionHandling) {
976 char block_name[BLOCK_NAME_LEN];
977
978 GetBlockName(bb, block_name);
979 fprintf(file, " %s [shape=invhouse];\n", block_name);
980 }
981
982 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
983
buzbee0d829482013-10-11 15:24:55 -0700984 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800985 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700986 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800987 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
988 block_name1, block_name2);
989 }
buzbee0d829482013-10-11 15:24:55 -0700990 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800991 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700992 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800993 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
994 }
995
buzbee0d829482013-10-11 15:24:55 -0700996 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800997 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
998 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700999 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -08001000
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001001 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -08001002 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001003 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001004 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001005 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001006 succ_id,
buzbee311ca162013-02-28 15:56:43 -08001007 successor_block_info->key,
1008 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001009 (succ_id != last_succ_id) ? " | " : " ");
1010 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -08001011 }
1012 fprintf(file, " }\"];\n\n");
1013
1014 GetBlockName(bb, block_name1);
1015 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1016 block_name1, bb->start_offset, bb->id);
1017
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001018 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001019 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001020 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001021 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001022
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001023 GetBlockName(dest_block, block_name2);
1024 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1025 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001026 }
1027 }
1028 fprintf(file, "\n");
1029
1030 if (cu_->verbose) {
1031 /* Display the dominator tree */
1032 GetBlockName(bb, block_name1);
1033 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1034 block_name1, block_name1);
1035 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001036 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001037 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1038 }
1039 }
1040 }
1041 fprintf(file, "}\n");
1042 fclose(file);
1043}
1044
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001045/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001046void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001047 // Insert it after the last MIR.
1048 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001049}
1050
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001051void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1052 // Insert it after the last MIR.
1053 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1054}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001055
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001056void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1057 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1058 MIR* new_mir = *it;
1059
1060 // Add a copy of each MIR.
1061 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1062 }
buzbee1fd33462013-03-25 13:40:45 -07001063}
1064
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001065/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001066void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001067 InsertMIRListAfter(current_mir, new_mir, new_mir);
1068}
buzbee1fd33462013-03-25 13:40:45 -07001069
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001070void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1071 // If no MIR, we are done.
1072 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1073 return;
buzbee1fd33462013-03-25 13:40:45 -07001074 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001075
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001076 // If insert_after is null, assume BB is empty.
1077 if (insert_after == nullptr) {
1078 first_mir_insn = first_list_mir;
1079 last_mir_insn = last_list_mir;
1080 last_list_mir->next = nullptr;
1081 } else {
1082 MIR* after_list = insert_after->next;
1083 insert_after->next = first_list_mir;
1084 last_list_mir->next = after_list;
1085 if (after_list == nullptr) {
1086 last_mir_insn = last_list_mir;
1087 }
1088 }
1089
1090 // Set this BB to be the basic block of the MIRs.
1091 MIR* last = last_list_mir->next;
1092 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1093 mir->bb = id;
1094 }
1095}
1096
1097/* Insert an MIR instruction to the head of a basic block. */
1098void BasicBlock::PrependMIR(MIR* mir) {
1099 InsertMIRListBefore(first_mir_insn, mir, mir);
1100}
1101
1102void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1103 // Insert it before the first MIR.
1104 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1105}
1106
1107void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1108 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1109 MIR* mir = *it;
1110
1111 InsertMIRListBefore(first_mir_insn, mir, mir);
1112 }
1113}
1114
1115/* Insert a MIR instruction before the specified MIR. */
1116void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1117 // Insert as a single element list.
1118 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001119}
1120
1121MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1122 MIR* current = first_mir_insn;
1123
1124 while (current != nullptr) {
1125 MIR* next = current->next;
1126
1127 if (next == mir) {
1128 return current;
1129 }
1130
1131 current = next;
1132 }
1133
1134 return nullptr;
1135}
1136
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001137void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1138 // If no MIR, we are done.
1139 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1140 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001141 }
1142
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001143 // If insert_before is null, assume BB is empty.
1144 if (insert_before == nullptr) {
1145 first_mir_insn = first_list_mir;
1146 last_mir_insn = last_list_mir;
1147 last_list_mir->next = nullptr;
1148 } else {
1149 if (first_mir_insn == insert_before) {
1150 last_list_mir->next = first_mir_insn;
1151 first_mir_insn = first_list_mir;
1152 } else {
1153 // Find the preceding MIR.
1154 MIR* before_list = FindPreviousMIR(insert_before);
1155 DCHECK(before_list != nullptr);
1156 before_list->next = first_list_mir;
1157 last_list_mir->next = insert_before;
1158 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001159 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001160
1161 // Set this BB to be the basic block of the MIRs.
1162 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1163 mir->bb = id;
1164 }
1165}
1166
1167bool BasicBlock::RemoveMIR(MIR* mir) {
1168 // Remove as a single element list.
1169 return RemoveMIRList(mir, mir);
1170}
1171
1172bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1173 if (first_list_mir == nullptr) {
1174 return false;
1175 }
1176
1177 // Try to find the MIR.
1178 MIR* before_list = nullptr;
1179 MIR* after_list = nullptr;
1180
1181 // If we are removing from the beginning of the MIR list.
1182 if (first_mir_insn == first_list_mir) {
1183 before_list = nullptr;
1184 } else {
1185 before_list = FindPreviousMIR(first_list_mir);
1186 if (before_list == nullptr) {
1187 // We did not find the mir.
1188 return false;
1189 }
1190 }
1191
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001192 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001193 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001194 mir->bb = NullBasicBlockId;
1195 }
1196
1197 after_list = last_list_mir->next;
1198
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001199 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001200 if (before_list == nullptr) {
1201 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001202 } else {
1203 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001204 }
1205
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001206 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001207 if (after_list == nullptr) {
1208 last_mir_insn = before_list;
1209 }
1210
1211 return true;
buzbee1fd33462013-03-25 13:40:45 -07001212}
1213
Vladimir Marko26e7d452014-11-24 14:09:46 +00001214MIR* BasicBlock::GetFirstNonPhiInsn() {
1215 MIR* mir = first_mir_insn;
1216 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1217 mir = mir->next;
1218 }
1219 return mir;
1220}
1221
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001222MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001223 MIR* next_mir = nullptr;
1224
1225 if (current != nullptr) {
1226 next_mir = current->next;
1227 }
1228
1229 if (next_mir == nullptr) {
1230 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001231 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1232 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001233 }
1234 }
1235
1236 return next_mir;
1237}
1238
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001239static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1240 DCHECK(decoded_mir != nullptr);
1241 OpSize type = static_cast<OpSize>(type_size >> 16);
1242 uint16_t vect_size = (type_size & 0xFFFF);
1243
1244 // Now print the type and vector size.
1245 std::stringstream ss;
1246 ss << " (type:";
1247 ss << type;
1248 ss << " vectsize:";
1249 ss << vect_size;
1250 ss << ")";
1251
1252 decoded_mir->append(ss.str());
1253}
1254
1255void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1256 DCHECK(decoded_mir != nullptr);
1257 int opcode = mir->dalvikInsn.opcode;
1258 SSARepresentation* ssa_rep = mir->ssa_rep;
1259 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1260 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1261
Vladimirf41b92c2014-10-13 13:41:38 +07001262 if (opcode < kMirOpFirst) {
1263 return; // It is not an extended instruction.
1264 }
1265
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001266 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1267
1268 switch (opcode) {
1269 case kMirOpPhi: {
1270 if (defs > 0 && uses > 0) {
1271 BasicBlockId* incoming = mir->meta.phi_incoming;
1272 decoded_mir->append(StringPrintf(" %s = (%s",
1273 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1274 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1275 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1276 for (int i = 1; i < uses; i++) {
1277 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1278 }
1279 decoded_mir->append(")");
1280 }
1281 break;
1282 }
1283 case kMirOpCopy:
1284 if (ssa_rep != nullptr) {
1285 decoded_mir->append(" ");
1286 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1287 if (defs > 1) {
1288 decoded_mir->append(", ");
1289 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1290 }
1291 decoded_mir->append(" = ");
1292 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1293 if (uses > 1) {
1294 decoded_mir->append(", ");
1295 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1296 }
1297 } else {
1298 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1299 }
1300 break;
1301 case kMirOpFusedCmplFloat:
1302 case kMirOpFusedCmpgFloat:
1303 case kMirOpFusedCmplDouble:
1304 case kMirOpFusedCmpgDouble:
1305 case kMirOpFusedCmpLong:
1306 if (ssa_rep != nullptr) {
1307 decoded_mir->append(" ");
1308 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1309 for (int i = 1; i < uses; i++) {
1310 decoded_mir->append(", ");
1311 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1312 }
1313 } else {
1314 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1315 }
1316 break;
1317 case kMirOpMoveVector:
1318 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1319 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1320 break;
1321 case kMirOpPackedAddition:
1322 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1323 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1324 break;
1325 case kMirOpPackedMultiply:
1326 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1327 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1328 break;
1329 case kMirOpPackedSubtract:
1330 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1331 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1332 break;
1333 case kMirOpPackedAnd:
1334 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1335 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1336 break;
1337 case kMirOpPackedOr:
1338 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1339 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1340 break;
1341 case kMirOpPackedXor:
1342 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1343 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1344 break;
1345 case kMirOpPackedShiftLeft:
1346 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1347 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1348 break;
1349 case kMirOpPackedUnsignedShiftRight:
1350 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1351 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1352 break;
1353 case kMirOpPackedSignedShiftRight:
1354 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1355 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1356 break;
1357 case kMirOpConstVector:
1358 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1359 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1360 break;
1361 case kMirOpPackedSet:
1362 if (ssa_rep != nullptr) {
1363 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1364 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1365 if (uses > 1) {
1366 decoded_mir->append(", ");
1367 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1368 }
1369 } else {
1370 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1371 }
1372 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1373 break;
1374 case kMirOpPackedAddReduce:
1375 if (ssa_rep != nullptr) {
1376 decoded_mir->append(" ");
1377 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1378 if (defs > 1) {
1379 decoded_mir->append(", ");
1380 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1381 }
1382 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1383 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1384 if (uses > 1) {
1385 decoded_mir->append(", ");
1386 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1387 }
1388 } else {
1389 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1390 }
1391 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1392 break;
1393 case kMirOpPackedReduce:
1394 if (ssa_rep != nullptr) {
1395 decoded_mir->append(" ");
1396 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1397 if (defs > 1) {
1398 decoded_mir->append(", ");
1399 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1400 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001401 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001402 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001403 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1404 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001405 }
1406 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1407 break;
1408 case kMirOpReserveVectorRegisters:
1409 case kMirOpReturnVectorRegisters:
1410 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1411 break;
1412 case kMirOpMemBarrier: {
1413 decoded_mir->append(" type:");
1414 std::stringstream ss;
1415 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1416 decoded_mir->append(ss.str());
1417 break;
1418 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001419 case kMirOpPackedArrayGet:
1420 case kMirOpPackedArrayPut:
1421 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1422 if (ssa_rep != nullptr) {
1423 decoded_mir->append(StringPrintf(", %s[%s]",
1424 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1425 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1426 } else {
1427 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1428 }
1429 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1430 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001431 case kMirOpMaddInt:
1432 case kMirOpMsubInt:
1433 case kMirOpMaddLong:
1434 case kMirOpMsubLong:
1435 if (ssa_rep != nullptr) {
1436 decoded_mir->append(" ");
1437 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1438 if (defs > 1) {
1439 decoded_mir->append(", ");
1440 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1441 }
1442 for (int i = 0; i < uses; i++) {
1443 decoded_mir->append(", ");
1444 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1445 }
1446 } else {
1447 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1448 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1449 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1450 }
1451 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001452 default:
1453 break;
1454 }
1455}
1456
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001457char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001458 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001459 std::string str;
1460 int flags = 0;
1461 int opcode = insn.opcode;
1462 char* ret;
1463 bool nop = false;
1464 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001465 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001466
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001467 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001468 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1469 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1470 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001471 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001472 insn = mir->meta.throw_insn->dalvikInsn;
1473 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001474 opcode = insn.opcode;
1475 } else if (opcode == kMirOpNop) {
1476 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001477 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1478 // Recover original opcode.
1479 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1480 opcode = insn.opcode;
1481 }
buzbee1fd33462013-03-25 13:40:45 -07001482 nop = true;
1483 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001484 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1485 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001486
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001487 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001488 // Note that this does not check the MIR's opcode in all cases. In cases where it
1489 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1490 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001491 } else {
1492 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001493 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001494 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001495
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001496 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001497 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1498 (dalvik_format == Instruction::k3rc));
1499 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001500 str.append(" ");
1501 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1502 if (defs > 1) {
1503 str.append(", ");
1504 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1505 }
buzbee1fd33462013-03-25 13:40:45 -07001506 if (uses != 0) {
1507 str.append(", ");
1508 }
1509 }
1510 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001511 str.append(" ");
1512 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001513 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1514 // For the listing, skip the high sreg.
1515 i++;
1516 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001517 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001518 str.append(",");
1519 }
1520 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001521
buzbee1fd33462013-03-25 13:40:45 -07001522 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001523 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001524 case Instruction::k21s:
1525 case Instruction::k31i:
1526 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001527 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001528 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001529 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001530 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001531 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001532 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001533 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001534 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001535 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001536 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001537 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001538 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001539 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001540 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001541 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001542 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001543 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001544 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001545 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001546 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001547
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001548 if ((flags & Instruction::kBranch) != 0) {
1549 // For branches, decode the instructions to print out the branch targets.
1550 int offset = 0;
1551 switch (dalvik_format) {
1552 case Instruction::k21t:
1553 offset = insn.vB;
1554 break;
1555 case Instruction::k22t:
1556 offset = insn.vC;
1557 break;
1558 case Instruction::k10t:
1559 case Instruction::k20t:
1560 case Instruction::k30t:
1561 offset = insn.vA;
1562 break;
1563 default:
1564 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001565 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001566 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001567 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001568 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1569 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001570
1571 if (nop) {
1572 str.append("]--optimized away");
1573 }
buzbee1fd33462013-03-25 13:40:45 -07001574 }
1575 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001576 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001577 strncpy(ret, str.c_str(), length);
1578 return ret;
1579}
1580
1581/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001582void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001583 static const struct { const char before; const char after; } match[] = {
1584 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1585 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1586 };
buzbee1fd33462013-03-25 13:40:45 -07001587 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1588 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1589 }
1590}
1591
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001592std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001593 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1594 // the arena. We should be smarter and just place straight into the arena, or compute the
1595 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001596 int vreg = SRegToVReg(ssa_reg);
1597 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1598 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1599 } else {
1600 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1601 }
buzbee1fd33462013-03-25 13:40:45 -07001602}
1603
1604// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001605std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001606 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001607 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001608 return GetSSAName(ssa_reg);
1609 }
1610 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001611 if (!singles_only && reg_location_[ssa_reg].wide &&
1612 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001613 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001614 ConstantValueWide(reg_location_[ssa_reg]));
1615 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001616 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001617 ConstantValue(reg_location_[ssa_reg]));
1618 }
1619 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001620 int vreg = SRegToVReg(ssa_reg);
1621 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1622 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1623 } else {
1624 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1625 }
buzbee1fd33462013-03-25 13:40:45 -07001626 }
1627}
1628
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001629void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001630 switch (bb->block_type) {
1631 case kEntryBlock:
1632 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1633 break;
1634 case kExitBlock:
1635 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1636 break;
1637 case kDalvikByteCode:
1638 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1639 break;
1640 case kExceptionHandling:
1641 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1642 bb->id);
1643 break;
1644 default:
1645 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1646 break;
1647 }
1648}
1649
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001650const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001651 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001652 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1653 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1654}
1655
Serguei Katkov717a3e42014-11-13 17:19:42 +06001656const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1657 const DexFile::MethodId& method_id =
1658 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1659 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1660}
1661
buzbee1fd33462013-03-25 13:40:45 -07001662/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001663void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001664 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001665 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001666 "Entry Block",
1667 "Code Block",
1668 "Exit Block",
1669 "Exception Handling",
1670 "Catch Block"
1671 };
1672
1673 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001674 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001675 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001676
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001677 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001678 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1679 bb->id,
1680 block_type_names[bb->block_type],
1681 bb->start_offset,
1682 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1683 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001684 if (bb->taken != NullBasicBlockId) {
1685 LOG(INFO) << " Taken branch: block " << bb->taken
1686 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001687 }
buzbee0d829482013-10-11 15:24:55 -07001688 if (bb->fall_through != NullBasicBlockId) {
1689 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1690 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001691 }
1692 }
1693}
1694
1695/*
1696 * Build an array of location records for the incoming arguments.
1697 * Note: one location record per word of arguments, with dummy
1698 * high-word loc for wide arguments. Also pull up any following
1699 * MOVE_RESULT and incorporate it into the invoke.
1700 */
1701CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001702 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001703 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001704 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001705 MIR* move_result_mir = FindMoveResult(bb, mir);
1706 if (move_result_mir == NULL) {
1707 info->result.location = kLocInvalid;
1708 } else {
1709 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001710 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1711 }
1712 info->num_arg_words = mir->ssa_rep->num_uses;
1713 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001714 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001715 for (int i = 0; i < info->num_arg_words; i++) {
1716 info->args[i] = GetRawSrc(mir, i);
1717 }
1718 info->opt_flags = mir->optimization_flags;
1719 info->type = type;
1720 info->is_range = is_range;
1721 info->index = mir->dalvikInsn.vB;
1722 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001723 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001724 return info;
1725}
1726
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001727// Allocate a new MIR.
1728MIR* MIRGraph::NewMIR() {
1729 MIR* mir = new (arena_) MIR();
1730 return mir;
1731}
1732
buzbee862a7602013-04-05 10:58:54 -07001733// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001734BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001735 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001736
buzbee862a7602013-04-05 10:58:54 -07001737 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001738 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001739 block_id_map_.Put(block_id, block_id);
1740 return bb;
1741}
buzbee1fd33462013-03-25 13:40:45 -07001742
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001743void MIRGraph::InitializeConstantPropagation() {
1744 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001745 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001746}
1747
1748void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001749 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001750 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001751 use_counts_.clear();
1752 use_counts_.reserve(num_ssa_regs + 32);
1753 use_counts_.resize(num_ssa_regs, 0u);
1754 raw_use_counts_.clear();
1755 raw_use_counts_.reserve(num_ssa_regs + 32);
1756 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001757}
1758
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001759void MIRGraph::SSATransformationStart() {
1760 DCHECK(temp_scoped_alloc_.get() == nullptr);
1761 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001762 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1763 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1764 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001765}
1766
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001767void MIRGraph::SSATransformationEnd() {
1768 // Verify the dataflow information after the pass.
1769 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1770 VerifyDataflow();
1771 }
1772
Vladimir Markof585e542014-11-21 13:41:32 +00001773 temp_.ssa.num_vregs = 0u;
1774 temp_.ssa.work_live_vregs = nullptr;
1775 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001776 DCHECK(temp_scoped_alloc_.get() != nullptr);
1777 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001778
1779 // Update the maximum number of reachable blocks.
1780 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001781
1782 // Mark MIR SSA representations as up to date.
1783 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001784}
1785
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001786size_t MIRGraph::GetNumDalvikInsns() const {
1787 size_t cumulative_size = 0u;
1788 bool counted_current_item = false;
1789 const uint8_t size_for_null_code_item = 2u;
1790
1791 for (auto it : m_units_) {
1792 const DexFile::CodeItem* code_item = it->GetCodeItem();
1793 // Even if the code item is null, we still count non-zero value so that
1794 // each m_unit is counted as having impact.
1795 cumulative_size += (code_item == nullptr ?
1796 size_for_null_code_item : code_item->insns_size_in_code_units_);
1797 if (code_item == current_code_item_) {
1798 counted_current_item = true;
1799 }
1800 }
1801
1802 // If the current code item was not counted yet, count it now.
1803 // This can happen for example in unit tests where some fields like m_units_
1804 // are not initialized.
1805 if (counted_current_item == false) {
1806 cumulative_size += (current_code_item_ == nullptr ?
1807 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1808 }
1809
1810 return cumulative_size;
1811}
1812
Vladimir Marko55fff042014-07-10 12:42:52 +01001813static BasicBlock* SelectTopologicalSortOrderFallBack(
1814 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1815 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1816 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1817 // No true loop head has been found but there may be true loop heads after the mess we need
1818 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1819 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1820 BasicBlock* fall_back = nullptr;
1821 size_t fall_back_num_reachable = 0u;
1822 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1823 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1824 AllNodesIterator iter(mir_graph);
1825 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1826 if (candidate->hidden || // Hidden, or
1827 candidate->visited || // already processed, or
1828 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1829 (current_loop != nullptr && // outside current loop.
1830 !current_loop->IsBitSet(candidate->id))) {
1831 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001832 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001833 DCHECK(tmp_stack->empty());
1834 tmp_stack->push_back(candidate->id);
1835 candidate_reachable.ClearAllBits();
1836 size_t num_reachable = 0u;
1837 while (!tmp_stack->empty()) {
1838 BasicBlockId current_id = tmp_stack->back();
1839 tmp_stack->pop_back();
1840 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1841 DCHECK(current_bb != nullptr);
1842 ChildBlockIterator child_iter(current_bb, mir_graph);
1843 BasicBlock* child_bb = child_iter.Next();
1844 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1845 DCHECK(!child_bb->hidden);
1846 if (child_bb->visited || // Already processed, or
1847 (current_loop != nullptr && // outside current loop.
1848 !current_loop->IsBitSet(child_bb->id))) {
1849 continue;
1850 }
1851 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1852 candidate_reachable.SetBit(child_bb->id);
1853 tmp_stack->push_back(child_bb->id);
1854 num_reachable += 1u;
1855 }
1856 }
1857 }
1858 if (fall_back_num_reachable < num_reachable) {
1859 fall_back_num_reachable = num_reachable;
1860 fall_back = candidate;
1861 }
1862 }
1863 return fall_back;
1864}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001865
Vladimir Marko55fff042014-07-10 12:42:52 +01001866// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1867static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1868 ArenaBitVector* reachable,
1869 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1870 // NOTE: Loop heads indicated by the "visited" flag.
1871 DCHECK(tmp_stack->empty());
1872 reachable->ClearAllBits();
1873 tmp_stack->push_back(bb_id);
1874 while (!tmp_stack->empty()) {
1875 BasicBlockId current_id = tmp_stack->back();
1876 tmp_stack->pop_back();
1877 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1878 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001879 for (BasicBlockId pred_id : current_bb->predecessors) {
1880 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1881 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001882 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1883 reachable->SetBit(pred_bb->id);
1884 tmp_stack->push_back(pred_bb->id);
1885 }
1886 }
1887 }
1888}
1889
1890void MIRGraph::ComputeTopologicalSortOrder() {
1891 ScopedArenaAllocator allocator(&cu_->arena_stack);
1892 unsigned int num_blocks = GetNumBlocks();
1893
1894 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1895 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1896 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1897 size_t max_nested_loops = 0u;
1898 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1899 loop_exit_blocks.ClearAllBits();
1900
1901 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001902 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001903 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001904 if (bb->hidden == true) {
1905 continue;
1906 }
1907
Vladimir Marko55fff042014-07-10 12:42:52 +01001908 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001909
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001910 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001911 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001912 q.push(bb);
1913 }
1914 }
1915
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001916 // Clear the topological order arrays.
1917 topological_order_.clear();
1918 topological_order_.reserve(num_blocks);
1919 topological_order_loop_ends_.clear();
1920 topological_order_loop_ends_.resize(num_blocks, 0u);
1921 topological_order_indexes_.clear();
1922 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001923
1924 // Mark all blocks as unvisited.
1925 ClearAllVisitedFlags();
1926
1927 // For loop heads, keep track from which blocks they are reachable not going through other
1928 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1929 // in this set go into the loop body, the other children are jumping over the loop.
1930 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1931 loop_head_reachable_from.resize(num_blocks, nullptr);
1932 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1933 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1934
1935 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001936 BasicBlock* bb = nullptr;
1937 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001938 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001939 // Get top.
1940 bb = q.front();
1941 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001942 if (bb->visited) {
1943 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1944 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001945 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1946 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001947 DCHECK_EQ(loop_head_stack.back(), bb->id);
1948 loop_head_stack.pop_back();
1949 ArenaBitVector* reachable =
1950 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1951 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1952 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1953 q.push(GetBasicBlock(candidate_id));
1954 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1955 // so clearing the bit has no effect on the iterator.
1956 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001957 }
1958 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001959 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001960 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001961 } else {
1962 // Find the new loop head.
1963 AllNodesIterator iter(this);
1964 while (true) {
1965 BasicBlock* candidate = iter.Next();
1966 if (candidate == nullptr) {
1967 // We did not find a true loop head, fall back to a reachable block in any loop.
1968 ArenaBitVector* current_loop =
1969 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1970 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1971 &allocator, &tmp_stack);
1972 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1973 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1974 LOG(INFO) << "Topological sort order: Using fall-back in "
1975 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1976 << " @0x" << std::hex << bb->start_offset
1977 << ", num_blocks = " << std::dec << num_blocks;
1978 }
1979 break;
1980 }
1981 if (candidate->hidden || // Hidden, or
1982 candidate->visited || // already processed, or
1983 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1984 (!loop_head_stack.empty() && // outside current loop.
1985 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1986 continue;
1987 }
1988
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001989 for (BasicBlockId pred_id : candidate->predecessors) {
1990 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1991 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001992 if (pred_bb != candidate && !pred_bb->visited &&
1993 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001994 candidate = nullptr; // Set candidate to null to indicate failure.
1995 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001996 }
1997 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001998 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001999 bb = candidate;
2000 break;
2001 }
2002 }
2003 // Compute blocks from which the loop head is reachable and process those blocks first.
2004 ArenaBitVector* reachable =
2005 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
2006 loop_head_reachable_from[bb->id] = reachable;
2007 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
2008 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
2009 loop_head_stack.push_back(bb->id);
2010 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002011 }
2012
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002013 DCHECK_EQ(bb->hidden, false);
2014 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002015 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00002016 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002017
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002018 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002019 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
2020 topological_order_indexes_[bb->id] = idx;
2021 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002022
Vladimir Marko55fff042014-07-10 12:42:52 +01002023 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002024 ChildBlockIterator succIter(bb, this);
2025 BasicBlock* successor = succIter.Next();
2026 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002027 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002028 continue;
2029 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002030
Vladimir Marko55fff042014-07-10 12:42:52 +01002031 // One more predecessor was visited.
2032 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002033 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002034 if (loop_head_stack.empty() ||
2035 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2036 q.push(successor);
2037 } else {
2038 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2039 loop_exit_blocks.SetBit(successor->id);
2040 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002041 }
2042 }
2043 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002044
2045 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002046 topological_order_loop_head_stack_.clear();
2047 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002048 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002049 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002050}
2051
2052bool BasicBlock::IsExceptionBlock() const {
2053 if (block_type == kExceptionHandling) {
2054 return true;
2055 }
2056 return false;
2057}
2058
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002059ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2060 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2061 visited_taken_(false), have_successors_(false) {
2062 // Check if we actually do have successors.
2063 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2064 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002065 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002066 }
2067}
2068
2069BasicBlock* ChildBlockIterator::Next() {
2070 // We check if we have a basic block. If we don't we cannot get next child.
2071 if (basic_block_ == nullptr) {
2072 return nullptr;
2073 }
2074
2075 // If we haven't visited fallthrough, return that.
2076 if (visited_fallthrough_ == false) {
2077 visited_fallthrough_ = true;
2078
2079 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2080 if (result != nullptr) {
2081 return result;
2082 }
2083 }
2084
2085 // If we haven't visited taken, return that.
2086 if (visited_taken_ == false) {
2087 visited_taken_ = true;
2088
2089 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2090 if (result != nullptr) {
2091 return result;
2092 }
2093 }
2094
2095 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2096 if (have_successors_ == true) {
2097 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002098 auto end = basic_block_->successor_blocks.cend();
2099 while (successor_iter_ != end) {
2100 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2101 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002102 // If block was replaced by zero block, take next one.
2103 if (successor_block_info->block != NullBasicBlockId) {
2104 return mir_graph_->GetBasicBlock(successor_block_info->block);
2105 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002106 }
2107 }
2108
2109 // We do not have anything.
2110 return nullptr;
2111}
2112
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002113BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2114 MIRGraph* mir_graph = c_unit->mir_graph.get();
2115 return Copy(mir_graph);
2116}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002117
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002118BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2119 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002120
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002121 // We don't do a memcpy style copy here because it would lead to a lot of things
2122 // to clean up. Let us do it by hand instead.
2123 // Copy in taken and fallthrough.
2124 result_bb->fall_through = fall_through;
2125 result_bb->taken = taken;
2126
2127 // Copy successor links if needed.
2128 ArenaAllocator* arena = mir_graph->GetArena();
2129
2130 result_bb->successor_block_list_type = successor_block_list_type;
2131 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002132 result_bb->successor_blocks.reserve(successor_blocks.size());
2133 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2134 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2135 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002136 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002137 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002138 }
2139 }
2140
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002141 // Copy offset, method.
2142 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002143
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002144 // Now copy instructions.
2145 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2146 // Get a copy first.
2147 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002148
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002149 // Append it.
2150 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002151 }
2152
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002153 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002154}
2155
2156MIR* MIR::Copy(MIRGraph* mir_graph) {
2157 MIR* res = mir_graph->NewMIR();
2158 *res = *this;
2159
2160 // Remove links
2161 res->next = nullptr;
2162 res->bb = NullBasicBlockId;
2163 res->ssa_rep = nullptr;
2164
2165 return res;
2166}
2167
2168MIR* MIR::Copy(CompilationUnit* c_unit) {
2169 return Copy(c_unit->mir_graph.get());
2170}
2171
2172uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2173 // Default result.
2174 int res = 0;
2175
2176 // We are basically setting the iputs to their igets counterparts.
2177 switch (opcode) {
2178 case Instruction::IPUT:
2179 case Instruction::IPUT_OBJECT:
2180 case Instruction::IPUT_BOOLEAN:
2181 case Instruction::IPUT_BYTE:
2182 case Instruction::IPUT_CHAR:
2183 case Instruction::IPUT_SHORT:
2184 case Instruction::IPUT_QUICK:
2185 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002186 case Instruction::IPUT_BOOLEAN_QUICK:
2187 case Instruction::IPUT_BYTE_QUICK:
2188 case Instruction::IPUT_CHAR_QUICK:
2189 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002190 case Instruction::APUT:
2191 case Instruction::APUT_OBJECT:
2192 case Instruction::APUT_BOOLEAN:
2193 case Instruction::APUT_BYTE:
2194 case Instruction::APUT_CHAR:
2195 case Instruction::APUT_SHORT:
2196 case Instruction::SPUT:
2197 case Instruction::SPUT_OBJECT:
2198 case Instruction::SPUT_BOOLEAN:
2199 case Instruction::SPUT_BYTE:
2200 case Instruction::SPUT_CHAR:
2201 case Instruction::SPUT_SHORT:
2202 // Skip the VR containing what to store.
2203 res = 1;
2204 break;
2205 case Instruction::IPUT_WIDE:
2206 case Instruction::IPUT_WIDE_QUICK:
2207 case Instruction::APUT_WIDE:
2208 case Instruction::SPUT_WIDE:
2209 // Skip the two VRs containing what to store.
2210 res = 2;
2211 break;
2212 default:
2213 // Do nothing in the general case.
2214 break;
2215 }
2216
2217 return res;
2218}
2219
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002220/**
2221 * @brief Given a decoded instruction, it checks whether the instruction
2222 * sets a constant and if it does, more information is provided about the
2223 * constant being set.
2224 * @param ptr_value pointer to a 64-bit holder for the constant.
2225 * @param wide Updated by function whether a wide constant is being set by bytecode.
2226 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2227 */
2228bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2229 bool sets_const = true;
2230 int64_t value = vB;
2231
2232 DCHECK(ptr_value != nullptr);
2233 DCHECK(wide != nullptr);
2234
2235 switch (opcode) {
2236 case Instruction::CONST_4:
2237 case Instruction::CONST_16:
2238 case Instruction::CONST:
2239 *wide = false;
2240 value <<= 32; // In order to get the sign extend.
2241 value >>= 32;
2242 break;
2243 case Instruction::CONST_HIGH16:
2244 *wide = false;
2245 value <<= 48; // In order to get the sign extend.
2246 value >>= 32;
2247 break;
2248 case Instruction::CONST_WIDE_16:
2249 case Instruction::CONST_WIDE_32:
2250 *wide = true;
2251 value <<= 32; // In order to get the sign extend.
2252 value >>= 32;
2253 break;
2254 case Instruction::CONST_WIDE:
2255 *wide = true;
2256 value = vB_wide;
2257 break;
2258 case Instruction::CONST_WIDE_HIGH16:
2259 *wide = true;
2260 value <<= 48; // In order to get the sign extend.
2261 break;
2262 default:
2263 sets_const = false;
2264 break;
2265 }
2266
2267 if (sets_const) {
2268 *ptr_value = value;
2269 }
2270
2271 return sets_const;
2272}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002273
2274void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2275 // Reset flags for all MIRs in bb.
2276 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2277 mir->optimization_flags &= (~reset_flags);
2278 }
2279}
2280
Vladimir Markocb873d82014-12-08 15:16:54 +00002281void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002282 for (BasicBlockId pred_id : predecessors) {
2283 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2284 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002285
2286 // Sadly we have to go through the children by hand here.
2287 pred_bb->ReplaceChild(id, NullBasicBlockId);
2288 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002289 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002290
Vladimir Marko312eb252014-10-07 15:01:57 +01002291 // Mark as dead and hidden.
2292 block_type = kDead;
2293 hidden = true;
2294
2295 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2296 // are updated to know that they no longer have a parent.
2297 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2298 mir->bb = NullBasicBlockId;
2299 }
2300 first_mir_insn = nullptr;
2301 last_mir_insn = nullptr;
2302
2303 data_flow_info = nullptr;
2304
2305 // Erase this bb from all children's predecessors and kill unreachable children.
2306 ChildBlockIterator iter(this, mir_graph);
2307 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2308 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002309 }
2310
2311 // Remove links to children.
2312 fall_through = NullBasicBlockId;
2313 taken = NullBasicBlockId;
2314 successor_block_list_type = kNotUsed;
2315
2316 if (kIsDebugBuild) {
2317 if (catch_entry) {
2318 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2319 mir_graph->catches_.erase(start_offset);
2320 }
2321 }
2322}
2323
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002324bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2325 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2326 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2327 // then it is not live out of this BB.
2328 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2329
2330 int last_ssa_reg = -1;
2331
2332 // Walk through the MIRs backwards.
2333 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2334 // Get ssa rep.
2335 SSARepresentation *ssa_rep = mir->ssa_rep;
2336
2337 // Go through the defines for this MIR.
2338 for (int i = 0; i < ssa_rep->num_defs; i++) {
2339 DCHECK(ssa_rep->defs != nullptr);
2340
2341 // Get the ssa reg.
2342 int def_ssa_reg = ssa_rep->defs[i];
2343
2344 // Get dalvik reg.
2345 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2346
2347 // Compare dalvik regs.
2348 if (dalvik_reg == def_dalvik_reg) {
2349 // We found a def of the register that we are being asked about.
2350 // Remember it.
2351 last_ssa_reg = def_ssa_reg;
2352 }
2353 }
2354 }
2355
2356 if (last_ssa_reg == -1) {
2357 // If we get to this point we couldn't find a define of register user asked about.
2358 // Let's assume the user knows what he's doing so we can be safe and say that if we
2359 // couldn't find a def, it is live out.
2360 return true;
2361 }
2362
2363 // If it is not -1, we found a match, is it ssa_reg?
2364 return (ssa_reg == last_ssa_reg);
2365}
2366
2367bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2368 // We need to check taken, fall_through, and successor_blocks to replace.
2369 bool found = false;
2370 if (taken == old_bb) {
2371 taken = new_bb;
2372 found = true;
2373 }
2374
2375 if (fall_through == old_bb) {
2376 fall_through = new_bb;
2377 found = true;
2378 }
2379
2380 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002381 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002382 if (successor_block_info->block == old_bb) {
2383 successor_block_info->block = new_bb;
2384 found = true;
2385 }
2386 }
2387 }
2388
2389 return found;
2390}
2391
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002392void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2393 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2394 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002395 // It's faster to move the back() to *pos than erase(pos).
2396 *pos = predecessors.back();
2397 predecessors.pop_back();
2398 size_t idx = std::distance(predecessors.begin(), pos);
2399 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2400 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2401 break;
2402 }
2403 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2404 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2405 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2406 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2407 mir->ssa_rep->num_uses = predecessors.size();
2408 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002409}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002410
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002411void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2412 DCHECK_NE(new_pred, NullBasicBlockId);
2413 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002414 DCHECK(pos != predecessors.end());
2415 *pos = new_pred;
2416 size_t idx = std::distance(predecessors.begin(), pos);
2417 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2418 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2419 break;
2420 }
2421 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2422 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002423 }
2424}
2425
2426// Create a new basic block with block_id as num_blocks_ that is
2427// post-incremented.
2428BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002429 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2430 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002431 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002432 return res;
2433}
2434
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002435void MIRGraph::CalculateBasicBlockInformation() {
Mathieu Chartier5bdab122015-01-26 18:30:19 -08002436 auto* quick_compiler = down_cast<QuickCompiler*>(cu_->compiler_driver->GetCompiler());
2437 DCHECK(quick_compiler != nullptr);
2438 /* Create the pass driver and launch it */
2439 PassDriverMEPostOpt driver(quick_compiler->GetPostOptPassManager(), cu_);
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002440 driver.Launch();
2441}
2442
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002443int MIR::DecodedInstruction::FlagsOf() const {
2444 // Calculate new index.
2445 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2446
2447 // Check if it is an extended or not.
2448 if (idx < 0) {
2449 return Instruction::FlagsOf(opcode);
2450 }
2451
2452 // For extended, we use a switch.
2453 switch (static_cast<int>(opcode)) {
2454 case kMirOpPhi:
2455 return Instruction::kContinue;
2456 case kMirOpCopy:
2457 return Instruction::kContinue;
2458 case kMirOpFusedCmplFloat:
2459 return Instruction::kContinue | Instruction::kBranch;
2460 case kMirOpFusedCmpgFloat:
2461 return Instruction::kContinue | Instruction::kBranch;
2462 case kMirOpFusedCmplDouble:
2463 return Instruction::kContinue | Instruction::kBranch;
2464 case kMirOpFusedCmpgDouble:
2465 return Instruction::kContinue | Instruction::kBranch;
2466 case kMirOpFusedCmpLong:
2467 return Instruction::kContinue | Instruction::kBranch;
2468 case kMirOpNop:
2469 return Instruction::kContinue;
2470 case kMirOpNullCheck:
2471 return Instruction::kContinue | Instruction::kThrow;
2472 case kMirOpRangeCheck:
2473 return Instruction::kContinue | Instruction::kThrow;
2474 case kMirOpDivZeroCheck:
2475 return Instruction::kContinue | Instruction::kThrow;
2476 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002477 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002478 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002479 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002480 case kMirOpSelect:
2481 return Instruction::kContinue;
2482 case kMirOpConstVector:
2483 return Instruction::kContinue;
2484 case kMirOpMoveVector:
2485 return Instruction::kContinue;
2486 case kMirOpPackedMultiply:
2487 return Instruction::kContinue;
2488 case kMirOpPackedAddition:
2489 return Instruction::kContinue;
2490 case kMirOpPackedSubtract:
2491 return Instruction::kContinue;
2492 case kMirOpPackedShiftLeft:
2493 return Instruction::kContinue;
2494 case kMirOpPackedSignedShiftRight:
2495 return Instruction::kContinue;
2496 case kMirOpPackedUnsignedShiftRight:
2497 return Instruction::kContinue;
2498 case kMirOpPackedAnd:
2499 return Instruction::kContinue;
2500 case kMirOpPackedOr:
2501 return Instruction::kContinue;
2502 case kMirOpPackedXor:
2503 return Instruction::kContinue;
2504 case kMirOpPackedAddReduce:
2505 return Instruction::kContinue;
2506 case kMirOpPackedReduce:
2507 return Instruction::kContinue;
2508 case kMirOpPackedSet:
2509 return Instruction::kContinue;
2510 case kMirOpReserveVectorRegisters:
2511 return Instruction::kContinue;
2512 case kMirOpReturnVectorRegisters:
2513 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002514 case kMirOpMemBarrier:
2515 return Instruction::kContinue;
2516 case kMirOpPackedArrayGet:
2517 return Instruction::kContinue | Instruction::kThrow;
2518 case kMirOpPackedArrayPut:
2519 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002520 case kMirOpMaddInt:
2521 case kMirOpMsubInt:
2522 case kMirOpMaddLong:
2523 case kMirOpMsubLong:
2524 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002525 default:
2526 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2527 return 0;
2528 }
2529}
Andreas Gampe0b9203e2015-01-22 20:39:27 -08002530
2531const uint16_t* MIRGraph::GetInsns(int m_unit_index) const {
2532 return m_units_[m_unit_index]->GetCodeItem()->insns_;
2533}
2534
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002535} // namespace art