blob: 1871f07106ce2101254b3f312baa882002f597c1 [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"
Mathieu Chartierb666f482015-02-18 14:33:14 -080027#include "base/scoped_arena_containers.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080028#include "compiler_ir.h"
buzbee311ca162013-02-28 15:56:43 -080029#include "dex_file-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080030#include "dex_flags.h"
Ian Rogers29a26482014-05-02 15:27:29 -070031#include "dex_instruction-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080032#include "driver/compiler_driver.h"
33#include "driver/dex_compilation_unit.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080034#include "dex/quick/quick_compiler.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000035#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070036#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070037#include "stack.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",
Vladimir Markoe299f162015-05-07 12:25:40 +010055 "Check",
buzbee1fd33462013-03-25 13:40:45 -070056 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040057 "ConstVector",
58 "MoveVector",
59 "PackedMultiply",
60 "PackedAddition",
61 "PackedSubtract",
62 "PackedShiftLeft",
63 "PackedSignedShiftRight",
64 "PackedUnsignedShiftRight",
65 "PackedAnd",
66 "PackedOr",
67 "PackedXor",
68 "PackedAddReduce",
69 "PackedReduce",
70 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070071 "ReserveVectorRegisters",
72 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070073 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070074 "PackedArrayGet",
75 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080076 "MaddInt",
77 "MsubInt",
78 "MaddLong",
79 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070080};
81
buzbee862a7602013-04-05 10:58:54 -070082MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
Mathieu Chartier2cebb242015-04-21 16:50:40 -070083 : reg_location_(nullptr),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010084 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070085 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010086 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
87 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 vreg_to_ssa_map_(nullptr),
89 ssa_last_defs_(nullptr),
90 is_constant_v_(nullptr),
91 constant_values_(nullptr),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010092 use_counts_(arena->Adapter()),
93 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080094 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070095 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010096 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000097 domination_up_to_date_(false),
98 mir_ssa_rep_up_to_date_(false),
99 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100100 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
101 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
102 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
103 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
104 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
105 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
106 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100107 max_nested_loops_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700108 i_dom_list_(nullptr),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000109 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100110 block_list_(arena->Adapter(kArenaAllocBBList)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 try_block_addr_(nullptr),
112 entry_block_(nullptr),
113 exit_block_(nullptr),
114 current_code_item_(nullptr),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100115 m_units_(arena->Adapter()),
116 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800117 current_method_(kInvalidEntry),
118 current_offset_(kInvalidEntry),
119 def_count_(0),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700120 opcode_count_(nullptr),
buzbee1fd33462013-03-25 13:40:45 -0700121 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100122 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700123 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700124 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700125 checkstats_(nullptr),
buzbeeb48819d2013-09-14 16:15:25 -0700126 arena_(arena),
127 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800128 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800129 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700130 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
131 requested_backend_temp_(false),
132 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000133 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000134 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100135 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
136 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
137 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000138 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000139 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100140 use_counts_.reserve(256);
141 raw_use_counts_.reserve(256);
142 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700143 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700144
145
146 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
147 // X86 requires a temp to keep track of the method address.
148 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
149 // this needs to be updated to reserve 0 temps for BE.
150 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
151 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
152 } else {
153 // Other architectures do not have a known lower bound for non-special temps.
154 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
155 max_available_non_special_compiler_temps_ = 0;
156 reserved_temps_for_backend_ = 0;
157 }
buzbee311ca162013-02-28 15:56:43 -0800158}
159
Ian Rogers6282dc12013-04-18 15:54:02 -0700160MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100161 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700162 STLDeleteElements(&m_units_);
163}
164
buzbee311ca162013-02-28 15:56:43 -0800165/*
166 * Parse an instruction, return the length of the instruction
167 */
Ian Rogers29a26482014-05-02 15:27:29 -0700168int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
169 const Instruction* inst = Instruction::At(code_ptr);
170 decoded_instruction->opcode = inst->Opcode();
171 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
172 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
173 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
174 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
175 if (inst->HasVarArgs()) {
176 inst->GetVarArgs(decoded_instruction->arg);
177 }
178 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800179}
180
181
182/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700183BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700184 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700185 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800186 MIR* insn = orig_block->first_mir_insn;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 MIR* prev = nullptr; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800188 while (insn) {
189 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700190 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800191 insn = insn->next;
192 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700193 if (insn == nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800194 LOG(FATAL) << "Break split failed";
195 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400196 // Now insn is at the instruction where we want to split, namely
197 // insn will be the first instruction of the "bottom" block.
198 // Similarly, prev will be the last instruction of the "top" block
199
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100200 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800201
202 bottom_block->start_offset = code_offset;
203 bottom_block->first_mir_insn = insn;
204 bottom_block->last_mir_insn = orig_block->last_mir_insn;
205
Junmo Park90223cc2014-08-04 18:51:21 +0900206 /* If this block was terminated by a return, conditional branch or throw,
207 * the flag needs to go with the bottom block
208 */
buzbee311ca162013-02-28 15:56:43 -0800209 bottom_block->terminated_by_return = orig_block->terminated_by_return;
210 orig_block->terminated_by_return = false;
211
Junmo Park90223cc2014-08-04 18:51:21 +0900212 bottom_block->conditional_branch = orig_block->conditional_branch;
213 orig_block->conditional_branch = false;
214
215 bottom_block->explicit_throw = orig_block->explicit_throw;
216 orig_block->explicit_throw = false;
217
buzbee311ca162013-02-28 15:56:43 -0800218 /* Handle the taken path */
219 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700220 if (bottom_block->taken != NullBasicBlockId) {
221 orig_block->taken = NullBasicBlockId;
222 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100223 bb_taken->ErasePredecessor(orig_block->id);
224 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800225 }
226
227 /* Handle the fallthrough path */
228 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700229 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100230 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700231 if (bottom_block->fall_through != NullBasicBlockId) {
232 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100233 bb_fall_through->ErasePredecessor(orig_block->id);
234 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800235 }
236
237 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700238 if (orig_block->successor_block_list_type != kNotUsed) {
239 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100240 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700241 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
243 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700244 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700245 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100246 bb->ErasePredecessor(orig_block->id);
247 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700248 }
buzbee311ca162013-02-28 15:56:43 -0800249 }
250 }
251
buzbee0d829482013-10-11 15:24:55 -0700252 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700253 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800254
buzbee311ca162013-02-28 15:56:43 -0800255 /*
256 * Update the immediate predecessor block pointer so that outgoing edges
257 * can be applied to the proper block.
258 */
259 if (immed_pred_block_p) {
260 DCHECK_EQ(*immed_pred_block_p, orig_block);
261 *immed_pred_block_p = bottom_block;
262 }
buzbeeb48819d2013-09-14 16:15:25 -0700263
264 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000265 DCHECK(insn != nullptr);
266 DCHECK(insn != orig_block->first_mir_insn);
267 DCHECK(insn == bottom_block->first_mir_insn);
268 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400269 // Scan the "bottom" instructions, remapping them to the
270 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000271 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400272 p->bb = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000273 while (p != bottom_block->last_mir_insn) {
274 p = p->next;
275 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700276 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700277 }
278
buzbee311ca162013-02-28 15:56:43 -0800279 return bottom_block;
280}
281
282/*
283 * Given a code offset, find out the block that starts with it. If the offset
284 * is in the middle of an existing block, split it into two. If immed_pred_block_p
285 * is not non-null and is the block being split, update *immed_pred_block_p to
286 * point to the bottom block so that outgoing edges can be set up properly
287 * (by the caller)
288 * Utilizes a map for fast lookup of the typical cases.
289 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700290BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800291 BasicBlock** immed_pred_block_p,
292 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Calin Juravle2bee20b2015-04-07 19:43:36 +0100293 if (UNLIKELY(code_offset >= current_code_item_->insns_size_in_code_units_)) {
294 // There can be a fall-through out of the method code. We shall record such a block
295 // here (assuming create==true) and check that it's dead at the end of InlineMethod().
296 // Though we're only aware of the cases where code_offset is exactly the same as
297 // insns_size_in_code_units_, treat greater code_offset the same just in case.
298 code_offset = current_code_item_->insns_size_in_code_units_;
buzbee311ca162013-02-28 15:56:43 -0800299 }
buzbeeb48819d2013-09-14 16:15:25 -0700300
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800301 int block_id = (*dex_pc_to_block_map)[code_offset];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100302 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700303
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700304 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700305 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700306 return bb;
307 }
buzbee311ca162013-02-28 15:56:43 -0800308
buzbeeb48819d2013-09-14 16:15:25 -0700309 // No direct hit.
310 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700311 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800312 }
313
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700314 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700315 // The target exists somewhere in an existing block.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800316 BasicBlock* bottom_block = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
317 DCHECK(bottom_block != nullptr);
318 MIR* p = bottom_block->first_mir_insn;
319 BasicBlock* orig_block = bb;
320 DCHECK_EQ((*dex_pc_to_block_map)[p->offset], orig_block->id);
321 // Scan the "bottom" instructions, remapping them to the
322 // newly created "bottom" block.
323 (*dex_pc_to_block_map)[p->offset] = bottom_block->id;
324 while (p != bottom_block->last_mir_insn) {
325 p = p->next;
326 DCHECK(p != nullptr);
327 int opcode = p->dalvikInsn.opcode;
328 /*
329 * Some messiness here to ensure that we only enter real opcodes and only the
330 * first half of a potentially throwing instruction that has been split into
331 * CHECK and work portions. Since the 2nd half of a split operation is always
332 * the first in a BasicBlock, we can't hit it here.
333 */
334 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
335 BasicBlockId mapped_id = (*dex_pc_to_block_map)[p->offset];
336 // At first glance the instructions should all be mapped to orig_block.
337 // However, multiple instructions may correspond to the same dex, hence an earlier
338 // instruction may have already moved the mapping for dex to bottom_block.
339 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
340 (*dex_pc_to_block_map)[p->offset] = bottom_block->id;
341 }
342 }
343 return bottom_block;
buzbeeb48819d2013-09-14 16:15:25 -0700344 }
345
346 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100347 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800348 bb->start_offset = code_offset;
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800349 (*dex_pc_to_block_map)[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800350 return bb;
351}
352
buzbeeb48819d2013-09-14 16:15:25 -0700353
buzbee311ca162013-02-28 15:56:43 -0800354/* Identify code range in try blocks and set up the empty catch blocks */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800355void MIRGraph::ProcessTryCatchBlocks(ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
buzbee311ca162013-02-28 15:56:43 -0800356 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700357 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800358
359 if (tries_size == 0) {
360 return;
361 }
362
363 for (int i = 0; i < tries_size; i++) {
364 const DexFile::TryItem* pTry =
365 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700366 DexOffset start_offset = pTry->start_addr_;
367 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800368 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700369 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800370 }
371 }
372
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700373 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700374 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800375 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
376 for (uint32_t idx = 0; idx < handlers_size; idx++) {
377 CatchHandlerIterator iterator(handlers_ptr);
378 for (; iterator.HasNext(); iterator.Next()) {
379 uint32_t address = iterator.GetHandlerAddress();
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800380 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800381 }
382 handlers_ptr = iterator.EndDataPointer();
383 }
384}
385
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100386bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
387 NarrowDexOffset catch_offset) {
388 // Catches for monitor-exit during stack unwinding have the pattern
389 // move-exception (move)* (goto)? monitor-exit throw
390 // In the currently generated dex bytecode we see these catching a bytecode range including
391 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
392 // it's the case for a given monitor-exit and catch block so that we can ignore it.
393 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
394 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
395 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700396 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100397 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
398 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700399 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100400 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
401 if (check_insn->VRegA_11x() == monitor_reg) {
402 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
403 return false;
404 }
405 check_insn = check_insn->Next();
406 while (true) {
407 int dest = -1;
408 bool wide = false;
409 switch (check_insn->Opcode()) {
410 case Instruction::MOVE_WIDE:
411 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700412 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100413 case Instruction::MOVE_OBJECT:
414 case Instruction::MOVE:
415 dest = check_insn->VRegA_12x();
416 break;
417
418 case Instruction::MOVE_WIDE_FROM16:
419 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700420 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100421 case Instruction::MOVE_OBJECT_FROM16:
422 case Instruction::MOVE_FROM16:
423 dest = check_insn->VRegA_22x();
424 break;
425
426 case Instruction::MOVE_WIDE_16:
427 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700428 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100429 case Instruction::MOVE_OBJECT_16:
430 case Instruction::MOVE_16:
431 dest = check_insn->VRegA_32x();
432 break;
433
434 case Instruction::GOTO:
435 case Instruction::GOTO_16:
436 case Instruction::GOTO_32:
437 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700438 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100439 default:
440 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
441 check_insn->VRegA_11x() == monitor_reg;
442 }
443
444 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
445 return false;
446 }
447
448 check_insn = check_insn->Next();
449 }
450}
451
buzbee311ca162013-02-28 15:56:43 -0800452/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700453BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
454 int width, int flags, const uint16_t* code_ptr,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800455 const uint16_t* code_end,
456 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
buzbee0d829482013-10-11 15:24:55 -0700457 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800458 switch (insn->dalvikInsn.opcode) {
459 case Instruction::GOTO:
460 case Instruction::GOTO_16:
461 case Instruction::GOTO_32:
462 target += insn->dalvikInsn.vA;
463 break;
464 case Instruction::IF_EQ:
465 case Instruction::IF_NE:
466 case Instruction::IF_LT:
467 case Instruction::IF_GE:
468 case Instruction::IF_GT:
469 case Instruction::IF_LE:
470 cur_block->conditional_branch = true;
471 target += insn->dalvikInsn.vC;
472 break;
473 case Instruction::IF_EQZ:
474 case Instruction::IF_NEZ:
475 case Instruction::IF_LTZ:
476 case Instruction::IF_GEZ:
477 case Instruction::IF_GTZ:
478 case Instruction::IF_LEZ:
479 cur_block->conditional_branch = true;
480 target += insn->dalvikInsn.vB;
481 break;
482 default:
483 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
484 }
buzbeeb48819d2013-09-14 16:15:25 -0700485 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700486 BasicBlock* taken_block = FindBlock(target, /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800487 /* immed_pred_block_p */ &cur_block,
488 dex_pc_to_block_map);
Calin Juravle2bee20b2015-04-07 19:43:36 +0100489 DCHECK(taken_block != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700490 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100491 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800492
493 /* Always terminate the current block for conditional branches */
494 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700495 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800496 /* create */
497 true,
498 /* immed_pred_block_p */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800499 &cur_block,
500 dex_pc_to_block_map);
Calin Juravle2bee20b2015-04-07 19:43:36 +0100501 DCHECK(fallthrough_block != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700502 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100503 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800504 } else if (code_ptr < code_end) {
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800505 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800506 }
507 return cur_block;
508}
509
510/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800511BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800512 int width, int flags,
513 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700514 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800515 const uint16_t* switch_data =
Calin Juravle2bee20b2015-04-07 19:43:36 +0100516 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset +
517 static_cast<int32_t>(insn->dalvikInsn.vB));
buzbee311ca162013-02-28 15:56:43 -0800518 int size;
519 const int* keyTable;
520 const int* target_table;
521 int i;
522 int first_key;
523
524 /*
525 * Packed switch data format:
526 * ushort ident = 0x0100 magic value
527 * ushort size number of entries in the table
528 * int first_key first (and lowest) switch case value
529 * int targets[size] branch targets, relative to switch opcode
530 *
531 * Total size is (4+size*2) 16-bit code units.
532 */
533 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
534 DCHECK_EQ(static_cast<int>(switch_data[0]),
535 static_cast<int>(Instruction::kPackedSwitchSignature));
536 size = switch_data[1];
537 first_key = switch_data[2] | (switch_data[3] << 16);
538 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700539 keyTable = nullptr; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800540 /*
541 * Sparse switch data format:
542 * ushort ident = 0x0200 magic value
543 * ushort size number of entries in the table; > 0
544 * int keys[size] keys, sorted low-to-high; 32-bit aligned
545 * int targets[size] branch targets, relative to switch opcode
546 *
547 * Total size is (2+size*4) 16-bit code units.
548 */
549 } else {
550 DCHECK_EQ(static_cast<int>(switch_data[0]),
551 static_cast<int>(Instruction::kSparseSwitchSignature));
552 size = switch_data[1];
553 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
554 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700555 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800556 }
557
buzbee0d829482013-10-11 15:24:55 -0700558 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800559 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700560 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800561 }
buzbee0d829482013-10-11 15:24:55 -0700562 cur_block->successor_block_list_type =
563 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100564 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800565
566 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700567 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800568 /* immed_pred_block_p */ &cur_block,
569 dex_pc_to_block_map);
Calin Juravle2bee20b2015-04-07 19:43:36 +0100570 DCHECK(case_block != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700571 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700572 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000573 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700574 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800575 successor_block_info->key =
576 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
577 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100578 cur_block->successor_blocks.push_back(successor_block_info);
579 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800580 }
581
582 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700583 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800584 /* immed_pred_block_p */ nullptr,
585 dex_pc_to_block_map);
Calin Juravle2bee20b2015-04-07 19:43:36 +0100586 DCHECK(fallthrough_block != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700587 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100588 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800589 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800590}
591
592/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700593BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
594 int width, int flags, ArenaBitVector* try_block_addr,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800595 const uint16_t* code_ptr, const uint16_t* code_end,
596 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700597 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700598 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800599 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800600
601 /* In try block */
602 if (in_try_block) {
603 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
604
buzbee0d829482013-10-11 15:24:55 -0700605 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800606 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
607 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700608 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800609 }
610
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700611 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700612 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800613 nullptr /* immed_pred_block_p */,
614 dex_pc_to_block_map);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100615 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
616 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
617 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
618 continue;
619 }
620 if (cur_block->successor_block_list_type == kNotUsed) {
621 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100622 }
buzbee311ca162013-02-28 15:56:43 -0800623 catch_block->catch_entry = true;
624 if (kIsDebugBuild) {
625 catches_.insert(catch_block->start_offset);
626 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700627 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000628 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700629 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800630 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100631 cur_block->successor_blocks.push_back(successor_block_info);
632 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800633 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100634 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
635 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100636 bool build_all_edges =
637 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100638 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100639 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700640 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800641 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100642 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800643 }
644
buzbee17189ac2013-11-08 11:07:02 -0800645 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800646 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700647 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700648 // Force creation of new block following THROW via side-effect.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800649 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800650 }
651 if (!in_try_block) {
652 // Don't split a THROW that can't rethrow - we're done.
653 return cur_block;
654 }
655 }
656
buzbee17189ac2013-11-08 11:07:02 -0800657 if (!build_all_edges) {
658 /*
659 * Even though there is an exception edge here, control cannot return to this
660 * method. Thus, for the purposes of dataflow analysis and optimization, we can
661 * ignore the edge. Doing this reduces compile time, and increases the scope
662 * of the basic-block level optimization pass.
663 */
664 return cur_block;
665 }
666
buzbee311ca162013-02-28 15:56:43 -0800667 /*
668 * Split the potentially-throwing instruction into two parts.
669 * The first half will be a pseudo-op that captures the exception
670 * edges and terminates the basic block. It always falls through.
671 * Then, create a new basic block that begins with the throwing instruction
672 * (minus exceptions). Note: this new basic block must NOT be entered into
673 * the block_map. If the potentially-throwing instruction is the target of a
674 * future branch, we need to find the check psuedo half. The new
675 * basic block containing the work portion of the instruction should
676 * only be entered via fallthrough from the block containing the
677 * pseudo exception edge MIR. Note also that this new block is
678 * not automatically terminated after the work portion, and may
679 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700680 *
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800681 * Note also that the dex_pc_to_block_map entry for the potentially
buzbeeb48819d2013-09-14 16:15:25 -0700682 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800683 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100684 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800685 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700686 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100687 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700688 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800689 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700690 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700691 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800692 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700693 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800694 return new_block;
695}
696
697/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
698void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Vladimir Marko20f85592015-03-19 10:07:02 +0000699 InvokeType invoke_type ATTRIBUTE_UNUSED, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700700 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800701 current_code_item_ = code_item;
702 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
703 current_method_ = m_units_.size();
704 current_offset_ = 0;
705 // TODO: will need to snapshot stack image and use that as the mir context identification.
Vladimir Markoc91df2d2015-04-23 09:29:21 +0000706 m_units_.push_back(new (arena_) DexCompilationUnit(
707 cu_, class_loader, Runtime::Current()->GetClassLinker(), dex_file,
708 current_code_item_, class_def_idx, method_idx, access_flags,
709 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800710 const uint16_t* code_ptr = current_code_item_->insns_;
711 const uint16_t* code_end =
712 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
713
714 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700715 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100716 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800717 // FindBlock lookup cache.
718 ScopedArenaAllocator allocator(&cu_->arena_stack);
719 ScopedArenaVector<uint16_t> dex_pc_to_block_map(allocator.Adapter());
Calin Juravle2bee20b2015-04-07 19:43:36 +0100720 dex_pc_to_block_map.resize(current_code_item_->insns_size_in_code_units_ +
721 1 /* Fall-through on last insn; dead or punt to interpreter. */);
buzbeebd663de2013-09-10 15:41:31 -0700722
buzbee311ca162013-02-28 15:56:43 -0800723 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700724 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
725 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800726
727 // If this is the first method, set up default entry and exit blocks.
728 if (current_method_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 DCHECK(entry_block_ == nullptr);
730 DCHECK(exit_block_ == nullptr);
Vladimir Markoffda4992014-12-18 17:05:58 +0000731 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700732 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100733 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700734 DCHECK_EQ(null_block->id, NullBasicBlockId);
735 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100736 entry_block_ = CreateNewBB(kEntryBlock);
737 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800738 } else {
739 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
740 /*
741 * Will need to manage storage for ins & outs, push prevous state and update
742 * insert point.
743 */
744 }
745
746 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100747 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700748 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800749 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700750 // TODO: for inlining support, insert at the insert point rather than entry block.
751 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100752 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800753
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000754 /* Identify code range in try blocks and set up the empty catch blocks */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800755 ProcessTryCatchBlocks(&dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800756
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000757 uint64_t merged_df_flags = 0u;
758
buzbee311ca162013-02-28 15:56:43 -0800759 /* Parse all instructions and put them into containing basic blocks */
760 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700761 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800762 insn->offset = current_offset_;
763 insn->m_unit_index = current_method_;
764 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800765 Instruction::Code opcode = insn->dalvikInsn.opcode;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700766 if (opcode_count_ != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800767 opcode_count_[static_cast<int>(opcode)]++;
768 }
769
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700770 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800771 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800772
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700773 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000774 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800775
776 if (df_flags & DF_HAS_DEFS) {
777 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
778 }
779
buzbee1da1e2f2013-11-15 13:37:01 -0800780 if (df_flags & DF_LVN) {
781 cur_block->use_lvn = true; // Run local value numbering on this basic block.
782 }
783
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700784 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700785 if (opcode == Instruction::NOP) {
786 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
787 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
788 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
789 uint16_t following_raw_instruction = code_ptr[1];
790 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
791 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
792 (following_raw_instruction == Instruction::kArrayDataSignature)) {
793 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
794 }
795 }
796 if (width == 1) {
797 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700798 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700799 } else {
buzbee0d829482013-10-11 15:24:55 -0700800 DCHECK(cur_block->fall_through == NullBasicBlockId);
801 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800802 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700803 flags &= ~Instruction::kContinue;
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800804 FindBlock(current_offset_ + width, /* create */ true,
805 /* immed_pred_block_p */ nullptr, &dex_pc_to_block_map);
buzbee27247762013-07-28 12:03:58 -0700806 }
807 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700808 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700809 }
810
buzbeeb48819d2013-09-14 16:15:25 -0700811 // Associate the starting dex_pc for this opcode with its containing basic block.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800812 dex_pc_to_block_map[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700813
buzbee27247762013-07-28 12:03:58 -0700814 code_ptr += width;
815
buzbee311ca162013-02-28 15:56:43 -0800816 if (flags & Instruction::kBranch) {
817 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800818 width, flags, code_ptr, code_end, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800819 } else if (flags & Instruction::kReturn) {
820 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700821 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100822 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800823 /*
824 * Terminate the current block if there are instructions
825 * afterwards.
826 */
827 if (code_ptr < code_end) {
828 /*
829 * Create a fallthrough block for real instructions
830 * (incl. NOP).
831 */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800832 FindBlock(current_offset_ + width, /* create */ true,
833 /* immed_pred_block_p */ nullptr, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800834 }
835 } else if (flags & Instruction::kThrow) {
836 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800837 code_ptr, code_end, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800838 } else if (flags & Instruction::kSwitch) {
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800839 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width,
840 flags, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800841 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700842 if (verify_flags & Instruction::kVerifyVarArgRange ||
843 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800844 /*
845 * The Quick backend's runtime model includes a gap between a method's
846 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
847 * which spans the gap is somewhat complicated, and should not happen
848 * in normal usage of dx. Punt to the interpreter.
849 */
850 int first_reg_in_range = insn->dalvikInsn.vC;
851 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
852 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
853 punt_to_interpreter_ = true;
854 }
855 }
buzbee311ca162013-02-28 15:56:43 -0800856 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700857 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800858 /* immed_pred_block_p */ nullptr,
859 &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800860 if (next_block) {
861 /*
862 * The next instruction could be the target of a previously parsed
863 * forward branch so a block is already created. If the current
864 * instruction is not an unconditional branch, connect them through
865 * the fall-through link.
866 */
buzbee0d829482013-10-11 15:24:55 -0700867 DCHECK(cur_block->fall_through == NullBasicBlockId ||
868 GetBasicBlock(cur_block->fall_through) == next_block ||
869 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800870
buzbee0d829482013-10-11 15:24:55 -0700871 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
872 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100873 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800874 }
875 cur_block = next_block;
876 }
877 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000878 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000879
buzbee311ca162013-02-28 15:56:43 -0800880 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
881 DumpCFG("/sdcard/1_post_parse_cfg/", true);
882 }
883
884 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700885 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800886 }
Calin Juravle2bee20b2015-04-07 19:43:36 +0100887
888 // Check if there's been a fall-through out of the method code.
889 BasicBlockId out_bb_id = dex_pc_to_block_map[current_code_item_->insns_size_in_code_units_];
890 if (UNLIKELY(out_bb_id != NullBasicBlockId)) {
891 // Eagerly calculate DFS order to determine if the block is dead.
892 DCHECK(!DfsOrdersUpToDate());
893 ComputeDFSOrders();
894 BasicBlock* out_bb = GetBasicBlock(out_bb_id);
895 DCHECK(out_bb != nullptr);
896 if (out_bb->block_type != kDead) {
897 LOG(WARNING) << "Live fall-through out of method in " << PrettyMethod(method_idx, dex_file);
898 SetPuntToInterpreter(true);
899 }
900 }
buzbee311ca162013-02-28 15:56:43 -0800901}
902
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700903void MIRGraph::ShowOpcodeStats() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700904 DCHECK(opcode_count_ != nullptr);
buzbee311ca162013-02-28 15:56:43 -0800905 LOG(INFO) << "Opcode Count";
906 for (int i = 0; i < kNumPackedOpcodes; i++) {
907 if (opcode_count_[i] != 0) {
908 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
909 << " " << opcode_count_[i];
910 }
911 }
912}
913
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700914uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
915 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
916 return oat_data_flow_attributes_[opcode];
917}
918
919uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
920 DCHECK(mir != nullptr);
921 Instruction::Code opcode = mir->dalvikInsn.opcode;
922 return GetDataFlowAttributes(opcode);
923}
924
Andreas Gampecee97e52014-12-19 15:30:11 -0800925// The path can easily surpass FS limits because of parameters etc. Use pathconf to get FS
926// restrictions here. Note that a successful invocation will return an actual value. If the path
927// is too long for some reason, the return will be ENAMETOOLONG. Then cut off part of the name.
928//
929// It's possible the path is not valid, or some other errors appear. In that case return false.
930static bool CreateDumpFile(std::string& fname, const char* dir_prefix, NarrowDexOffset start_offset,
931 const char *suffix, int nr, std::string* output) {
932 std::string dir = StringPrintf("./%s", dir_prefix);
933 int64_t max_name_length = pathconf(dir.c_str(), _PC_NAME_MAX);
934 if (max_name_length <= 0) {
935 PLOG(ERROR) << "Could not get file name restrictions for " << dir;
936 return false;
937 }
938
939 std::string name = StringPrintf("%s%x%s_%d.dot", fname.c_str(), start_offset,
940 suffix == nullptr ? "" : suffix, nr);
941 std::string fpath;
942 if (static_cast<int64_t>(name.size()) > max_name_length) {
943 std::string suffix_str = StringPrintf("_%d.dot", nr);
944 name = name.substr(0, static_cast<size_t>(max_name_length) - suffix_str.size()) + suffix_str;
945 }
946 // Sanity check.
947 DCHECK_LE(name.size(), static_cast<size_t>(max_name_length));
948
949 *output = StringPrintf("%s%s", dir_prefix, name.c_str());
950 return true;
951}
952
buzbee311ca162013-02-28 15:56:43 -0800953// TODO: use a configurable base prefix, and adjust callers to supply pass name.
954/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800955void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800956 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700957 static AtomicInteger cnt(0);
958
959 // Increment counter to get a unique file number.
960 cnt++;
Andreas Gampecee97e52014-12-19 15:30:11 -0800961 int nr = cnt.LoadRelaxed();
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700962
buzbee311ca162013-02-28 15:56:43 -0800963 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
964 ReplaceSpecialChars(fname);
Andreas Gampecee97e52014-12-19 15:30:11 -0800965 std::string fpath;
966 if (!CreateDumpFile(fname, dir_prefix, GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
967 suffix, nr, &fpath)) {
968 LOG(ERROR) << "Could not create dump file name for " << fname;
969 return;
970 }
971 file = fopen(fpath.c_str(), "w");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700972 if (file == nullptr) {
Andreas Gampecee97e52014-12-19 15:30:11 -0800973 PLOG(ERROR) << "Could not open " << fpath << " for DumpCFG.";
buzbee311ca162013-02-28 15:56:43 -0800974 return;
975 }
976 fprintf(file, "digraph G {\n");
977
978 fprintf(file, " rankdir=TB\n");
979
980 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
981 int idx;
982
983 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100984 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700985 BasicBlock* bb = GetBasicBlock(block_idx);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700986 if (bb == nullptr) continue;
buzbee311ca162013-02-28 15:56:43 -0800987 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700988 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800989 if (bb->block_type == kEntryBlock) {
990 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
991 } else if (bb->block_type == kExitBlock) {
992 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
993 } else if (bb->block_type == kDalvikByteCode) {
994 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
995 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700996 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800997 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
998 bb->first_mir_insn ? " | " : " ");
999 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
1000 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -08001001 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -04001002 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001003 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
1004 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -04001005 extended_mir_op_names_[opcode - kMirOpFirst],
1006 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
1007 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -07001008 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -07001009 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001010 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001011 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
1012 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -08001013 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -04001014 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -08001015 }
1016 fprintf(file, " }\"];\n\n");
1017 } else if (bb->block_type == kExceptionHandling) {
1018 char block_name[BLOCK_NAME_LEN];
1019
1020 GetBlockName(bb, block_name);
1021 fprintf(file, " %s [shape=invhouse];\n", block_name);
1022 }
1023
1024 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
1025
buzbee0d829482013-10-11 15:24:55 -07001026 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -08001027 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -07001028 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001029 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
1030 block_name1, block_name2);
1031 }
buzbee0d829482013-10-11 15:24:55 -07001032 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -08001033 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -07001034 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001035 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
1036 }
1037
buzbee0d829482013-10-11 15:24:55 -07001038 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -08001039 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
1040 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -07001041 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -08001042
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001043 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -08001044 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001045 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001046 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001047 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001048 succ_id,
buzbee311ca162013-02-28 15:56:43 -08001049 successor_block_info->key,
1050 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001051 (succ_id != last_succ_id) ? " | " : " ");
1052 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -08001053 }
1054 fprintf(file, " }\"];\n\n");
1055
1056 GetBlockName(bb, block_name1);
1057 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1058 block_name1, bb->start_offset, bb->id);
1059
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001060 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001061 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001062 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001063 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001064
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001065 GetBlockName(dest_block, block_name2);
1066 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1067 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001068 }
1069 }
1070 fprintf(file, "\n");
1071
1072 if (cu_->verbose) {
1073 /* Display the dominator tree */
1074 GetBlockName(bb, block_name1);
1075 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1076 block_name1, block_name1);
1077 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001078 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001079 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1080 }
1081 }
1082 }
1083 fprintf(file, "}\n");
1084 fclose(file);
1085}
1086
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001087/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001088void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001089 // Insert it after the last MIR.
1090 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001091}
1092
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001093void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1094 // Insert it after the last MIR.
1095 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1096}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001097
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001098void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1099 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1100 MIR* new_mir = *it;
1101
1102 // Add a copy of each MIR.
1103 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1104 }
buzbee1fd33462013-03-25 13:40:45 -07001105}
1106
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001107/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001108void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001109 InsertMIRListAfter(current_mir, new_mir, new_mir);
1110}
buzbee1fd33462013-03-25 13:40:45 -07001111
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001112void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1113 // If no MIR, we are done.
1114 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1115 return;
buzbee1fd33462013-03-25 13:40:45 -07001116 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001117
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001118 // If insert_after is null, assume BB is empty.
1119 if (insert_after == nullptr) {
1120 first_mir_insn = first_list_mir;
1121 last_mir_insn = last_list_mir;
1122 last_list_mir->next = nullptr;
1123 } else {
1124 MIR* after_list = insert_after->next;
1125 insert_after->next = first_list_mir;
1126 last_list_mir->next = after_list;
1127 if (after_list == nullptr) {
1128 last_mir_insn = last_list_mir;
1129 }
1130 }
1131
1132 // Set this BB to be the basic block of the MIRs.
1133 MIR* last = last_list_mir->next;
1134 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1135 mir->bb = id;
1136 }
1137}
1138
1139/* Insert an MIR instruction to the head of a basic block. */
1140void BasicBlock::PrependMIR(MIR* mir) {
1141 InsertMIRListBefore(first_mir_insn, mir, mir);
1142}
1143
1144void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1145 // Insert it before the first MIR.
1146 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1147}
1148
1149void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1150 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1151 MIR* mir = *it;
1152
1153 InsertMIRListBefore(first_mir_insn, mir, mir);
1154 }
1155}
1156
1157/* Insert a MIR instruction before the specified MIR. */
1158void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1159 // Insert as a single element list.
1160 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001161}
1162
1163MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1164 MIR* current = first_mir_insn;
1165
1166 while (current != nullptr) {
1167 MIR* next = current->next;
1168
1169 if (next == mir) {
1170 return current;
1171 }
1172
1173 current = next;
1174 }
1175
1176 return nullptr;
1177}
1178
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001179void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1180 // If no MIR, we are done.
1181 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1182 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001183 }
1184
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001185 // If insert_before is null, assume BB is empty.
1186 if (insert_before == nullptr) {
1187 first_mir_insn = first_list_mir;
1188 last_mir_insn = last_list_mir;
1189 last_list_mir->next = nullptr;
1190 } else {
1191 if (first_mir_insn == insert_before) {
1192 last_list_mir->next = first_mir_insn;
1193 first_mir_insn = first_list_mir;
1194 } else {
1195 // Find the preceding MIR.
1196 MIR* before_list = FindPreviousMIR(insert_before);
1197 DCHECK(before_list != nullptr);
1198 before_list->next = first_list_mir;
1199 last_list_mir->next = insert_before;
1200 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001201 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001202
1203 // Set this BB to be the basic block of the MIRs.
1204 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1205 mir->bb = id;
1206 }
1207}
1208
1209bool BasicBlock::RemoveMIR(MIR* mir) {
1210 // Remove as a single element list.
1211 return RemoveMIRList(mir, mir);
1212}
1213
1214bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1215 if (first_list_mir == nullptr) {
1216 return false;
1217 }
1218
1219 // Try to find the MIR.
1220 MIR* before_list = nullptr;
1221 MIR* after_list = nullptr;
1222
1223 // If we are removing from the beginning of the MIR list.
1224 if (first_mir_insn == first_list_mir) {
1225 before_list = nullptr;
1226 } else {
1227 before_list = FindPreviousMIR(first_list_mir);
1228 if (before_list == nullptr) {
1229 // We did not find the mir.
1230 return false;
1231 }
1232 }
1233
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001234 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001235 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001236 mir->bb = NullBasicBlockId;
1237 }
1238
1239 after_list = last_list_mir->next;
1240
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001241 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001242 if (before_list == nullptr) {
1243 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001244 } else {
1245 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001246 }
1247
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001248 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001249 if (after_list == nullptr) {
1250 last_mir_insn = before_list;
1251 }
1252
1253 return true;
buzbee1fd33462013-03-25 13:40:45 -07001254}
1255
Vladimir Marko26e7d452014-11-24 14:09:46 +00001256MIR* BasicBlock::GetFirstNonPhiInsn() {
1257 MIR* mir = first_mir_insn;
1258 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1259 mir = mir->next;
1260 }
1261 return mir;
1262}
1263
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001264MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001265 MIR* next_mir = nullptr;
1266
1267 if (current != nullptr) {
1268 next_mir = current->next;
1269 }
1270
1271 if (next_mir == nullptr) {
1272 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001273 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1274 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001275 }
1276 }
1277
1278 return next_mir;
1279}
1280
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001281static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1282 DCHECK(decoded_mir != nullptr);
1283 OpSize type = static_cast<OpSize>(type_size >> 16);
1284 uint16_t vect_size = (type_size & 0xFFFF);
1285
1286 // Now print the type and vector size.
1287 std::stringstream ss;
1288 ss << " (type:";
1289 ss << type;
1290 ss << " vectsize:";
1291 ss << vect_size;
1292 ss << ")";
1293
1294 decoded_mir->append(ss.str());
1295}
1296
1297void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1298 DCHECK(decoded_mir != nullptr);
1299 int opcode = mir->dalvikInsn.opcode;
1300 SSARepresentation* ssa_rep = mir->ssa_rep;
1301 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1302 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1303
Vladimirf41b92c2014-10-13 13:41:38 +07001304 if (opcode < kMirOpFirst) {
1305 return; // It is not an extended instruction.
1306 }
1307
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001308 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1309
1310 switch (opcode) {
1311 case kMirOpPhi: {
1312 if (defs > 0 && uses > 0) {
1313 BasicBlockId* incoming = mir->meta.phi_incoming;
1314 decoded_mir->append(StringPrintf(" %s = (%s",
1315 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1316 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1317 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1318 for (int i = 1; i < uses; i++) {
1319 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1320 }
1321 decoded_mir->append(")");
1322 }
1323 break;
1324 }
1325 case kMirOpCopy:
1326 if (ssa_rep != nullptr) {
1327 decoded_mir->append(" ");
1328 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1329 if (defs > 1) {
1330 decoded_mir->append(", ");
1331 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1332 }
1333 decoded_mir->append(" = ");
1334 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1335 if (uses > 1) {
1336 decoded_mir->append(", ");
1337 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1338 }
1339 } else {
1340 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1341 }
1342 break;
1343 case kMirOpFusedCmplFloat:
1344 case kMirOpFusedCmpgFloat:
1345 case kMirOpFusedCmplDouble:
1346 case kMirOpFusedCmpgDouble:
1347 case kMirOpFusedCmpLong:
1348 if (ssa_rep != nullptr) {
1349 decoded_mir->append(" ");
1350 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1351 for (int i = 1; i < uses; i++) {
1352 decoded_mir->append(", ");
1353 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1354 }
1355 } else {
1356 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1357 }
1358 break;
1359 case kMirOpMoveVector:
1360 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1361 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1362 break;
1363 case kMirOpPackedAddition:
1364 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1365 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1366 break;
1367 case kMirOpPackedMultiply:
1368 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1369 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1370 break;
1371 case kMirOpPackedSubtract:
1372 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1373 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1374 break;
1375 case kMirOpPackedAnd:
1376 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1377 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1378 break;
1379 case kMirOpPackedOr:
1380 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1381 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1382 break;
1383 case kMirOpPackedXor:
1384 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1385 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1386 break;
1387 case kMirOpPackedShiftLeft:
1388 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1389 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1390 break;
1391 case kMirOpPackedUnsignedShiftRight:
1392 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1393 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1394 break;
1395 case kMirOpPackedSignedShiftRight:
1396 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1397 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1398 break;
1399 case kMirOpConstVector:
1400 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1401 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1402 break;
1403 case kMirOpPackedSet:
1404 if (ssa_rep != nullptr) {
1405 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1406 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1407 if (uses > 1) {
1408 decoded_mir->append(", ");
1409 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1410 }
1411 } else {
1412 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1413 }
1414 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1415 break;
1416 case kMirOpPackedAddReduce:
1417 if (ssa_rep != nullptr) {
1418 decoded_mir->append(" ");
1419 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1420 if (defs > 1) {
1421 decoded_mir->append(", ");
1422 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1423 }
1424 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1425 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1426 if (uses > 1) {
1427 decoded_mir->append(", ");
1428 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1429 }
1430 } else {
1431 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1432 }
1433 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1434 break;
1435 case kMirOpPackedReduce:
1436 if (ssa_rep != nullptr) {
1437 decoded_mir->append(" ");
1438 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1439 if (defs > 1) {
1440 decoded_mir->append(", ");
1441 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1442 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001443 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001444 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001445 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1446 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001447 }
1448 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1449 break;
1450 case kMirOpReserveVectorRegisters:
1451 case kMirOpReturnVectorRegisters:
1452 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1453 break;
1454 case kMirOpMemBarrier: {
1455 decoded_mir->append(" type:");
1456 std::stringstream ss;
1457 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1458 decoded_mir->append(ss.str());
1459 break;
1460 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001461 case kMirOpPackedArrayGet:
1462 case kMirOpPackedArrayPut:
1463 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1464 if (ssa_rep != nullptr) {
1465 decoded_mir->append(StringPrintf(", %s[%s]",
1466 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1467 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1468 } else {
1469 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1470 }
1471 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1472 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001473 case kMirOpMaddInt:
1474 case kMirOpMsubInt:
1475 case kMirOpMaddLong:
1476 case kMirOpMsubLong:
1477 if (ssa_rep != nullptr) {
1478 decoded_mir->append(" ");
1479 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1480 if (defs > 1) {
1481 decoded_mir->append(", ");
1482 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1483 }
1484 for (int i = 0; i < uses; i++) {
1485 decoded_mir->append(", ");
1486 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1487 }
1488 } else {
1489 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1490 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1491 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1492 }
1493 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001494 default:
1495 break;
1496 }
1497}
1498
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001499char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001500 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001501 std::string str;
1502 int flags = 0;
1503 int opcode = insn.opcode;
1504 char* ret;
1505 bool nop = false;
1506 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001507 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001508
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001509 // Handle special cases that recover the original dalvik instruction.
Vladimir Markoe299f162015-05-07 12:25:40 +01001510 if (opcode == kMirOpCheck) {
buzbee1fd33462013-03-25 13:40:45 -07001511 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1512 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001513 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001514 insn = mir->meta.throw_insn->dalvikInsn;
1515 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001516 opcode = insn.opcode;
1517 } else if (opcode == kMirOpNop) {
1518 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001519 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1520 // Recover original opcode.
1521 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1522 opcode = insn.opcode;
1523 }
buzbee1fd33462013-03-25 13:40:45 -07001524 nop = true;
1525 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001526 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1527 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001528
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001529 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001530 // Note that this does not check the MIR's opcode in all cases. In cases where it
1531 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1532 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001533 } else {
1534 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001535 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001536 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001537
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001538 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001539 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1540 (dalvik_format == Instruction::k3rc));
1541 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001542 str.append(" ");
1543 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1544 if (defs > 1) {
1545 str.append(", ");
1546 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1547 }
buzbee1fd33462013-03-25 13:40:45 -07001548 if (uses != 0) {
1549 str.append(", ");
1550 }
1551 }
1552 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001553 str.append(" ");
1554 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001555 if (!show_singles && (reg_location_ != nullptr) && reg_location_[i].wide) {
buzbee1fd33462013-03-25 13:40:45 -07001556 // For the listing, skip the high sreg.
1557 i++;
1558 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001559 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001560 str.append(",");
1561 }
1562 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001563
buzbee1fd33462013-03-25 13:40:45 -07001564 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001565 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001566 case Instruction::k21s:
1567 case Instruction::k31i:
1568 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001569 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001570 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001571 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001572 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001573 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001574 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001575 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001576 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001577 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001578 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001579 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001580 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001581 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001582 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001583 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001584 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001585 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001586 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001587 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001588 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001589
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001590 if ((flags & Instruction::kBranch) != 0) {
1591 // For branches, decode the instructions to print out the branch targets.
1592 int offset = 0;
1593 switch (dalvik_format) {
1594 case Instruction::k21t:
1595 offset = insn.vB;
1596 break;
1597 case Instruction::k22t:
1598 offset = insn.vC;
1599 break;
1600 case Instruction::k10t:
1601 case Instruction::k20t:
1602 case Instruction::k30t:
1603 offset = insn.vA;
1604 break;
1605 default:
1606 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001607 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001608 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001609 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001610 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1611 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001612
1613 if (nop) {
1614 str.append("]--optimized away");
1615 }
buzbee1fd33462013-03-25 13:40:45 -07001616 }
1617 int length = str.length() + 1;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001618 ret = arena_->AllocArray<char>(length, kArenaAllocDFInfo);
buzbee1fd33462013-03-25 13:40:45 -07001619 strncpy(ret, str.c_str(), length);
1620 return ret;
1621}
1622
1623/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001624void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001625 static const struct { const char before; const char after; } match[] = {
1626 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1627 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1628 };
buzbee1fd33462013-03-25 13:40:45 -07001629 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1630 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1631 }
1632}
1633
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001634std::string MIRGraph::GetSSAName(int ssa_reg) {
Andreas Gampec7399c82015-04-07 19:58:03 -07001635 // TODO: This value is needed for debugging. Currently, we compute this and then copy to the
1636 // arena. We should be smarter and just place straight into the arena, or compute the
Ian Rogers39ebcb82013-05-30 16:57:23 -07001637 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001638 int vreg = SRegToVReg(ssa_reg);
1639 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1640 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1641 } else {
1642 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1643 }
buzbee1fd33462013-03-25 13:40:45 -07001644}
1645
1646// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001647std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001648 if (reg_location_ == nullptr) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001649 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001650 return GetSSAName(ssa_reg);
1651 }
1652 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001653 if (!singles_only && reg_location_[ssa_reg].wide &&
1654 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001655 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001656 ConstantValueWide(reg_location_[ssa_reg]));
1657 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001658 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001659 ConstantValue(reg_location_[ssa_reg]));
1660 }
1661 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001662 int vreg = SRegToVReg(ssa_reg);
1663 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1664 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1665 } else {
1666 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1667 }
buzbee1fd33462013-03-25 13:40:45 -07001668 }
1669}
1670
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001671void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001672 switch (bb->block_type) {
1673 case kEntryBlock:
1674 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1675 break;
1676 case kExitBlock:
1677 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1678 break;
1679 case kDalvikByteCode:
1680 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1681 break;
1682 case kExceptionHandling:
1683 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1684 bb->id);
1685 break;
1686 default:
1687 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1688 break;
1689 }
1690}
1691
Serguei Katkov717a3e42014-11-13 17:19:42 +06001692const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1693 const DexFile::MethodId& method_id =
1694 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1695 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1696}
1697
buzbee1fd33462013-03-25 13:40:45 -07001698/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001699void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001700 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001701 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001702 "Entry Block",
1703 "Code Block",
1704 "Exit Block",
1705 "Exception Handling",
1706 "Catch Block"
1707 };
1708
1709 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001710 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001711 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001712
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001713 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001714 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1715 bb->id,
1716 block_type_names[bb->block_type],
1717 bb->start_offset,
1718 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1719 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001720 if (bb->taken != NullBasicBlockId) {
1721 LOG(INFO) << " Taken branch: block " << bb->taken
1722 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001723 }
buzbee0d829482013-10-11 15:24:55 -07001724 if (bb->fall_through != NullBasicBlockId) {
1725 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1726 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001727 }
1728 }
1729}
1730
1731/*
1732 * Build an array of location records for the incoming arguments.
1733 * Note: one location record per word of arguments, with dummy
1734 * high-word loc for wide arguments. Also pull up any following
1735 * MOVE_RESULT and incorporate it into the invoke.
1736 */
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001737CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type, bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001738 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001739 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001740 MIR* move_result_mir = FindMoveResult(bb, mir);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001741 if (move_result_mir == nullptr) {
buzbee1fd33462013-03-25 13:40:45 -07001742 info->result.location = kLocInvalid;
1743 } else {
1744 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001745 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1746 }
1747 info->num_arg_words = mir->ssa_rep->num_uses;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001748 info->args = (info->num_arg_words == 0) ? nullptr :
1749 arena_->AllocArray<RegLocation>(info->num_arg_words, kArenaAllocMisc);
Vladimir Marko6ce3eba2015-02-16 13:05:59 +00001750 for (size_t i = 0; i < info->num_arg_words; i++) {
buzbee1fd33462013-03-25 13:40:45 -07001751 info->args[i] = GetRawSrc(mir, i);
1752 }
1753 info->opt_flags = mir->optimization_flags;
1754 info->type = type;
1755 info->is_range = is_range;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001756 if (IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) {
1757 const auto& method_info = GetMethodLoweringInfo(mir);
1758 info->method_ref = method_info.GetTargetMethod();
1759 } else {
1760 info->method_ref = MethodReference(GetCurrentDexCompilationUnit()->GetDexFile(),
1761 mir->dalvikInsn.vB);
1762 }
buzbee1fd33462013-03-25 13:40:45 -07001763 info->index = mir->dalvikInsn.vB;
1764 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001765 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001766 return info;
1767}
1768
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001769// Allocate a new MIR.
1770MIR* MIRGraph::NewMIR() {
1771 MIR* mir = new (arena_) MIR();
1772 return mir;
1773}
1774
buzbee862a7602013-04-05 10:58:54 -07001775// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001776BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001777 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001778
buzbee862a7602013-04-05 10:58:54 -07001779 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001780 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001781 block_id_map_.Put(block_id, block_id);
1782 return bb;
1783}
buzbee1fd33462013-03-25 13:40:45 -07001784
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001785void MIRGraph::InitializeConstantPropagation() {
1786 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001787 constant_values_ = arena_->AllocArray<int>(GetNumSSARegs(), kArenaAllocDFInfo);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001788}
1789
1790void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001791 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001792 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001793 use_counts_.clear();
1794 use_counts_.reserve(num_ssa_regs + 32);
1795 use_counts_.resize(num_ssa_regs, 0u);
1796 raw_use_counts_.clear();
1797 raw_use_counts_.reserve(num_ssa_regs + 32);
1798 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001799}
1800
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001801void MIRGraph::SSATransformationStart() {
1802 DCHECK(temp_scoped_alloc_.get() == nullptr);
1803 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001804 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1805 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1806 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001807}
1808
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001809void MIRGraph::SSATransformationEnd() {
1810 // Verify the dataflow information after the pass.
1811 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1812 VerifyDataflow();
1813 }
1814
Vladimir Markof585e542014-11-21 13:41:32 +00001815 temp_.ssa.num_vregs = 0u;
1816 temp_.ssa.work_live_vregs = nullptr;
Vladimir Marko6a8946b2015-02-09 12:35:05 +00001817 DCHECK(temp_.ssa.def_block_matrix == nullptr);
1818 temp_.ssa.phi_node_blocks = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001819 DCHECK(temp_scoped_alloc_.get() != nullptr);
1820 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001821
1822 // Update the maximum number of reachable blocks.
1823 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001824
1825 // Mark MIR SSA representations as up to date.
1826 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001827}
1828
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001829size_t MIRGraph::GetNumDalvikInsns() const {
1830 size_t cumulative_size = 0u;
1831 bool counted_current_item = false;
1832 const uint8_t size_for_null_code_item = 2u;
1833
1834 for (auto it : m_units_) {
1835 const DexFile::CodeItem* code_item = it->GetCodeItem();
1836 // Even if the code item is null, we still count non-zero value so that
1837 // each m_unit is counted as having impact.
1838 cumulative_size += (code_item == nullptr ?
1839 size_for_null_code_item : code_item->insns_size_in_code_units_);
1840 if (code_item == current_code_item_) {
1841 counted_current_item = true;
1842 }
1843 }
1844
1845 // If the current code item was not counted yet, count it now.
1846 // This can happen for example in unit tests where some fields like m_units_
1847 // are not initialized.
1848 if (counted_current_item == false) {
1849 cumulative_size += (current_code_item_ == nullptr ?
1850 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1851 }
1852
1853 return cumulative_size;
1854}
1855
Vladimir Marko55fff042014-07-10 12:42:52 +01001856static BasicBlock* SelectTopologicalSortOrderFallBack(
1857 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1858 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1859 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1860 // No true loop head has been found but there may be true loop heads after the mess we need
1861 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1862 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1863 BasicBlock* fall_back = nullptr;
1864 size_t fall_back_num_reachable = 0u;
1865 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1866 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1867 AllNodesIterator iter(mir_graph);
1868 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1869 if (candidate->hidden || // Hidden, or
1870 candidate->visited || // already processed, or
1871 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1872 (current_loop != nullptr && // outside current loop.
1873 !current_loop->IsBitSet(candidate->id))) {
1874 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001875 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001876 DCHECK(tmp_stack->empty());
1877 tmp_stack->push_back(candidate->id);
1878 candidate_reachable.ClearAllBits();
1879 size_t num_reachable = 0u;
1880 while (!tmp_stack->empty()) {
1881 BasicBlockId current_id = tmp_stack->back();
1882 tmp_stack->pop_back();
1883 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1884 DCHECK(current_bb != nullptr);
1885 ChildBlockIterator child_iter(current_bb, mir_graph);
1886 BasicBlock* child_bb = child_iter.Next();
1887 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1888 DCHECK(!child_bb->hidden);
1889 if (child_bb->visited || // Already processed, or
1890 (current_loop != nullptr && // outside current loop.
1891 !current_loop->IsBitSet(child_bb->id))) {
1892 continue;
1893 }
1894 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1895 candidate_reachable.SetBit(child_bb->id);
1896 tmp_stack->push_back(child_bb->id);
1897 num_reachable += 1u;
1898 }
1899 }
1900 }
1901 if (fall_back_num_reachable < num_reachable) {
1902 fall_back_num_reachable = num_reachable;
1903 fall_back = candidate;
1904 }
1905 }
1906 return fall_back;
1907}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001908
Vladimir Marko55fff042014-07-10 12:42:52 +01001909// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1910static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1911 ArenaBitVector* reachable,
1912 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1913 // NOTE: Loop heads indicated by the "visited" flag.
1914 DCHECK(tmp_stack->empty());
1915 reachable->ClearAllBits();
1916 tmp_stack->push_back(bb_id);
1917 while (!tmp_stack->empty()) {
1918 BasicBlockId current_id = tmp_stack->back();
1919 tmp_stack->pop_back();
1920 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1921 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001922 for (BasicBlockId pred_id : current_bb->predecessors) {
1923 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1924 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001925 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1926 reachable->SetBit(pred_bb->id);
1927 tmp_stack->push_back(pred_bb->id);
1928 }
1929 }
1930 }
1931}
1932
1933void MIRGraph::ComputeTopologicalSortOrder() {
1934 ScopedArenaAllocator allocator(&cu_->arena_stack);
1935 unsigned int num_blocks = GetNumBlocks();
1936
1937 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1938 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1939 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1940 size_t max_nested_loops = 0u;
1941 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1942 loop_exit_blocks.ClearAllBits();
1943
1944 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001945 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001946 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001947 if (bb->hidden == true) {
1948 continue;
1949 }
1950
Vladimir Marko55fff042014-07-10 12:42:52 +01001951 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001952
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001953 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001955 q.push(bb);
1956 }
1957 }
1958
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001959 // Clear the topological order arrays.
1960 topological_order_.clear();
1961 topological_order_.reserve(num_blocks);
1962 topological_order_loop_ends_.clear();
1963 topological_order_loop_ends_.resize(num_blocks, 0u);
1964 topological_order_indexes_.clear();
1965 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001966
1967 // Mark all blocks as unvisited.
1968 ClearAllVisitedFlags();
1969
1970 // For loop heads, keep track from which blocks they are reachable not going through other
1971 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1972 // in this set go into the loop body, the other children are jumping over the loop.
1973 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1974 loop_head_reachable_from.resize(num_blocks, nullptr);
1975 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1976 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1977
1978 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001979 BasicBlock* bb = nullptr;
1980 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001981 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001982 // Get top.
1983 bb = q.front();
1984 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001985 if (bb->visited) {
1986 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1987 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001988 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1989 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001990 DCHECK_EQ(loop_head_stack.back(), bb->id);
1991 loop_head_stack.pop_back();
1992 ArenaBitVector* reachable =
1993 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1994 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1995 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1996 q.push(GetBasicBlock(candidate_id));
1997 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1998 // so clearing the bit has no effect on the iterator.
1999 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002000 }
2001 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002002 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002003 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002004 } else {
2005 // Find the new loop head.
2006 AllNodesIterator iter(this);
2007 while (true) {
2008 BasicBlock* candidate = iter.Next();
2009 if (candidate == nullptr) {
2010 // We did not find a true loop head, fall back to a reachable block in any loop.
2011 ArenaBitVector* current_loop =
2012 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
2013 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
2014 &allocator, &tmp_stack);
2015 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
2016 if (kIsDebugBuild && cu_->dex_file != nullptr) {
2017 LOG(INFO) << "Topological sort order: Using fall-back in "
2018 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
2019 << " @0x" << std::hex << bb->start_offset
2020 << ", num_blocks = " << std::dec << num_blocks;
2021 }
2022 break;
2023 }
2024 if (candidate->hidden || // Hidden, or
2025 candidate->visited || // already processed, or
2026 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
2027 (!loop_head_stack.empty() && // outside current loop.
2028 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
2029 continue;
2030 }
2031
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002032 for (BasicBlockId pred_id : candidate->predecessors) {
2033 BasicBlock* pred_bb = GetBasicBlock(pred_id);
2034 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01002035 if (pred_bb != candidate && !pred_bb->visited &&
2036 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002037 candidate = nullptr; // Set candidate to null to indicate failure.
2038 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01002039 }
2040 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002041 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002042 bb = candidate;
2043 break;
2044 }
2045 }
2046 // Compute blocks from which the loop head is reachable and process those blocks first.
2047 ArenaBitVector* reachable =
2048 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
2049 loop_head_reachable_from[bb->id] = reachable;
2050 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
2051 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
2052 loop_head_stack.push_back(bb->id);
2053 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002054 }
2055
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002056 DCHECK_EQ(bb->hidden, false);
2057 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002058 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00002059 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002060
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002061 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002062 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
2063 topological_order_indexes_[bb->id] = idx;
2064 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002065
Vladimir Marko55fff042014-07-10 12:42:52 +01002066 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002067 ChildBlockIterator succIter(bb, this);
2068 BasicBlock* successor = succIter.Next();
2069 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002070 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002071 continue;
2072 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002073
Vladimir Marko55fff042014-07-10 12:42:52 +01002074 // One more predecessor was visited.
2075 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002076 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002077 if (loop_head_stack.empty() ||
2078 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2079 q.push(successor);
2080 } else {
2081 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2082 loop_exit_blocks.SetBit(successor->id);
2083 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002084 }
2085 }
2086 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002087
2088 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002089 topological_order_loop_head_stack_.clear();
2090 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002091 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002092 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002093}
2094
2095bool BasicBlock::IsExceptionBlock() const {
2096 if (block_type == kExceptionHandling) {
2097 return true;
2098 }
2099 return false;
2100}
2101
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002102ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2103 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2104 visited_taken_(false), have_successors_(false) {
2105 // Check if we actually do have successors.
2106 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2107 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002108 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002109 }
2110}
2111
2112BasicBlock* ChildBlockIterator::Next() {
2113 // We check if we have a basic block. If we don't we cannot get next child.
2114 if (basic_block_ == nullptr) {
2115 return nullptr;
2116 }
2117
2118 // If we haven't visited fallthrough, return that.
2119 if (visited_fallthrough_ == false) {
2120 visited_fallthrough_ = true;
2121
2122 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2123 if (result != nullptr) {
2124 return result;
2125 }
2126 }
2127
2128 // If we haven't visited taken, return that.
2129 if (visited_taken_ == false) {
2130 visited_taken_ = true;
2131
2132 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2133 if (result != nullptr) {
2134 return result;
2135 }
2136 }
2137
2138 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2139 if (have_successors_ == true) {
2140 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002141 auto end = basic_block_->successor_blocks.cend();
2142 while (successor_iter_ != end) {
2143 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2144 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002145 // If block was replaced by zero block, take next one.
2146 if (successor_block_info->block != NullBasicBlockId) {
2147 return mir_graph_->GetBasicBlock(successor_block_info->block);
2148 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002149 }
2150 }
2151
2152 // We do not have anything.
2153 return nullptr;
2154}
2155
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002156BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2157 MIRGraph* mir_graph = c_unit->mir_graph.get();
2158 return Copy(mir_graph);
2159}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002160
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002161BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2162 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002163
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002164 // We don't do a memcpy style copy here because it would lead to a lot of things
2165 // to clean up. Let us do it by hand instead.
2166 // Copy in taken and fallthrough.
2167 result_bb->fall_through = fall_through;
2168 result_bb->taken = taken;
2169
2170 // Copy successor links if needed.
2171 ArenaAllocator* arena = mir_graph->GetArena();
2172
2173 result_bb->successor_block_list_type = successor_block_list_type;
2174 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002175 result_bb->successor_blocks.reserve(successor_blocks.size());
2176 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2177 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2178 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002179 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002180 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002181 }
2182 }
2183
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002184 // Copy offset, method.
2185 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002186
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002187 // Now copy instructions.
2188 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2189 // Get a copy first.
2190 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002191
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002192 // Append it.
2193 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002194 }
2195
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002196 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002197}
2198
2199MIR* MIR::Copy(MIRGraph* mir_graph) {
2200 MIR* res = mir_graph->NewMIR();
2201 *res = *this;
2202
2203 // Remove links
2204 res->next = nullptr;
2205 res->bb = NullBasicBlockId;
2206 res->ssa_rep = nullptr;
2207
2208 return res;
2209}
2210
2211MIR* MIR::Copy(CompilationUnit* c_unit) {
2212 return Copy(c_unit->mir_graph.get());
2213}
2214
2215uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2216 // Default result.
2217 int res = 0;
2218
2219 // We are basically setting the iputs to their igets counterparts.
2220 switch (opcode) {
2221 case Instruction::IPUT:
2222 case Instruction::IPUT_OBJECT:
2223 case Instruction::IPUT_BOOLEAN:
2224 case Instruction::IPUT_BYTE:
2225 case Instruction::IPUT_CHAR:
2226 case Instruction::IPUT_SHORT:
2227 case Instruction::IPUT_QUICK:
2228 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002229 case Instruction::IPUT_BOOLEAN_QUICK:
2230 case Instruction::IPUT_BYTE_QUICK:
2231 case Instruction::IPUT_CHAR_QUICK:
2232 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002233 case Instruction::APUT:
2234 case Instruction::APUT_OBJECT:
2235 case Instruction::APUT_BOOLEAN:
2236 case Instruction::APUT_BYTE:
2237 case Instruction::APUT_CHAR:
2238 case Instruction::APUT_SHORT:
2239 case Instruction::SPUT:
2240 case Instruction::SPUT_OBJECT:
2241 case Instruction::SPUT_BOOLEAN:
2242 case Instruction::SPUT_BYTE:
2243 case Instruction::SPUT_CHAR:
2244 case Instruction::SPUT_SHORT:
2245 // Skip the VR containing what to store.
2246 res = 1;
2247 break;
2248 case Instruction::IPUT_WIDE:
2249 case Instruction::IPUT_WIDE_QUICK:
2250 case Instruction::APUT_WIDE:
2251 case Instruction::SPUT_WIDE:
2252 // Skip the two VRs containing what to store.
2253 res = 2;
2254 break;
2255 default:
2256 // Do nothing in the general case.
2257 break;
2258 }
2259
2260 return res;
2261}
2262
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002263/**
2264 * @brief Given a decoded instruction, it checks whether the instruction
2265 * sets a constant and if it does, more information is provided about the
2266 * constant being set.
2267 * @param ptr_value pointer to a 64-bit holder for the constant.
2268 * @param wide Updated by function whether a wide constant is being set by bytecode.
2269 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2270 */
2271bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2272 bool sets_const = true;
2273 int64_t value = vB;
2274
2275 DCHECK(ptr_value != nullptr);
2276 DCHECK(wide != nullptr);
2277
2278 switch (opcode) {
2279 case Instruction::CONST_4:
2280 case Instruction::CONST_16:
2281 case Instruction::CONST:
2282 *wide = false;
2283 value <<= 32; // In order to get the sign extend.
2284 value >>= 32;
2285 break;
2286 case Instruction::CONST_HIGH16:
2287 *wide = false;
2288 value <<= 48; // In order to get the sign extend.
2289 value >>= 32;
2290 break;
2291 case Instruction::CONST_WIDE_16:
2292 case Instruction::CONST_WIDE_32:
2293 *wide = true;
2294 value <<= 32; // In order to get the sign extend.
2295 value >>= 32;
2296 break;
2297 case Instruction::CONST_WIDE:
2298 *wide = true;
2299 value = vB_wide;
2300 break;
2301 case Instruction::CONST_WIDE_HIGH16:
2302 *wide = true;
2303 value <<= 48; // In order to get the sign extend.
2304 break;
2305 default:
2306 sets_const = false;
2307 break;
2308 }
2309
2310 if (sets_const) {
2311 *ptr_value = value;
2312 }
2313
2314 return sets_const;
2315}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002316
2317void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2318 // Reset flags for all MIRs in bb.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002319 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002320 mir->optimization_flags &= (~reset_flags);
2321 }
2322}
2323
Vladimir Markocb873d82014-12-08 15:16:54 +00002324void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002325 for (BasicBlockId pred_id : predecessors) {
2326 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2327 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002328
2329 // Sadly we have to go through the children by hand here.
2330 pred_bb->ReplaceChild(id, NullBasicBlockId);
2331 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002332 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002333
Vladimir Marko312eb252014-10-07 15:01:57 +01002334 // Mark as dead and hidden.
2335 block_type = kDead;
2336 hidden = true;
2337
2338 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2339 // are updated to know that they no longer have a parent.
2340 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2341 mir->bb = NullBasicBlockId;
2342 }
2343 first_mir_insn = nullptr;
2344 last_mir_insn = nullptr;
2345
2346 data_flow_info = nullptr;
2347
2348 // Erase this bb from all children's predecessors and kill unreachable children.
2349 ChildBlockIterator iter(this, mir_graph);
2350 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2351 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002352 }
2353
2354 // Remove links to children.
2355 fall_through = NullBasicBlockId;
2356 taken = NullBasicBlockId;
2357 successor_block_list_type = kNotUsed;
2358
2359 if (kIsDebugBuild) {
2360 if (catch_entry) {
2361 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2362 mir_graph->catches_.erase(start_offset);
2363 }
2364 }
2365}
2366
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002367bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2368 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2369 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2370 // then it is not live out of this BB.
2371 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2372
2373 int last_ssa_reg = -1;
2374
2375 // Walk through the MIRs backwards.
2376 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2377 // Get ssa rep.
2378 SSARepresentation *ssa_rep = mir->ssa_rep;
2379
2380 // Go through the defines for this MIR.
2381 for (int i = 0; i < ssa_rep->num_defs; i++) {
2382 DCHECK(ssa_rep->defs != nullptr);
2383
2384 // Get the ssa reg.
2385 int def_ssa_reg = ssa_rep->defs[i];
2386
2387 // Get dalvik reg.
2388 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2389
2390 // Compare dalvik regs.
2391 if (dalvik_reg == def_dalvik_reg) {
2392 // We found a def of the register that we are being asked about.
2393 // Remember it.
2394 last_ssa_reg = def_ssa_reg;
2395 }
2396 }
2397 }
2398
2399 if (last_ssa_reg == -1) {
2400 // If we get to this point we couldn't find a define of register user asked about.
2401 // Let's assume the user knows what he's doing so we can be safe and say that if we
2402 // couldn't find a def, it is live out.
2403 return true;
2404 }
2405
2406 // If it is not -1, we found a match, is it ssa_reg?
2407 return (ssa_reg == last_ssa_reg);
2408}
2409
2410bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2411 // We need to check taken, fall_through, and successor_blocks to replace.
2412 bool found = false;
2413 if (taken == old_bb) {
2414 taken = new_bb;
2415 found = true;
2416 }
2417
2418 if (fall_through == old_bb) {
2419 fall_through = new_bb;
2420 found = true;
2421 }
2422
2423 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002424 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002425 if (successor_block_info->block == old_bb) {
2426 successor_block_info->block = new_bb;
2427 found = true;
2428 }
2429 }
2430 }
2431
2432 return found;
2433}
2434
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002435void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2436 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2437 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002438 // It's faster to move the back() to *pos than erase(pos).
2439 *pos = predecessors.back();
2440 predecessors.pop_back();
2441 size_t idx = std::distance(predecessors.begin(), pos);
2442 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2443 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2444 break;
2445 }
2446 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2447 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2448 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2449 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2450 mir->ssa_rep->num_uses = predecessors.size();
2451 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002452}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002453
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002454void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2455 DCHECK_NE(new_pred, NullBasicBlockId);
2456 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002457 DCHECK(pos != predecessors.end());
2458 *pos = new_pred;
2459 size_t idx = std::distance(predecessors.begin(), pos);
2460 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2461 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2462 break;
2463 }
2464 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2465 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002466 }
2467}
2468
2469// Create a new basic block with block_id as num_blocks_ that is
2470// post-incremented.
2471BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002472 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2473 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002474 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002475 return res;
2476}
2477
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00002478void MIRGraph::CalculateBasicBlockInformation(const PassManager* const post_opt_pass_manager) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -08002479 /* Create the pass driver and launch it */
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00002480 PassDriverMEPostOpt driver(post_opt_pass_manager, cu_);
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002481 driver.Launch();
2482}
2483
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002484int MIR::DecodedInstruction::FlagsOf() const {
2485 // Calculate new index.
2486 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2487
2488 // Check if it is an extended or not.
2489 if (idx < 0) {
2490 return Instruction::FlagsOf(opcode);
2491 }
2492
2493 // For extended, we use a switch.
2494 switch (static_cast<int>(opcode)) {
2495 case kMirOpPhi:
2496 return Instruction::kContinue;
2497 case kMirOpCopy:
2498 return Instruction::kContinue;
2499 case kMirOpFusedCmplFloat:
2500 return Instruction::kContinue | Instruction::kBranch;
2501 case kMirOpFusedCmpgFloat:
2502 return Instruction::kContinue | Instruction::kBranch;
2503 case kMirOpFusedCmplDouble:
2504 return Instruction::kContinue | Instruction::kBranch;
2505 case kMirOpFusedCmpgDouble:
2506 return Instruction::kContinue | Instruction::kBranch;
2507 case kMirOpFusedCmpLong:
2508 return Instruction::kContinue | Instruction::kBranch;
2509 case kMirOpNop:
2510 return Instruction::kContinue;
2511 case kMirOpNullCheck:
2512 return Instruction::kContinue | Instruction::kThrow;
2513 case kMirOpRangeCheck:
2514 return Instruction::kContinue | Instruction::kThrow;
2515 case kMirOpDivZeroCheck:
2516 return Instruction::kContinue | Instruction::kThrow;
2517 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002518 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002519 case kMirOpSelect:
2520 return Instruction::kContinue;
2521 case kMirOpConstVector:
2522 return Instruction::kContinue;
2523 case kMirOpMoveVector:
2524 return Instruction::kContinue;
2525 case kMirOpPackedMultiply:
2526 return Instruction::kContinue;
2527 case kMirOpPackedAddition:
2528 return Instruction::kContinue;
2529 case kMirOpPackedSubtract:
2530 return Instruction::kContinue;
2531 case kMirOpPackedShiftLeft:
2532 return Instruction::kContinue;
2533 case kMirOpPackedSignedShiftRight:
2534 return Instruction::kContinue;
2535 case kMirOpPackedUnsignedShiftRight:
2536 return Instruction::kContinue;
2537 case kMirOpPackedAnd:
2538 return Instruction::kContinue;
2539 case kMirOpPackedOr:
2540 return Instruction::kContinue;
2541 case kMirOpPackedXor:
2542 return Instruction::kContinue;
2543 case kMirOpPackedAddReduce:
2544 return Instruction::kContinue;
2545 case kMirOpPackedReduce:
2546 return Instruction::kContinue;
2547 case kMirOpPackedSet:
2548 return Instruction::kContinue;
2549 case kMirOpReserveVectorRegisters:
2550 return Instruction::kContinue;
2551 case kMirOpReturnVectorRegisters:
2552 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002553 case kMirOpMemBarrier:
2554 return Instruction::kContinue;
2555 case kMirOpPackedArrayGet:
2556 return Instruction::kContinue | Instruction::kThrow;
2557 case kMirOpPackedArrayPut:
2558 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002559 case kMirOpMaddInt:
2560 case kMirOpMsubInt:
2561 case kMirOpMaddLong:
2562 case kMirOpMsubLong:
2563 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002564 default:
2565 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2566 return 0;
2567 }
2568}
Andreas Gampe0b9203e2015-01-22 20:39:27 -08002569
2570const uint16_t* MIRGraph::GetInsns(int m_unit_index) const {
2571 return m_units_[m_unit_index]->GetCodeItem()->insns_;
2572}
2573
Vladimir Marko7a01dc22015-01-02 17:00:44 +00002574void MIRGraph::SetPuntToInterpreter(bool val) {
2575 punt_to_interpreter_ = val;
2576 if (val) {
2577 // Disable all subsequent optimizations. They may not be safe to run. (For example,
2578 // LVN/GVN assumes there are no conflicts found by the type inference pass.)
2579 cu_->disable_opt = ~static_cast<decltype(cu_->disable_opt)>(0);
2580 }
2581}
2582
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002583} // namespace art