blob: 023abca64efc2937b4fad349a611436c7c0ebddd [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070023#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070026#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010027#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000030#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070031#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010033#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000034
buzbee311ca162013-02-28 15:56:43 -080035namespace art {
36
37#define MAX_PATTERN_LEN 5
38
buzbee1fd33462013-03-25 13:40:45 -070039const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
40 "Phi",
41 "Copy",
42 "FusedCmplFloat",
43 "FusedCmpgFloat",
44 "FusedCmplDouble",
45 "FusedCmpgDouble",
46 "FusedCmpLong",
47 "Nop",
48 "OpNullCheck",
49 "OpRangeCheck",
50 "OpDivZeroCheck",
51 "Check1",
52 "Check2",
53 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040054 "ConstVector",
55 "MoveVector",
56 "PackedMultiply",
57 "PackedAddition",
58 "PackedSubtract",
59 "PackedShiftLeft",
60 "PackedSignedShiftRight",
61 "PackedUnsignedShiftRight",
62 "PackedAnd",
63 "PackedOr",
64 "PackedXor",
65 "PackedAddReduce",
66 "PackedReduce",
67 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070068 "ReserveVectorRegisters",
69 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070070 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070071 "PackedArrayGet",
72 "PackedArrayPut",
buzbee1fd33462013-03-25 13:40:45 -070073};
74
buzbee862a7602013-04-05 10:58:54 -070075MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070076 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010077 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070078 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010079 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
80 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
buzbee311ca162013-02-28 15:56:43 -080081 vreg_to_ssa_map_(NULL),
82 ssa_last_defs_(NULL),
83 is_constant_v_(NULL),
84 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010085 use_counts_(arena->Adapter()),
86 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080087 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070088 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010089 dfs_orders_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010090 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
91 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
92 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
93 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
94 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
95 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
96 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +010097 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -080098 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000099 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100100 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800101 try_block_addr_(NULL),
102 entry_block_(NULL),
103 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800104 num_blocks_(0),
105 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100106 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100107 m_units_(arena->Adapter()),
108 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800109 current_method_(kInvalidEntry),
110 current_offset_(kInvalidEntry),
111 def_count_(0),
112 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700113 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100114 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700115 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700116 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
117 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700118 arena_(arena),
119 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800120 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800121 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700122 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
123 requested_backend_temp_(false),
124 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000125 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000126 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100127 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
128 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
129 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
130 gen_suspend_test_list_(arena->Adapter()) {
Vladimir Markof585e542014-11-21 13:41:32 +0000131 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100132 use_counts_.reserve(256);
133 raw_use_counts_.reserve(256);
134 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700135 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700136
137
138 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
139 // X86 requires a temp to keep track of the method address.
140 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
141 // this needs to be updated to reserve 0 temps for BE.
142 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
143 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
144 } else {
145 // Other architectures do not have a known lower bound for non-special temps.
146 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
147 max_available_non_special_compiler_temps_ = 0;
148 reserved_temps_for_backend_ = 0;
149 }
buzbee311ca162013-02-28 15:56:43 -0800150}
151
Ian Rogers6282dc12013-04-18 15:54:02 -0700152MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100153 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700154 STLDeleteElements(&m_units_);
155}
156
buzbee311ca162013-02-28 15:56:43 -0800157/*
158 * Parse an instruction, return the length of the instruction
159 */
Ian Rogers29a26482014-05-02 15:27:29 -0700160int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
161 const Instruction* inst = Instruction::At(code_ptr);
162 decoded_instruction->opcode = inst->Opcode();
163 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
164 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
165 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
166 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
167 if (inst->HasVarArgs()) {
168 inst->GetVarArgs(decoded_instruction->arg);
169 }
170 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800171}
172
173
174/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700175BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700176 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700177 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800178 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400179 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800180 while (insn) {
181 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700182 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800183 insn = insn->next;
184 }
185 if (insn == NULL) {
186 LOG(FATAL) << "Break split failed";
187 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400188 // Now insn is at the instruction where we want to split, namely
189 // insn will be the first instruction of the "bottom" block.
190 // Similarly, prev will be the last instruction of the "top" block
191
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100192 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800193
194 bottom_block->start_offset = code_offset;
195 bottom_block->first_mir_insn = insn;
196 bottom_block->last_mir_insn = orig_block->last_mir_insn;
197
Junmo Park90223cc2014-08-04 18:51:21 +0900198 /* If this block was terminated by a return, conditional branch or throw,
199 * the flag needs to go with the bottom block
200 */
buzbee311ca162013-02-28 15:56:43 -0800201 bottom_block->terminated_by_return = orig_block->terminated_by_return;
202 orig_block->terminated_by_return = false;
203
Junmo Park90223cc2014-08-04 18:51:21 +0900204 bottom_block->conditional_branch = orig_block->conditional_branch;
205 orig_block->conditional_branch = false;
206
207 bottom_block->explicit_throw = orig_block->explicit_throw;
208 orig_block->explicit_throw = false;
209
buzbee311ca162013-02-28 15:56:43 -0800210 /* Handle the taken path */
211 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700212 if (bottom_block->taken != NullBasicBlockId) {
213 orig_block->taken = NullBasicBlockId;
214 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100215 bb_taken->ErasePredecessor(orig_block->id);
216 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800217 }
218
219 /* Handle the fallthrough path */
220 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700221 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100222 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700223 if (bottom_block->fall_through != NullBasicBlockId) {
224 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100225 bb_fall_through->ErasePredecessor(orig_block->id);
226 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800227 }
228
229 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700230 if (orig_block->successor_block_list_type != kNotUsed) {
231 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100232 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700233 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100234 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
235 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700236 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700237 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 bb->ErasePredecessor(orig_block->id);
239 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700240 }
buzbee311ca162013-02-28 15:56:43 -0800241 }
242 }
243
buzbee0d829482013-10-11 15:24:55 -0700244 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700245 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800246
buzbee311ca162013-02-28 15:56:43 -0800247 /*
248 * Update the immediate predecessor block pointer so that outgoing edges
249 * can be applied to the proper block.
250 */
251 if (immed_pred_block_p) {
252 DCHECK_EQ(*immed_pred_block_p, orig_block);
253 *immed_pred_block_p = bottom_block;
254 }
buzbeeb48819d2013-09-14 16:15:25 -0700255
256 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000257 DCHECK(insn != nullptr);
258 DCHECK(insn != orig_block->first_mir_insn);
259 DCHECK(insn == bottom_block->first_mir_insn);
260 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100261 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400262 // Scan the "bottom" instructions, remapping them to the
263 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000264 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400265 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100266 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000267 while (p != bottom_block->last_mir_insn) {
268 p = p->next;
269 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700270 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700271 int opcode = p->dalvikInsn.opcode;
272 /*
273 * Some messiness here to ensure that we only enter real opcodes and only the
274 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000275 * CHECK and work portions. Since the 2nd half of a split operation is always
276 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700277 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700278 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400279 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
280 // At first glance the instructions should all be mapped to orig_block.
281 // However, multiple instructions may correspond to the same dex, hence an earlier
282 // instruction may have already moved the mapping for dex to bottom_block.
283 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100284 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700285 }
buzbeeb48819d2013-09-14 16:15:25 -0700286 }
287
buzbee311ca162013-02-28 15:56:43 -0800288 return bottom_block;
289}
290
291/*
292 * Given a code offset, find out the block that starts with it. If the offset
293 * is in the middle of an existing block, split it into two. If immed_pred_block_p
294 * is not non-null and is the block being split, update *immed_pred_block_p to
295 * point to the bottom block so that outgoing edges can be set up properly
296 * (by the caller)
297 * Utilizes a map for fast lookup of the typical cases.
298 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700299BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700300 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700301 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700302 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800303 }
buzbeeb48819d2013-09-14 16:15:25 -0700304
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100305 int block_id = dex_pc_to_block_map_[code_offset];
306 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700307
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700308 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700309 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700310 return bb;
311 }
buzbee311ca162013-02-28 15:56:43 -0800312
buzbeeb48819d2013-09-14 16:15:25 -0700313 // No direct hit.
314 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700315 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800316 }
317
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700318 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700319 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700320 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700321 }
322
323 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100324 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800325 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100326 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800327 return bb;
328}
329
buzbeeb48819d2013-09-14 16:15:25 -0700330
buzbee311ca162013-02-28 15:56:43 -0800331/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700332void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800333 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700334 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800335
336 if (tries_size == 0) {
337 return;
338 }
339
340 for (int i = 0; i < tries_size; i++) {
341 const DexFile::TryItem* pTry =
342 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700343 DexOffset start_offset = pTry->start_addr_;
344 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800345 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700346 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800347 }
348 }
349
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700350 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700351 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800352 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
353 for (uint32_t idx = 0; idx < handlers_size; idx++) {
354 CatchHandlerIterator iterator(handlers_ptr);
355 for (; iterator.HasNext(); iterator.Next()) {
356 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700357 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800358 }
359 handlers_ptr = iterator.EndDataPointer();
360 }
361}
362
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100363bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
364 NarrowDexOffset catch_offset) {
365 // Catches for monitor-exit during stack unwinding have the pattern
366 // move-exception (move)* (goto)? monitor-exit throw
367 // In the currently generated dex bytecode we see these catching a bytecode range including
368 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
369 // it's the case for a given monitor-exit and catch block so that we can ignore it.
370 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
371 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
372 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700373 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100374 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
375 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700376 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100377 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
378 if (check_insn->VRegA_11x() == monitor_reg) {
379 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
380 return false;
381 }
382 check_insn = check_insn->Next();
383 while (true) {
384 int dest = -1;
385 bool wide = false;
386 switch (check_insn->Opcode()) {
387 case Instruction::MOVE_WIDE:
388 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700389 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100390 case Instruction::MOVE_OBJECT:
391 case Instruction::MOVE:
392 dest = check_insn->VRegA_12x();
393 break;
394
395 case Instruction::MOVE_WIDE_FROM16:
396 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700397 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100398 case Instruction::MOVE_OBJECT_FROM16:
399 case Instruction::MOVE_FROM16:
400 dest = check_insn->VRegA_22x();
401 break;
402
403 case Instruction::MOVE_WIDE_16:
404 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700405 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100406 case Instruction::MOVE_OBJECT_16:
407 case Instruction::MOVE_16:
408 dest = check_insn->VRegA_32x();
409 break;
410
411 case Instruction::GOTO:
412 case Instruction::GOTO_16:
413 case Instruction::GOTO_32:
414 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700415 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100416 default:
417 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
418 check_insn->VRegA_11x() == monitor_reg;
419 }
420
421 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
422 return false;
423 }
424
425 check_insn = check_insn->Next();
426 }
427}
428
buzbee311ca162013-02-28 15:56:43 -0800429/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700430BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
431 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700432 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700433 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800434 switch (insn->dalvikInsn.opcode) {
435 case Instruction::GOTO:
436 case Instruction::GOTO_16:
437 case Instruction::GOTO_32:
438 target += insn->dalvikInsn.vA;
439 break;
440 case Instruction::IF_EQ:
441 case Instruction::IF_NE:
442 case Instruction::IF_LT:
443 case Instruction::IF_GE:
444 case Instruction::IF_GT:
445 case Instruction::IF_LE:
446 cur_block->conditional_branch = true;
447 target += insn->dalvikInsn.vC;
448 break;
449 case Instruction::IF_EQZ:
450 case Instruction::IF_NEZ:
451 case Instruction::IF_LTZ:
452 case Instruction::IF_GEZ:
453 case Instruction::IF_GTZ:
454 case Instruction::IF_LEZ:
455 cur_block->conditional_branch = true;
456 target += insn->dalvikInsn.vB;
457 break;
458 default:
459 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
460 }
buzbeeb48819d2013-09-14 16:15:25 -0700461 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700462 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800463 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700464 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100465 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800466
467 /* Always terminate the current block for conditional branches */
468 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700469 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800470 /* create */
471 true,
472 /* immed_pred_block_p */
473 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700474 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100475 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800476 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700477 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800478 }
479 return cur_block;
480}
481
482/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800483BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
484 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700485 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800486 const uint16_t* switch_data =
487 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
488 int size;
489 const int* keyTable;
490 const int* target_table;
491 int i;
492 int first_key;
493
494 /*
495 * Packed switch data format:
496 * ushort ident = 0x0100 magic value
497 * ushort size number of entries in the table
498 * int first_key first (and lowest) switch case value
499 * int targets[size] branch targets, relative to switch opcode
500 *
501 * Total size is (4+size*2) 16-bit code units.
502 */
503 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
504 DCHECK_EQ(static_cast<int>(switch_data[0]),
505 static_cast<int>(Instruction::kPackedSwitchSignature));
506 size = switch_data[1];
507 first_key = switch_data[2] | (switch_data[3] << 16);
508 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700509 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800510 /*
511 * Sparse switch data format:
512 * ushort ident = 0x0200 magic value
513 * ushort size number of entries in the table; > 0
514 * int keys[size] keys, sorted low-to-high; 32-bit aligned
515 * int targets[size] branch targets, relative to switch opcode
516 *
517 * Total size is (2+size*4) 16-bit code units.
518 */
519 } else {
520 DCHECK_EQ(static_cast<int>(switch_data[0]),
521 static_cast<int>(Instruction::kSparseSwitchSignature));
522 size = switch_data[1];
523 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
524 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700525 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800526 }
527
buzbee0d829482013-10-11 15:24:55 -0700528 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800529 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700530 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800531 }
buzbee0d829482013-10-11 15:24:55 -0700532 cur_block->successor_block_list_type =
533 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100534 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800535
536 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700537 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
538 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700539 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700540 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000541 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700542 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800543 successor_block_info->key =
544 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
545 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100546 cur_block->successor_blocks.push_back(successor_block_info);
547 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800548 }
549
550 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700551 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
552 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700553 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100554 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800555 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800556}
557
558/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700559BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
560 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700561 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700562 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700563 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800564 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800565
566 /* In try block */
567 if (in_try_block) {
568 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
569
buzbee0d829482013-10-11 15:24:55 -0700570 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800571 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
572 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700573 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800574 }
575
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700576 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700577 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
578 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100579 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
580 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
581 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
582 continue;
583 }
584 if (cur_block->successor_block_list_type == kNotUsed) {
585 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100586 }
buzbee311ca162013-02-28 15:56:43 -0800587 catch_block->catch_entry = true;
588 if (kIsDebugBuild) {
589 catches_.insert(catch_block->start_offset);
590 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700591 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000592 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700593 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800594 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100595 cur_block->successor_blocks.push_back(successor_block_info);
596 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800597 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100598 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
599 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100600 bool build_all_edges =
601 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100602 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100603 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700604 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800605 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100606 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800607 }
608
buzbee17189ac2013-11-08 11:07:02 -0800609 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800610 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700611 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700612 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700613 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800614 }
615 if (!in_try_block) {
616 // Don't split a THROW that can't rethrow - we're done.
617 return cur_block;
618 }
619 }
620
buzbee17189ac2013-11-08 11:07:02 -0800621 if (!build_all_edges) {
622 /*
623 * Even though there is an exception edge here, control cannot return to this
624 * method. Thus, for the purposes of dataflow analysis and optimization, we can
625 * ignore the edge. Doing this reduces compile time, and increases the scope
626 * of the basic-block level optimization pass.
627 */
628 return cur_block;
629 }
630
buzbee311ca162013-02-28 15:56:43 -0800631 /*
632 * Split the potentially-throwing instruction into two parts.
633 * The first half will be a pseudo-op that captures the exception
634 * edges and terminates the basic block. It always falls through.
635 * Then, create a new basic block that begins with the throwing instruction
636 * (minus exceptions). Note: this new basic block must NOT be entered into
637 * the block_map. If the potentially-throwing instruction is the target of a
638 * future branch, we need to find the check psuedo half. The new
639 * basic block containing the work portion of the instruction should
640 * only be entered via fallthrough from the block containing the
641 * pseudo exception edge MIR. Note also that this new block is
642 * not automatically terminated after the work portion, and may
643 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700644 *
645 * Note also that the dex_pc_to_block_map_ entry for the potentially
646 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800647 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100648 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800649 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700650 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100651 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700652 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800653 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700654 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700655 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800656 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700657 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800658 return new_block;
659}
660
661/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
662void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700663 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700664 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800665 current_code_item_ = code_item;
666 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
667 current_method_ = m_units_.size();
668 current_offset_ = 0;
669 // TODO: will need to snapshot stack image and use that as the mir context identification.
670 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000671 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
672 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800673 const uint16_t* code_ptr = current_code_item_->insns_;
674 const uint16_t* code_end =
675 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
676
677 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700678 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100679 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
680 dex_pc_to_block_map_.resize(dex_pc_to_block_map_.size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700681
buzbee311ca162013-02-28 15:56:43 -0800682 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700683 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
684 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800685
686 // If this is the first method, set up default entry and exit blocks.
687 if (current_method_ == 0) {
688 DCHECK(entry_block_ == NULL);
689 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700690 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700691 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100692 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700693 DCHECK_EQ(null_block->id, NullBasicBlockId);
694 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100695 entry_block_ = CreateNewBB(kEntryBlock);
696 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800697 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
698 cu_->dex_file = &dex_file;
699 cu_->class_def_idx = class_def_idx;
700 cu_->method_idx = method_idx;
701 cu_->access_flags = access_flags;
702 cu_->invoke_type = invoke_type;
703 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800704 } else {
705 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
706 /*
707 * Will need to manage storage for ins & outs, push prevous state and update
708 * insert point.
709 */
710 }
711
712 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100713 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700714 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800715 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700716 // TODO: for inlining support, insert at the insert point rather than entry block.
717 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100718 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800719
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000720 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800721 ProcessTryCatchBlocks();
722
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000723 uint64_t merged_df_flags = 0u;
724
buzbee311ca162013-02-28 15:56:43 -0800725 /* Parse all instructions and put them into containing basic blocks */
726 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700727 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800728 insn->offset = current_offset_;
729 insn->m_unit_index = current_method_;
730 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800731 Instruction::Code opcode = insn->dalvikInsn.opcode;
732 if (opcode_count_ != NULL) {
733 opcode_count_[static_cast<int>(opcode)]++;
734 }
735
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700736 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800737 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800738
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700739 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000740 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800741
742 if (df_flags & DF_HAS_DEFS) {
743 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
744 }
745
buzbee1da1e2f2013-11-15 13:37:01 -0800746 if (df_flags & DF_LVN) {
747 cur_block->use_lvn = true; // Run local value numbering on this basic block.
748 }
749
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700750 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700751 if (opcode == Instruction::NOP) {
752 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
753 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
754 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
755 uint16_t following_raw_instruction = code_ptr[1];
756 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
757 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
758 (following_raw_instruction == Instruction::kArrayDataSignature)) {
759 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
760 }
761 }
762 if (width == 1) {
763 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700764 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700765 } else {
buzbee0d829482013-10-11 15:24:55 -0700766 DCHECK(cur_block->fall_through == NullBasicBlockId);
767 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800768 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700769 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800770 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700771 }
772 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700773 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700774 }
775
buzbeeb48819d2013-09-14 16:15:25 -0700776 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100777 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700778
buzbee27247762013-07-28 12:03:58 -0700779 code_ptr += width;
780
buzbee311ca162013-02-28 15:56:43 -0800781 if (flags & Instruction::kBranch) {
782 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
783 width, flags, code_ptr, code_end);
784 } else if (flags & Instruction::kReturn) {
785 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700786 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100787 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800788 /*
789 * Terminate the current block if there are instructions
790 * afterwards.
791 */
792 if (code_ptr < code_end) {
793 /*
794 * Create a fallthrough block for real instructions
795 * (incl. NOP).
796 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700797 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800798 }
799 } else if (flags & Instruction::kThrow) {
800 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
801 code_ptr, code_end);
802 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800803 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800804 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700805 if (verify_flags & Instruction::kVerifyVarArgRange ||
806 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800807 /*
808 * The Quick backend's runtime model includes a gap between a method's
809 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
810 * which spans the gap is somewhat complicated, and should not happen
811 * in normal usage of dx. Punt to the interpreter.
812 */
813 int first_reg_in_range = insn->dalvikInsn.vC;
814 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
815 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
816 punt_to_interpreter_ = true;
817 }
818 }
buzbee311ca162013-02-28 15:56:43 -0800819 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700820 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
821 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800822 if (next_block) {
823 /*
824 * The next instruction could be the target of a previously parsed
825 * forward branch so a block is already created. If the current
826 * instruction is not an unconditional branch, connect them through
827 * the fall-through link.
828 */
buzbee0d829482013-10-11 15:24:55 -0700829 DCHECK(cur_block->fall_through == NullBasicBlockId ||
830 GetBasicBlock(cur_block->fall_through) == next_block ||
831 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800832
buzbee0d829482013-10-11 15:24:55 -0700833 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
834 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100835 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800836 }
837 cur_block = next_block;
838 }
839 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000840 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000841
buzbee311ca162013-02-28 15:56:43 -0800842 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
843 DumpCFG("/sdcard/1_post_parse_cfg/", true);
844 }
845
846 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700847 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800848 }
849}
850
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700851void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800852 DCHECK(opcode_count_ != NULL);
853 LOG(INFO) << "Opcode Count";
854 for (int i = 0; i < kNumPackedOpcodes; i++) {
855 if (opcode_count_[i] != 0) {
856 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
857 << " " << opcode_count_[i];
858 }
859 }
860}
861
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700862uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
863 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
864 return oat_data_flow_attributes_[opcode];
865}
866
867uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
868 DCHECK(mir != nullptr);
869 Instruction::Code opcode = mir->dalvikInsn.opcode;
870 return GetDataFlowAttributes(opcode);
871}
872
buzbee311ca162013-02-28 15:56:43 -0800873// TODO: use a configurable base prefix, and adjust callers to supply pass name.
874/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800875void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800876 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700877 static AtomicInteger cnt(0);
878
879 // Increment counter to get a unique file number.
880 cnt++;
881
buzbee311ca162013-02-28 15:56:43 -0800882 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
883 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700884 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800885 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700886 suffix == nullptr ? "" : suffix,
887 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800888 file = fopen(fname.c_str(), "w");
889 if (file == NULL) {
890 return;
891 }
892 fprintf(file, "digraph G {\n");
893
894 fprintf(file, " rankdir=TB\n");
895
896 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
897 int idx;
898
899 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100900 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700901 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700902 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800903 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700904 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800905 if (bb->block_type == kEntryBlock) {
906 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
907 } else if (bb->block_type == kExitBlock) {
908 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
909 } else if (bb->block_type == kDalvikByteCode) {
910 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
911 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700912 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800913 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
914 bb->first_mir_insn ? " | " : " ");
915 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
916 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800917 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400918 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700919 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
920 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400921 extended_mir_op_names_[opcode - kMirOpFirst],
922 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
923 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700924 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700925 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700926 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100927 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
928 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800929 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400930 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800931 }
932 fprintf(file, " }\"];\n\n");
933 } else if (bb->block_type == kExceptionHandling) {
934 char block_name[BLOCK_NAME_LEN];
935
936 GetBlockName(bb, block_name);
937 fprintf(file, " %s [shape=invhouse];\n", block_name);
938 }
939
940 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
941
buzbee0d829482013-10-11 15:24:55 -0700942 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800943 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700944 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800945 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
946 block_name1, block_name2);
947 }
buzbee0d829482013-10-11 15:24:55 -0700948 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800949 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700950 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800951 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
952 }
953
buzbee0d829482013-10-11 15:24:55 -0700954 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800955 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
956 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700957 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800958
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100959 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800960 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100961 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700962 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800963 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100964 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800965 successor_block_info->key,
966 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100967 (succ_id != last_succ_id) ? " | " : " ");
968 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800969 }
970 fprintf(file, " }\"];\n\n");
971
972 GetBlockName(bb, block_name1);
973 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
974 block_name1, bb->start_offset, bb->id);
975
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700976 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700977 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100978 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700979 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800980
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700981 GetBlockName(dest_block, block_name2);
982 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
983 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800984 }
985 }
986 fprintf(file, "\n");
987
988 if (cu_->verbose) {
989 /* Display the dominator tree */
990 GetBlockName(bb, block_name1);
991 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
992 block_name1, block_name1);
993 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700994 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800995 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
996 }
997 }
998 }
999 fprintf(file, "}\n");
1000 fclose(file);
1001}
1002
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001003/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001004void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001005 // Insert it after the last MIR.
1006 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001007}
1008
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001009void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1010 // Insert it after the last MIR.
1011 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1012}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001013
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001014void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1015 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1016 MIR* new_mir = *it;
1017
1018 // Add a copy of each MIR.
1019 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1020 }
buzbee1fd33462013-03-25 13:40:45 -07001021}
1022
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001023/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001024void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001025 InsertMIRListAfter(current_mir, new_mir, new_mir);
1026}
buzbee1fd33462013-03-25 13:40:45 -07001027
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001028void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1029 // If no MIR, we are done.
1030 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1031 return;
buzbee1fd33462013-03-25 13:40:45 -07001032 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001033
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001034 // If insert_after is null, assume BB is empty.
1035 if (insert_after == nullptr) {
1036 first_mir_insn = first_list_mir;
1037 last_mir_insn = last_list_mir;
1038 last_list_mir->next = nullptr;
1039 } else {
1040 MIR* after_list = insert_after->next;
1041 insert_after->next = first_list_mir;
1042 last_list_mir->next = after_list;
1043 if (after_list == nullptr) {
1044 last_mir_insn = last_list_mir;
1045 }
1046 }
1047
1048 // Set this BB to be the basic block of the MIRs.
1049 MIR* last = last_list_mir->next;
1050 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1051 mir->bb = id;
1052 }
1053}
1054
1055/* Insert an MIR instruction to the head of a basic block. */
1056void BasicBlock::PrependMIR(MIR* mir) {
1057 InsertMIRListBefore(first_mir_insn, mir, mir);
1058}
1059
1060void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1061 // Insert it before the first MIR.
1062 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1063}
1064
1065void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1066 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1067 MIR* mir = *it;
1068
1069 InsertMIRListBefore(first_mir_insn, mir, mir);
1070 }
1071}
1072
1073/* Insert a MIR instruction before the specified MIR. */
1074void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1075 // Insert as a single element list.
1076 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001077}
1078
1079MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1080 MIR* current = first_mir_insn;
1081
1082 while (current != nullptr) {
1083 MIR* next = current->next;
1084
1085 if (next == mir) {
1086 return current;
1087 }
1088
1089 current = next;
1090 }
1091
1092 return nullptr;
1093}
1094
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001095void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1096 // If no MIR, we are done.
1097 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1098 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001099 }
1100
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001101 // If insert_before is null, assume BB is empty.
1102 if (insert_before == nullptr) {
1103 first_mir_insn = first_list_mir;
1104 last_mir_insn = last_list_mir;
1105 last_list_mir->next = nullptr;
1106 } else {
1107 if (first_mir_insn == insert_before) {
1108 last_list_mir->next = first_mir_insn;
1109 first_mir_insn = first_list_mir;
1110 } else {
1111 // Find the preceding MIR.
1112 MIR* before_list = FindPreviousMIR(insert_before);
1113 DCHECK(before_list != nullptr);
1114 before_list->next = first_list_mir;
1115 last_list_mir->next = insert_before;
1116 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001117 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001118
1119 // Set this BB to be the basic block of the MIRs.
1120 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1121 mir->bb = id;
1122 }
1123}
1124
1125bool BasicBlock::RemoveMIR(MIR* mir) {
1126 // Remove as a single element list.
1127 return RemoveMIRList(mir, mir);
1128}
1129
1130bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1131 if (first_list_mir == nullptr) {
1132 return false;
1133 }
1134
1135 // Try to find the MIR.
1136 MIR* before_list = nullptr;
1137 MIR* after_list = nullptr;
1138
1139 // If we are removing from the beginning of the MIR list.
1140 if (first_mir_insn == first_list_mir) {
1141 before_list = nullptr;
1142 } else {
1143 before_list = FindPreviousMIR(first_list_mir);
1144 if (before_list == nullptr) {
1145 // We did not find the mir.
1146 return false;
1147 }
1148 }
1149
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001150 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001151 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001152 mir->bb = NullBasicBlockId;
1153 }
1154
1155 after_list = last_list_mir->next;
1156
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001157 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001158 if (before_list == nullptr) {
1159 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001160 } else {
1161 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001162 }
1163
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001164 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001165 if (after_list == nullptr) {
1166 last_mir_insn = before_list;
1167 }
1168
1169 return true;
buzbee1fd33462013-03-25 13:40:45 -07001170}
1171
Vladimir Marko26e7d452014-11-24 14:09:46 +00001172MIR* BasicBlock::GetFirstNonPhiInsn() {
1173 MIR* mir = first_mir_insn;
1174 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1175 mir = mir->next;
1176 }
1177 return mir;
1178}
1179
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001180MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001181 MIR* next_mir = nullptr;
1182
1183 if (current != nullptr) {
1184 next_mir = current->next;
1185 }
1186
1187 if (next_mir == nullptr) {
1188 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001189 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1190 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001191 }
1192 }
1193
1194 return next_mir;
1195}
1196
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001197static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1198 DCHECK(decoded_mir != nullptr);
1199 OpSize type = static_cast<OpSize>(type_size >> 16);
1200 uint16_t vect_size = (type_size & 0xFFFF);
1201
1202 // Now print the type and vector size.
1203 std::stringstream ss;
1204 ss << " (type:";
1205 ss << type;
1206 ss << " vectsize:";
1207 ss << vect_size;
1208 ss << ")";
1209
1210 decoded_mir->append(ss.str());
1211}
1212
1213void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1214 DCHECK(decoded_mir != nullptr);
1215 int opcode = mir->dalvikInsn.opcode;
1216 SSARepresentation* ssa_rep = mir->ssa_rep;
1217 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1218 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1219
Vladimirf41b92c2014-10-13 13:41:38 +07001220 if (opcode < kMirOpFirst) {
1221 return; // It is not an extended instruction.
1222 }
1223
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001224 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1225
1226 switch (opcode) {
1227 case kMirOpPhi: {
1228 if (defs > 0 && uses > 0) {
1229 BasicBlockId* incoming = mir->meta.phi_incoming;
1230 decoded_mir->append(StringPrintf(" %s = (%s",
1231 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1232 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1233 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1234 for (int i = 1; i < uses; i++) {
1235 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1236 }
1237 decoded_mir->append(")");
1238 }
1239 break;
1240 }
1241 case kMirOpCopy:
1242 if (ssa_rep != nullptr) {
1243 decoded_mir->append(" ");
1244 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1245 if (defs > 1) {
1246 decoded_mir->append(", ");
1247 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1248 }
1249 decoded_mir->append(" = ");
1250 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1251 if (uses > 1) {
1252 decoded_mir->append(", ");
1253 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1254 }
1255 } else {
1256 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1257 }
1258 break;
1259 case kMirOpFusedCmplFloat:
1260 case kMirOpFusedCmpgFloat:
1261 case kMirOpFusedCmplDouble:
1262 case kMirOpFusedCmpgDouble:
1263 case kMirOpFusedCmpLong:
1264 if (ssa_rep != nullptr) {
1265 decoded_mir->append(" ");
1266 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1267 for (int i = 1; i < uses; i++) {
1268 decoded_mir->append(", ");
1269 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1270 }
1271 } else {
1272 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1273 }
1274 break;
1275 case kMirOpMoveVector:
1276 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1277 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1278 break;
1279 case kMirOpPackedAddition:
1280 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1281 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1282 break;
1283 case kMirOpPackedMultiply:
1284 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1285 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1286 break;
1287 case kMirOpPackedSubtract:
1288 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1289 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1290 break;
1291 case kMirOpPackedAnd:
1292 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1293 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1294 break;
1295 case kMirOpPackedOr:
1296 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1297 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1298 break;
1299 case kMirOpPackedXor:
1300 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1301 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1302 break;
1303 case kMirOpPackedShiftLeft:
1304 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1305 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1306 break;
1307 case kMirOpPackedUnsignedShiftRight:
1308 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1309 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1310 break;
1311 case kMirOpPackedSignedShiftRight:
1312 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1313 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1314 break;
1315 case kMirOpConstVector:
1316 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1317 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1318 break;
1319 case kMirOpPackedSet:
1320 if (ssa_rep != nullptr) {
1321 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1322 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1323 if (uses > 1) {
1324 decoded_mir->append(", ");
1325 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1326 }
1327 } else {
1328 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1329 }
1330 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1331 break;
1332 case kMirOpPackedAddReduce:
1333 if (ssa_rep != nullptr) {
1334 decoded_mir->append(" ");
1335 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1336 if (defs > 1) {
1337 decoded_mir->append(", ");
1338 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1339 }
1340 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1341 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1342 if (uses > 1) {
1343 decoded_mir->append(", ");
1344 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1345 }
1346 } else {
1347 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1348 }
1349 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1350 break;
1351 case kMirOpPackedReduce:
1352 if (ssa_rep != nullptr) {
1353 decoded_mir->append(" ");
1354 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1355 if (defs > 1) {
1356 decoded_mir->append(", ");
1357 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1358 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001359 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001360 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001361 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1362 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001363 }
1364 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1365 break;
1366 case kMirOpReserveVectorRegisters:
1367 case kMirOpReturnVectorRegisters:
1368 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1369 break;
1370 case kMirOpMemBarrier: {
1371 decoded_mir->append(" type:");
1372 std::stringstream ss;
1373 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1374 decoded_mir->append(ss.str());
1375 break;
1376 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001377 case kMirOpPackedArrayGet:
1378 case kMirOpPackedArrayPut:
1379 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1380 if (ssa_rep != nullptr) {
1381 decoded_mir->append(StringPrintf(", %s[%s]",
1382 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1383 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1384 } else {
1385 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1386 }
1387 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1388 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001389 default:
1390 break;
1391 }
1392}
1393
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001394char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001395 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001396 std::string str;
1397 int flags = 0;
1398 int opcode = insn.opcode;
1399 char* ret;
1400 bool nop = false;
1401 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001402 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001403
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001404 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001405 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1406 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1407 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001408 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001409 insn = mir->meta.throw_insn->dalvikInsn;
1410 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001411 opcode = insn.opcode;
1412 } else if (opcode == kMirOpNop) {
1413 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001414 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1415 // Recover original opcode.
1416 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1417 opcode = insn.opcode;
1418 }
buzbee1fd33462013-03-25 13:40:45 -07001419 nop = true;
1420 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001421 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1422 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001423
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001424 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001425 // Note that this does not check the MIR's opcode in all cases. In cases where it
1426 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1427 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001428 } else {
1429 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001430 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001431 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001432
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001433 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001434 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1435 (dalvik_format == Instruction::k3rc));
1436 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001437 str.append(" ");
1438 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1439 if (defs > 1) {
1440 str.append(", ");
1441 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1442 }
buzbee1fd33462013-03-25 13:40:45 -07001443 if (uses != 0) {
1444 str.append(", ");
1445 }
1446 }
1447 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001448 str.append(" ");
1449 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001450 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1451 // For the listing, skip the high sreg.
1452 i++;
1453 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001454 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001455 str.append(",");
1456 }
1457 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001458
buzbee1fd33462013-03-25 13:40:45 -07001459 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001460 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001461 case Instruction::k21s:
1462 case Instruction::k31i:
1463 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001464 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001465 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001466 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001467 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001468 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001469 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001470 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001471 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001472 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001473 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001474 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001475 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001476 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001477 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001478 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001479 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001480 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001481 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001482 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001483 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001484
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001485 if ((flags & Instruction::kBranch) != 0) {
1486 // For branches, decode the instructions to print out the branch targets.
1487 int offset = 0;
1488 switch (dalvik_format) {
1489 case Instruction::k21t:
1490 offset = insn.vB;
1491 break;
1492 case Instruction::k22t:
1493 offset = insn.vC;
1494 break;
1495 case Instruction::k10t:
1496 case Instruction::k20t:
1497 case Instruction::k30t:
1498 offset = insn.vA;
1499 break;
1500 default:
1501 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001502 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001503 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001504 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001505 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1506 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001507
1508 if (nop) {
1509 str.append("]--optimized away");
1510 }
buzbee1fd33462013-03-25 13:40:45 -07001511 }
1512 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001513 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001514 strncpy(ret, str.c_str(), length);
1515 return ret;
1516}
1517
1518/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001519void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001520 static const struct { const char before; const char after; } match[] = {
1521 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1522 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1523 };
buzbee1fd33462013-03-25 13:40:45 -07001524 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1525 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1526 }
1527}
1528
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001529std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001530 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1531 // the arena. We should be smarter and just place straight into the arena, or compute the
1532 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001533 int vreg = SRegToVReg(ssa_reg);
1534 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1535 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1536 } else {
1537 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1538 }
buzbee1fd33462013-03-25 13:40:45 -07001539}
1540
1541// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001542std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001543 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001544 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001545 return GetSSAName(ssa_reg);
1546 }
1547 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001548 if (!singles_only && reg_location_[ssa_reg].wide &&
1549 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001550 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001551 ConstantValueWide(reg_location_[ssa_reg]));
1552 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001553 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001554 ConstantValue(reg_location_[ssa_reg]));
1555 }
1556 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001557 int vreg = SRegToVReg(ssa_reg);
1558 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1559 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1560 } else {
1561 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1562 }
buzbee1fd33462013-03-25 13:40:45 -07001563 }
1564}
1565
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001566void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001567 switch (bb->block_type) {
1568 case kEntryBlock:
1569 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1570 break;
1571 case kExitBlock:
1572 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1573 break;
1574 case kDalvikByteCode:
1575 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1576 break;
1577 case kExceptionHandling:
1578 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1579 bb->id);
1580 break;
1581 default:
1582 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1583 break;
1584 }
1585}
1586
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001587const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001588 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001589 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1590 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1591}
1592
1593/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001594void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001595 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001596 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001597 "Entry Block",
1598 "Code Block",
1599 "Exit Block",
1600 "Exception Handling",
1601 "Catch Block"
1602 };
1603
1604 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001605 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001606 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001607
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001608 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001609 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1610 bb->id,
1611 block_type_names[bb->block_type],
1612 bb->start_offset,
1613 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1614 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001615 if (bb->taken != NullBasicBlockId) {
1616 LOG(INFO) << " Taken branch: block " << bb->taken
1617 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001618 }
buzbee0d829482013-10-11 15:24:55 -07001619 if (bb->fall_through != NullBasicBlockId) {
1620 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1621 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001622 }
1623 }
1624}
1625
1626/*
1627 * Build an array of location records for the incoming arguments.
1628 * Note: one location record per word of arguments, with dummy
1629 * high-word loc for wide arguments. Also pull up any following
1630 * MOVE_RESULT and incorporate it into the invoke.
1631 */
1632CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001633 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001634 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001635 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001636 MIR* move_result_mir = FindMoveResult(bb, mir);
1637 if (move_result_mir == NULL) {
1638 info->result.location = kLocInvalid;
1639 } else {
1640 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001641 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1642 }
1643 info->num_arg_words = mir->ssa_rep->num_uses;
1644 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001645 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001646 for (int i = 0; i < info->num_arg_words; i++) {
1647 info->args[i] = GetRawSrc(mir, i);
1648 }
1649 info->opt_flags = mir->optimization_flags;
1650 info->type = type;
1651 info->is_range = is_range;
1652 info->index = mir->dalvikInsn.vB;
1653 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001654 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001655 return info;
1656}
1657
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001658// Allocate a new MIR.
1659MIR* MIRGraph::NewMIR() {
1660 MIR* mir = new (arena_) MIR();
1661 return mir;
1662}
1663
buzbee862a7602013-04-05 10:58:54 -07001664// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001665BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001666 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001667
buzbee862a7602013-04-05 10:58:54 -07001668 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001669 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001670 block_id_map_.Put(block_id, block_id);
1671 return bb;
1672}
buzbee1fd33462013-03-25 13:40:45 -07001673
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001674void MIRGraph::InitializeConstantPropagation() {
1675 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001676 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001677}
1678
1679void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001680 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001681 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001682 use_counts_.clear();
1683 use_counts_.reserve(num_ssa_regs + 32);
1684 use_counts_.resize(num_ssa_regs, 0u);
1685 raw_use_counts_.clear();
1686 raw_use_counts_.reserve(num_ssa_regs + 32);
1687 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001688}
1689
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001690void MIRGraph::SSATransformationStart() {
1691 DCHECK(temp_scoped_alloc_.get() == nullptr);
1692 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001693 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1694 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1695 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001696}
1697
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001698void MIRGraph::SSATransformationEnd() {
1699 // Verify the dataflow information after the pass.
1700 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1701 VerifyDataflow();
1702 }
1703
Vladimir Markof585e542014-11-21 13:41:32 +00001704 temp_.ssa.num_vregs = 0u;
1705 temp_.ssa.work_live_vregs = nullptr;
1706 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001707 DCHECK(temp_scoped_alloc_.get() != nullptr);
1708 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001709
1710 // Update the maximum number of reachable blocks.
1711 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001712}
1713
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001714size_t MIRGraph::GetNumDalvikInsns() const {
1715 size_t cumulative_size = 0u;
1716 bool counted_current_item = false;
1717 const uint8_t size_for_null_code_item = 2u;
1718
1719 for (auto it : m_units_) {
1720 const DexFile::CodeItem* code_item = it->GetCodeItem();
1721 // Even if the code item is null, we still count non-zero value so that
1722 // each m_unit is counted as having impact.
1723 cumulative_size += (code_item == nullptr ?
1724 size_for_null_code_item : code_item->insns_size_in_code_units_);
1725 if (code_item == current_code_item_) {
1726 counted_current_item = true;
1727 }
1728 }
1729
1730 // If the current code item was not counted yet, count it now.
1731 // This can happen for example in unit tests where some fields like m_units_
1732 // are not initialized.
1733 if (counted_current_item == false) {
1734 cumulative_size += (current_code_item_ == nullptr ?
1735 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1736 }
1737
1738 return cumulative_size;
1739}
1740
Vladimir Marko55fff042014-07-10 12:42:52 +01001741static BasicBlock* SelectTopologicalSortOrderFallBack(
1742 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1743 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1744 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1745 // No true loop head has been found but there may be true loop heads after the mess we need
1746 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1747 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1748 BasicBlock* fall_back = nullptr;
1749 size_t fall_back_num_reachable = 0u;
1750 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1751 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1752 AllNodesIterator iter(mir_graph);
1753 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1754 if (candidate->hidden || // Hidden, or
1755 candidate->visited || // already processed, or
1756 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1757 (current_loop != nullptr && // outside current loop.
1758 !current_loop->IsBitSet(candidate->id))) {
1759 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001760 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001761 DCHECK(tmp_stack->empty());
1762 tmp_stack->push_back(candidate->id);
1763 candidate_reachable.ClearAllBits();
1764 size_t num_reachable = 0u;
1765 while (!tmp_stack->empty()) {
1766 BasicBlockId current_id = tmp_stack->back();
1767 tmp_stack->pop_back();
1768 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1769 DCHECK(current_bb != nullptr);
1770 ChildBlockIterator child_iter(current_bb, mir_graph);
1771 BasicBlock* child_bb = child_iter.Next();
1772 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1773 DCHECK(!child_bb->hidden);
1774 if (child_bb->visited || // Already processed, or
1775 (current_loop != nullptr && // outside current loop.
1776 !current_loop->IsBitSet(child_bb->id))) {
1777 continue;
1778 }
1779 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1780 candidate_reachable.SetBit(child_bb->id);
1781 tmp_stack->push_back(child_bb->id);
1782 num_reachable += 1u;
1783 }
1784 }
1785 }
1786 if (fall_back_num_reachable < num_reachable) {
1787 fall_back_num_reachable = num_reachable;
1788 fall_back = candidate;
1789 }
1790 }
1791 return fall_back;
1792}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001793
Vladimir Marko55fff042014-07-10 12:42:52 +01001794// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1795static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1796 ArenaBitVector* reachable,
1797 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1798 // NOTE: Loop heads indicated by the "visited" flag.
1799 DCHECK(tmp_stack->empty());
1800 reachable->ClearAllBits();
1801 tmp_stack->push_back(bb_id);
1802 while (!tmp_stack->empty()) {
1803 BasicBlockId current_id = tmp_stack->back();
1804 tmp_stack->pop_back();
1805 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1806 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001807 for (BasicBlockId pred_id : current_bb->predecessors) {
1808 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1809 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001810 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1811 reachable->SetBit(pred_bb->id);
1812 tmp_stack->push_back(pred_bb->id);
1813 }
1814 }
1815 }
1816}
1817
1818void MIRGraph::ComputeTopologicalSortOrder() {
1819 ScopedArenaAllocator allocator(&cu_->arena_stack);
1820 unsigned int num_blocks = GetNumBlocks();
1821
1822 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1823 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1824 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1825 size_t max_nested_loops = 0u;
1826 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1827 loop_exit_blocks.ClearAllBits();
1828
1829 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001830 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001831 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001832 if (bb->hidden == true) {
1833 continue;
1834 }
1835
Vladimir Marko55fff042014-07-10 12:42:52 +01001836 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001837
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001838 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001839 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001840 q.push(bb);
1841 }
1842 }
1843
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001844 // Clear the topological order arrays.
1845 topological_order_.clear();
1846 topological_order_.reserve(num_blocks);
1847 topological_order_loop_ends_.clear();
1848 topological_order_loop_ends_.resize(num_blocks, 0u);
1849 topological_order_indexes_.clear();
1850 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001851
1852 // Mark all blocks as unvisited.
1853 ClearAllVisitedFlags();
1854
1855 // For loop heads, keep track from which blocks they are reachable not going through other
1856 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1857 // in this set go into the loop body, the other children are jumping over the loop.
1858 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1859 loop_head_reachable_from.resize(num_blocks, nullptr);
1860 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1861 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1862
1863 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001864 BasicBlock* bb = nullptr;
1865 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001866 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001867 // Get top.
1868 bb = q.front();
1869 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001870 if (bb->visited) {
1871 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1872 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001873 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1874 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001875 DCHECK_EQ(loop_head_stack.back(), bb->id);
1876 loop_head_stack.pop_back();
1877 ArenaBitVector* reachable =
1878 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1879 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1880 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1881 q.push(GetBasicBlock(candidate_id));
1882 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1883 // so clearing the bit has no effect on the iterator.
1884 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001885 }
1886 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001887 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001888 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001889 } else {
1890 // Find the new loop head.
1891 AllNodesIterator iter(this);
1892 while (true) {
1893 BasicBlock* candidate = iter.Next();
1894 if (candidate == nullptr) {
1895 // We did not find a true loop head, fall back to a reachable block in any loop.
1896 ArenaBitVector* current_loop =
1897 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1898 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1899 &allocator, &tmp_stack);
1900 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1901 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1902 LOG(INFO) << "Topological sort order: Using fall-back in "
1903 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1904 << " @0x" << std::hex << bb->start_offset
1905 << ", num_blocks = " << std::dec << num_blocks;
1906 }
1907 break;
1908 }
1909 if (candidate->hidden || // Hidden, or
1910 candidate->visited || // already processed, or
1911 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1912 (!loop_head_stack.empty() && // outside current loop.
1913 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1914 continue;
1915 }
1916
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001917 for (BasicBlockId pred_id : candidate->predecessors) {
1918 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1919 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001920 if (pred_bb != candidate && !pred_bb->visited &&
1921 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001922 candidate = nullptr; // Set candidate to null to indicate failure.
1923 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001924 }
1925 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001926 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001927 bb = candidate;
1928 break;
1929 }
1930 }
1931 // Compute blocks from which the loop head is reachable and process those blocks first.
1932 ArenaBitVector* reachable =
1933 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1934 loop_head_reachable_from[bb->id] = reachable;
1935 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1936 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1937 loop_head_stack.push_back(bb->id);
1938 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001939 }
1940
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001941 DCHECK_EQ(bb->hidden, false);
1942 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001943 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001944
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001945 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001946 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1947 topological_order_indexes_[bb->id] = idx;
1948 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001949
Vladimir Marko55fff042014-07-10 12:42:52 +01001950 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001951 ChildBlockIterator succIter(bb, this);
1952 BasicBlock* successor = succIter.Next();
1953 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001955 continue;
1956 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001957
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 // One more predecessor was visited.
1959 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001960 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001961 if (loop_head_stack.empty() ||
1962 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1963 q.push(successor);
1964 } else {
1965 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1966 loop_exit_blocks.SetBit(successor->id);
1967 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001968 }
1969 }
1970 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001971
1972 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001973 topological_order_loop_head_stack_.clear();
1974 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01001975 max_nested_loops_ = max_nested_loops;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001976}
1977
1978bool BasicBlock::IsExceptionBlock() const {
1979 if (block_type == kExceptionHandling) {
1980 return true;
1981 }
1982 return false;
1983}
1984
Wei Jin04f4d8a2014-05-29 18:04:29 -07001985bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1986 BasicBlock* target = GetBasicBlock(target_id);
1987
1988 if (source == nullptr || target == nullptr)
1989 return false;
1990
1991 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001992 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1993 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001994 if (bb == source)
1995 return true; // The block has been inserted by a suspend check before.
1996 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1997 return true;
1998 }
1999
2000 return false;
2001}
2002
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002003ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2004 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2005 visited_taken_(false), have_successors_(false) {
2006 // Check if we actually do have successors.
2007 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2008 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002009 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002010 }
2011}
2012
2013BasicBlock* ChildBlockIterator::Next() {
2014 // We check if we have a basic block. If we don't we cannot get next child.
2015 if (basic_block_ == nullptr) {
2016 return nullptr;
2017 }
2018
2019 // If we haven't visited fallthrough, return that.
2020 if (visited_fallthrough_ == false) {
2021 visited_fallthrough_ = true;
2022
2023 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2024 if (result != nullptr) {
2025 return result;
2026 }
2027 }
2028
2029 // If we haven't visited taken, return that.
2030 if (visited_taken_ == false) {
2031 visited_taken_ = true;
2032
2033 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2034 if (result != nullptr) {
2035 return result;
2036 }
2037 }
2038
2039 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2040 if (have_successors_ == true) {
2041 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002042 auto end = basic_block_->successor_blocks.cend();
2043 while (successor_iter_ != end) {
2044 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2045 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002046 // If block was replaced by zero block, take next one.
2047 if (successor_block_info->block != NullBasicBlockId) {
2048 return mir_graph_->GetBasicBlock(successor_block_info->block);
2049 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002050 }
2051 }
2052
2053 // We do not have anything.
2054 return nullptr;
2055}
2056
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002057BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2058 MIRGraph* mir_graph = c_unit->mir_graph.get();
2059 return Copy(mir_graph);
2060}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002061
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002062BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2063 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002064
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002065 // We don't do a memcpy style copy here because it would lead to a lot of things
2066 // to clean up. Let us do it by hand instead.
2067 // Copy in taken and fallthrough.
2068 result_bb->fall_through = fall_through;
2069 result_bb->taken = taken;
2070
2071 // Copy successor links if needed.
2072 ArenaAllocator* arena = mir_graph->GetArena();
2073
2074 result_bb->successor_block_list_type = successor_block_list_type;
2075 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002076 result_bb->successor_blocks.reserve(successor_blocks.size());
2077 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2078 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2079 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002080 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002081 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002082 }
2083 }
2084
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002085 // Copy offset, method.
2086 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002087
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002088 // Now copy instructions.
2089 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2090 // Get a copy first.
2091 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002092
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002093 // Append it.
2094 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002095 }
2096
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002097 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002098}
2099
2100MIR* MIR::Copy(MIRGraph* mir_graph) {
2101 MIR* res = mir_graph->NewMIR();
2102 *res = *this;
2103
2104 // Remove links
2105 res->next = nullptr;
2106 res->bb = NullBasicBlockId;
2107 res->ssa_rep = nullptr;
2108
2109 return res;
2110}
2111
2112MIR* MIR::Copy(CompilationUnit* c_unit) {
2113 return Copy(c_unit->mir_graph.get());
2114}
2115
2116uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2117 // Default result.
2118 int res = 0;
2119
2120 // We are basically setting the iputs to their igets counterparts.
2121 switch (opcode) {
2122 case Instruction::IPUT:
2123 case Instruction::IPUT_OBJECT:
2124 case Instruction::IPUT_BOOLEAN:
2125 case Instruction::IPUT_BYTE:
2126 case Instruction::IPUT_CHAR:
2127 case Instruction::IPUT_SHORT:
2128 case Instruction::IPUT_QUICK:
2129 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002130 case Instruction::IPUT_BOOLEAN_QUICK:
2131 case Instruction::IPUT_BYTE_QUICK:
2132 case Instruction::IPUT_CHAR_QUICK:
2133 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002134 case Instruction::APUT:
2135 case Instruction::APUT_OBJECT:
2136 case Instruction::APUT_BOOLEAN:
2137 case Instruction::APUT_BYTE:
2138 case Instruction::APUT_CHAR:
2139 case Instruction::APUT_SHORT:
2140 case Instruction::SPUT:
2141 case Instruction::SPUT_OBJECT:
2142 case Instruction::SPUT_BOOLEAN:
2143 case Instruction::SPUT_BYTE:
2144 case Instruction::SPUT_CHAR:
2145 case Instruction::SPUT_SHORT:
2146 // Skip the VR containing what to store.
2147 res = 1;
2148 break;
2149 case Instruction::IPUT_WIDE:
2150 case Instruction::IPUT_WIDE_QUICK:
2151 case Instruction::APUT_WIDE:
2152 case Instruction::SPUT_WIDE:
2153 // Skip the two VRs containing what to store.
2154 res = 2;
2155 break;
2156 default:
2157 // Do nothing in the general case.
2158 break;
2159 }
2160
2161 return res;
2162}
2163
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002164/**
2165 * @brief Given a decoded instruction, it checks whether the instruction
2166 * sets a constant and if it does, more information is provided about the
2167 * constant being set.
2168 * @param ptr_value pointer to a 64-bit holder for the constant.
2169 * @param wide Updated by function whether a wide constant is being set by bytecode.
2170 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2171 */
2172bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2173 bool sets_const = true;
2174 int64_t value = vB;
2175
2176 DCHECK(ptr_value != nullptr);
2177 DCHECK(wide != nullptr);
2178
2179 switch (opcode) {
2180 case Instruction::CONST_4:
2181 case Instruction::CONST_16:
2182 case Instruction::CONST:
2183 *wide = false;
2184 value <<= 32; // In order to get the sign extend.
2185 value >>= 32;
2186 break;
2187 case Instruction::CONST_HIGH16:
2188 *wide = false;
2189 value <<= 48; // In order to get the sign extend.
2190 value >>= 32;
2191 break;
2192 case Instruction::CONST_WIDE_16:
2193 case Instruction::CONST_WIDE_32:
2194 *wide = true;
2195 value <<= 32; // In order to get the sign extend.
2196 value >>= 32;
2197 break;
2198 case Instruction::CONST_WIDE:
2199 *wide = true;
2200 value = vB_wide;
2201 break;
2202 case Instruction::CONST_WIDE_HIGH16:
2203 *wide = true;
2204 value <<= 48; // In order to get the sign extend.
2205 break;
2206 default:
2207 sets_const = false;
2208 break;
2209 }
2210
2211 if (sets_const) {
2212 *ptr_value = value;
2213 }
2214
2215 return sets_const;
2216}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002217
2218void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2219 // Reset flags for all MIRs in bb.
2220 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2221 mir->optimization_flags &= (~reset_flags);
2222 }
2223}
2224
Vladimir Marko312eb252014-10-07 15:01:57 +01002225void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002226 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2227 block_type = kDalvikByteCode;
2228
2229 // Mark it as hidden.
2230 hidden = true;
2231
2232 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2233 // are updated to know that they no longer have a parent.
2234 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2235 mir->bb = NullBasicBlockId;
2236 }
2237 first_mir_insn = nullptr;
2238 last_mir_insn = nullptr;
2239
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002240 for (BasicBlockId pred_id : predecessors) {
2241 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2242 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002243
2244 // Sadly we have to go through the children by hand here.
2245 pred_bb->ReplaceChild(id, NullBasicBlockId);
2246 }
2247
2248 // Iterate through children of bb we are hiding.
2249 ChildBlockIterator successorChildIter(this, mir_graph);
2250
2251 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002252 // Erase this predecessor from child.
2253 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002254 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002255
2256 // Remove link to children.
2257 taken = NullBasicBlockId;
2258 fall_through = NullBasicBlockId;
2259 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002260}
2261
Vladimir Marko312eb252014-10-07 15:01:57 +01002262/*
2263 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2264 */
2265void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2266 DCHECK(predecessors.empty()); // Unreachable.
2267
2268 // Mark as dead and hidden.
2269 block_type = kDead;
2270 hidden = true;
2271
2272 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2273 // are updated to know that they no longer have a parent.
2274 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2275 mir->bb = NullBasicBlockId;
2276 }
2277 first_mir_insn = nullptr;
2278 last_mir_insn = nullptr;
2279
2280 data_flow_info = nullptr;
2281
2282 // Erase this bb from all children's predecessors and kill unreachable children.
2283 ChildBlockIterator iter(this, mir_graph);
2284 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2285 succ_bb->ErasePredecessor(id);
2286 if (succ_bb->predecessors.empty()) {
2287 succ_bb->KillUnreachable(mir_graph);
2288 }
2289 }
2290
2291 // Remove links to children.
2292 fall_through = NullBasicBlockId;
2293 taken = NullBasicBlockId;
2294 successor_block_list_type = kNotUsed;
2295
2296 if (kIsDebugBuild) {
2297 if (catch_entry) {
2298 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2299 mir_graph->catches_.erase(start_offset);
2300 }
2301 }
2302}
2303
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002304bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2305 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2306 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2307 // then it is not live out of this BB.
2308 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2309
2310 int last_ssa_reg = -1;
2311
2312 // Walk through the MIRs backwards.
2313 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2314 // Get ssa rep.
2315 SSARepresentation *ssa_rep = mir->ssa_rep;
2316
2317 // Go through the defines for this MIR.
2318 for (int i = 0; i < ssa_rep->num_defs; i++) {
2319 DCHECK(ssa_rep->defs != nullptr);
2320
2321 // Get the ssa reg.
2322 int def_ssa_reg = ssa_rep->defs[i];
2323
2324 // Get dalvik reg.
2325 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2326
2327 // Compare dalvik regs.
2328 if (dalvik_reg == def_dalvik_reg) {
2329 // We found a def of the register that we are being asked about.
2330 // Remember it.
2331 last_ssa_reg = def_ssa_reg;
2332 }
2333 }
2334 }
2335
2336 if (last_ssa_reg == -1) {
2337 // If we get to this point we couldn't find a define of register user asked about.
2338 // Let's assume the user knows what he's doing so we can be safe and say that if we
2339 // couldn't find a def, it is live out.
2340 return true;
2341 }
2342
2343 // If it is not -1, we found a match, is it ssa_reg?
2344 return (ssa_reg == last_ssa_reg);
2345}
2346
2347bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2348 // We need to check taken, fall_through, and successor_blocks to replace.
2349 bool found = false;
2350 if (taken == old_bb) {
2351 taken = new_bb;
2352 found = true;
2353 }
2354
2355 if (fall_through == old_bb) {
2356 fall_through = new_bb;
2357 found = true;
2358 }
2359
2360 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002361 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002362 if (successor_block_info->block == old_bb) {
2363 successor_block_info->block = new_bb;
2364 found = true;
2365 }
2366 }
2367 }
2368
2369 return found;
2370}
2371
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002372void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2373 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2374 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002375 // It's faster to move the back() to *pos than erase(pos).
2376 *pos = predecessors.back();
2377 predecessors.pop_back();
2378 size_t idx = std::distance(predecessors.begin(), pos);
2379 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2380 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2381 break;
2382 }
2383 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2384 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2385 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2386 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2387 mir->ssa_rep->num_uses = predecessors.size();
2388 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002389}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002390
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002391void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2392 DCHECK_NE(new_pred, NullBasicBlockId);
2393 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002394 DCHECK(pos != predecessors.end());
2395 *pos = new_pred;
2396 size_t idx = std::distance(predecessors.begin(), pos);
2397 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2398 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2399 break;
2400 }
2401 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2402 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002403 }
2404}
2405
2406// Create a new basic block with block_id as num_blocks_ that is
2407// post-incremented.
2408BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2409 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002410 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002411 return res;
2412}
2413
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002414void MIRGraph::CalculateBasicBlockInformation() {
2415 PassDriverMEPostOpt driver(cu_);
2416 driver.Launch();
2417}
2418
2419void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002420 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002421}
2422
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002423int MIR::DecodedInstruction::FlagsOf() const {
2424 // Calculate new index.
2425 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2426
2427 // Check if it is an extended or not.
2428 if (idx < 0) {
2429 return Instruction::FlagsOf(opcode);
2430 }
2431
2432 // For extended, we use a switch.
2433 switch (static_cast<int>(opcode)) {
2434 case kMirOpPhi:
2435 return Instruction::kContinue;
2436 case kMirOpCopy:
2437 return Instruction::kContinue;
2438 case kMirOpFusedCmplFloat:
2439 return Instruction::kContinue | Instruction::kBranch;
2440 case kMirOpFusedCmpgFloat:
2441 return Instruction::kContinue | Instruction::kBranch;
2442 case kMirOpFusedCmplDouble:
2443 return Instruction::kContinue | Instruction::kBranch;
2444 case kMirOpFusedCmpgDouble:
2445 return Instruction::kContinue | Instruction::kBranch;
2446 case kMirOpFusedCmpLong:
2447 return Instruction::kContinue | Instruction::kBranch;
2448 case kMirOpNop:
2449 return Instruction::kContinue;
2450 case kMirOpNullCheck:
2451 return Instruction::kContinue | Instruction::kThrow;
2452 case kMirOpRangeCheck:
2453 return Instruction::kContinue | Instruction::kThrow;
2454 case kMirOpDivZeroCheck:
2455 return Instruction::kContinue | Instruction::kThrow;
2456 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002457 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002458 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002459 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002460 case kMirOpSelect:
2461 return Instruction::kContinue;
2462 case kMirOpConstVector:
2463 return Instruction::kContinue;
2464 case kMirOpMoveVector:
2465 return Instruction::kContinue;
2466 case kMirOpPackedMultiply:
2467 return Instruction::kContinue;
2468 case kMirOpPackedAddition:
2469 return Instruction::kContinue;
2470 case kMirOpPackedSubtract:
2471 return Instruction::kContinue;
2472 case kMirOpPackedShiftLeft:
2473 return Instruction::kContinue;
2474 case kMirOpPackedSignedShiftRight:
2475 return Instruction::kContinue;
2476 case kMirOpPackedUnsignedShiftRight:
2477 return Instruction::kContinue;
2478 case kMirOpPackedAnd:
2479 return Instruction::kContinue;
2480 case kMirOpPackedOr:
2481 return Instruction::kContinue;
2482 case kMirOpPackedXor:
2483 return Instruction::kContinue;
2484 case kMirOpPackedAddReduce:
2485 return Instruction::kContinue;
2486 case kMirOpPackedReduce:
2487 return Instruction::kContinue;
2488 case kMirOpPackedSet:
2489 return Instruction::kContinue;
2490 case kMirOpReserveVectorRegisters:
2491 return Instruction::kContinue;
2492 case kMirOpReturnVectorRegisters:
2493 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002494 case kMirOpMemBarrier:
2495 return Instruction::kContinue;
2496 case kMirOpPackedArrayGet:
2497 return Instruction::kContinue | Instruction::kThrow;
2498 case kMirOpPackedArrayPut:
2499 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002500 default:
2501 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2502 return 0;
2503 }
2504}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002505} // namespace art