blob: 7c0a996a433e26d8935a361b4f5edce6ef5cea14 [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 Markoe39c54e2014-09-22 14:50:02 +010089 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
90 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
91 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
92 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
93 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
94 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
95 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
buzbee311ca162013-02-28 15:56:43 -080096 i_dom_list_(NULL),
97 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000098 temp_scoped_alloc_(),
99 temp_insn_data_(nullptr),
100 temp_bit_vector_size_(0u),
101 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100102 temp_gvn_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100103 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800104 try_block_addr_(NULL),
105 entry_block_(NULL),
106 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800107 num_blocks_(0),
108 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100109 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100110 m_units_(arena->Adapter()),
111 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800112 current_method_(kInvalidEntry),
113 current_offset_(kInvalidEntry),
114 def_count_(0),
115 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700116 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100117 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700118 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700119 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
120 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700121 arena_(arena),
122 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800123 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800124 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700125 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
126 requested_backend_temp_(false),
127 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000128 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000129 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100130 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
131 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
132 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
133 gen_suspend_test_list_(arena->Adapter()) {
134 use_counts_.reserve(256);
135 raw_use_counts_.reserve(256);
136 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700137 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700138
139
140 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
141 // X86 requires a temp to keep track of the method address.
142 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
143 // this needs to be updated to reserve 0 temps for BE.
144 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
145 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
146 } else {
147 // Other architectures do not have a known lower bound for non-special temps.
148 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
149 max_available_non_special_compiler_temps_ = 0;
150 reserved_temps_for_backend_ = 0;
151 }
buzbee311ca162013-02-28 15:56:43 -0800152}
153
Ian Rogers6282dc12013-04-18 15:54:02 -0700154MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100155 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700156 STLDeleteElements(&m_units_);
157}
158
buzbee311ca162013-02-28 15:56:43 -0800159/*
160 * Parse an instruction, return the length of the instruction
161 */
Ian Rogers29a26482014-05-02 15:27:29 -0700162int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
163 const Instruction* inst = Instruction::At(code_ptr);
164 decoded_instruction->opcode = inst->Opcode();
165 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
166 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
167 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
168 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
169 if (inst->HasVarArgs()) {
170 inst->GetVarArgs(decoded_instruction->arg);
171 }
172 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800173}
174
175
176/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700177BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700178 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700179 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800180 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700181 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800182 while (insn) {
183 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700184 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800185 insn = insn->next;
186 }
187 if (insn == NULL) {
188 LOG(FATAL) << "Break split failed";
189 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100190 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800191
192 bottom_block->start_offset = code_offset;
193 bottom_block->first_mir_insn = insn;
194 bottom_block->last_mir_insn = orig_block->last_mir_insn;
195
Junmo Park90223cc2014-08-04 18:51:21 +0900196 /* If this block was terminated by a return, conditional branch or throw,
197 * the flag needs to go with the bottom block
198 */
buzbee311ca162013-02-28 15:56:43 -0800199 bottom_block->terminated_by_return = orig_block->terminated_by_return;
200 orig_block->terminated_by_return = false;
201
Junmo Park90223cc2014-08-04 18:51:21 +0900202 bottom_block->conditional_branch = orig_block->conditional_branch;
203 orig_block->conditional_branch = false;
204
205 bottom_block->explicit_throw = orig_block->explicit_throw;
206 orig_block->explicit_throw = false;
207
buzbee311ca162013-02-28 15:56:43 -0800208 /* Handle the taken path */
209 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700210 if (bottom_block->taken != NullBasicBlockId) {
211 orig_block->taken = NullBasicBlockId;
212 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100213 bb_taken->ErasePredecessor(orig_block->id);
214 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800215 }
216
217 /* Handle the fallthrough path */
218 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700219 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100220 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700221 if (bottom_block->fall_through != NullBasicBlockId) {
222 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100223 bb_fall_through->ErasePredecessor(orig_block->id);
224 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800225 }
226
227 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700228 if (orig_block->successor_block_list_type != kNotUsed) {
229 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100230 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700231 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100232 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
233 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700234 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700235 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100236 bb->ErasePredecessor(orig_block->id);
237 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700238 }
buzbee311ca162013-02-28 15:56:43 -0800239 }
240 }
241
buzbee0d829482013-10-11 15:24:55 -0700242 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700243 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800244
buzbee311ca162013-02-28 15:56:43 -0800245 /*
246 * Update the immediate predecessor block pointer so that outgoing edges
247 * can be applied to the proper block.
248 */
249 if (immed_pred_block_p) {
250 DCHECK_EQ(*immed_pred_block_p, orig_block);
251 *immed_pred_block_p = bottom_block;
252 }
buzbeeb48819d2013-09-14 16:15:25 -0700253
254 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000255 DCHECK(insn != nullptr);
256 DCHECK(insn != orig_block->first_mir_insn);
257 DCHECK(insn == bottom_block->first_mir_insn);
258 DCHECK_EQ(insn->offset, bottom_block->start_offset);
259 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700260 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100261 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Vladimir Marko4376c872014-01-23 12:39:29 +0000262 MIR* p = insn;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100263 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000264 while (p != bottom_block->last_mir_insn) {
265 p = p->next;
266 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700267 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700268 int opcode = p->dalvikInsn.opcode;
269 /*
270 * Some messiness here to ensure that we only enter real opcodes and only the
271 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000272 * CHECK and work portions. Since the 2nd half of a split operation is always
273 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700274 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700275 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100276 DCHECK_EQ(dex_pc_to_block_map_[p->offset], orig_block->id);
277 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700278 }
buzbeeb48819d2013-09-14 16:15:25 -0700279 }
280
buzbee311ca162013-02-28 15:56:43 -0800281 return bottom_block;
282}
283
284/*
285 * Given a code offset, find out the block that starts with it. If the offset
286 * is in the middle of an existing block, split it into two. If immed_pred_block_p
287 * is not non-null and is the block being split, update *immed_pred_block_p to
288 * point to the bottom block so that outgoing edges can be set up properly
289 * (by the caller)
290 * Utilizes a map for fast lookup of the typical cases.
291 */
buzbee0d829482013-10-11 15:24:55 -0700292BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700293 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700294 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800295 return NULL;
296 }
buzbeeb48819d2013-09-14 16:15:25 -0700297
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100298 int block_id = dex_pc_to_block_map_[code_offset];
299 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700300
301 if ((bb != NULL) && (bb->start_offset == code_offset)) {
302 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700303 return bb;
304 }
buzbee311ca162013-02-28 15:56:43 -0800305
buzbeeb48819d2013-09-14 16:15:25 -0700306 // No direct hit.
307 if (!create) {
308 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800309 }
310
buzbeeb48819d2013-09-14 16:15:25 -0700311 if (bb != NULL) {
312 // The target exists somewhere in an existing block.
313 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
314 }
315
316 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100317 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800318 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100319 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800320 return bb;
321}
322
buzbeeb48819d2013-09-14 16:15:25 -0700323
buzbee311ca162013-02-28 15:56:43 -0800324/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700325void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800326 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700327 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800328
329 if (tries_size == 0) {
330 return;
331 }
332
333 for (int i = 0; i < tries_size; i++) {
334 const DexFile::TryItem* pTry =
335 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700336 DexOffset start_offset = pTry->start_addr_;
337 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800338 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700339 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800340 }
341 }
342
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700343 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800344 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
345 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
346 for (uint32_t idx = 0; idx < handlers_size; idx++) {
347 CatchHandlerIterator iterator(handlers_ptr);
348 for (; iterator.HasNext(); iterator.Next()) {
349 uint32_t address = iterator.GetHandlerAddress();
350 FindBlock(address, false /* split */, true /*create*/,
351 /* immed_pred_block_p */ NULL);
352 }
353 handlers_ptr = iterator.EndDataPointer();
354 }
355}
356
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100357bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
358 NarrowDexOffset catch_offset) {
359 // Catches for monitor-exit during stack unwinding have the pattern
360 // move-exception (move)* (goto)? monitor-exit throw
361 // In the currently generated dex bytecode we see these catching a bytecode range including
362 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
363 // it's the case for a given monitor-exit and catch block so that we can ignore it.
364 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
365 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
366 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700367 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100368 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
369 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700370 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100371 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
372 if (check_insn->VRegA_11x() == monitor_reg) {
373 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
374 return false;
375 }
376 check_insn = check_insn->Next();
377 while (true) {
378 int dest = -1;
379 bool wide = false;
380 switch (check_insn->Opcode()) {
381 case Instruction::MOVE_WIDE:
382 wide = true;
383 // Intentional fall-through.
384 case Instruction::MOVE_OBJECT:
385 case Instruction::MOVE:
386 dest = check_insn->VRegA_12x();
387 break;
388
389 case Instruction::MOVE_WIDE_FROM16:
390 wide = true;
391 // Intentional fall-through.
392 case Instruction::MOVE_OBJECT_FROM16:
393 case Instruction::MOVE_FROM16:
394 dest = check_insn->VRegA_22x();
395 break;
396
397 case Instruction::MOVE_WIDE_16:
398 wide = true;
399 // Intentional fall-through.
400 case Instruction::MOVE_OBJECT_16:
401 case Instruction::MOVE_16:
402 dest = check_insn->VRegA_32x();
403 break;
404
405 case Instruction::GOTO:
406 case Instruction::GOTO_16:
407 case Instruction::GOTO_32:
408 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
409 // Intentional fall-through.
410 default:
411 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
412 check_insn->VRegA_11x() == monitor_reg;
413 }
414
415 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
416 return false;
417 }
418
419 check_insn = check_insn->Next();
420 }
421}
422
buzbee311ca162013-02-28 15:56:43 -0800423/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700424BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
425 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700426 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700427 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800428 switch (insn->dalvikInsn.opcode) {
429 case Instruction::GOTO:
430 case Instruction::GOTO_16:
431 case Instruction::GOTO_32:
432 target += insn->dalvikInsn.vA;
433 break;
434 case Instruction::IF_EQ:
435 case Instruction::IF_NE:
436 case Instruction::IF_LT:
437 case Instruction::IF_GE:
438 case Instruction::IF_GT:
439 case Instruction::IF_LE:
440 cur_block->conditional_branch = true;
441 target += insn->dalvikInsn.vC;
442 break;
443 case Instruction::IF_EQZ:
444 case Instruction::IF_NEZ:
445 case Instruction::IF_LTZ:
446 case Instruction::IF_GEZ:
447 case Instruction::IF_GTZ:
448 case Instruction::IF_LEZ:
449 cur_block->conditional_branch = true;
450 target += insn->dalvikInsn.vB;
451 break;
452 default:
453 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
454 }
buzbeeb48819d2013-09-14 16:15:25 -0700455 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700456 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800457 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700458 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100459 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800460
461 /* Always terminate the current block for conditional branches */
462 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700463 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800464 /*
465 * If the method is processed
466 * in sequential order from the
467 * beginning, we don't need to
468 * specify split for continue
469 * blocks. However, this
470 * routine can be called by
471 * compileLoop, which starts
472 * parsing the method from an
473 * arbitrary address in the
474 * method body.
475 */
476 true,
477 /* create */
478 true,
479 /* immed_pred_block_p */
480 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700481 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100482 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800483 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700484 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800485 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800486 }
487 return cur_block;
488}
489
490/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800491BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
492 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800493 const uint16_t* switch_data =
494 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
495 int size;
496 const int* keyTable;
497 const int* target_table;
498 int i;
499 int first_key;
500
501 /*
502 * Packed switch data format:
503 * ushort ident = 0x0100 magic value
504 * ushort size number of entries in the table
505 * int first_key first (and lowest) switch case value
506 * int targets[size] branch targets, relative to switch opcode
507 *
508 * Total size is (4+size*2) 16-bit code units.
509 */
510 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
511 DCHECK_EQ(static_cast<int>(switch_data[0]),
512 static_cast<int>(Instruction::kPackedSwitchSignature));
513 size = switch_data[1];
514 first_key = switch_data[2] | (switch_data[3] << 16);
515 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700516 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800517 /*
518 * Sparse switch data format:
519 * ushort ident = 0x0200 magic value
520 * ushort size number of entries in the table; > 0
521 * int keys[size] keys, sorted low-to-high; 32-bit aligned
522 * int targets[size] branch targets, relative to switch opcode
523 *
524 * Total size is (2+size*4) 16-bit code units.
525 */
526 } else {
527 DCHECK_EQ(static_cast<int>(switch_data[0]),
528 static_cast<int>(Instruction::kSparseSwitchSignature));
529 size = switch_data[1];
530 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
531 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700532 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800533 }
534
buzbee0d829482013-10-11 15:24:55 -0700535 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800536 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700537 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800538 }
buzbee0d829482013-10-11 15:24:55 -0700539 cur_block->successor_block_list_type =
540 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100541 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800542
543 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700544 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800545 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700546 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700547 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000548 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700549 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800550 successor_block_info->key =
551 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
552 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100553 cur_block->successor_blocks.push_back(successor_block_info);
554 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800555 }
556
557 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700558 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
559 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700560 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100561 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800562 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800563}
564
565/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700566BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
567 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700568 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700569 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800570 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
571 bool build_all_edges =
572 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800573
574 /* In try block */
575 if (in_try_block) {
576 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
577
buzbee0d829482013-10-11 15:24:55 -0700578 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800579 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
580 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700581 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800582 }
583
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700584 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700585 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800586 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100587 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
588 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
589 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
590 continue;
591 }
592 if (cur_block->successor_block_list_type == kNotUsed) {
593 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100594 }
buzbee311ca162013-02-28 15:56:43 -0800595 catch_block->catch_entry = true;
596 if (kIsDebugBuild) {
597 catches_.insert(catch_block->start_offset);
598 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700599 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000600 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700601 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800602 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100603 cur_block->successor_blocks.push_back(successor_block_info);
604 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800605 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100606 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
607 }
608 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100609 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700610 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800611 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100612 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800613 }
614
buzbee17189ac2013-11-08 11:07:02 -0800615 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800616 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700617 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700618 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800619 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
620 /* immed_pred_block_p */ NULL);
621 }
622 if (!in_try_block) {
623 // Don't split a THROW that can't rethrow - we're done.
624 return cur_block;
625 }
626 }
627
buzbee17189ac2013-11-08 11:07:02 -0800628 if (!build_all_edges) {
629 /*
630 * Even though there is an exception edge here, control cannot return to this
631 * method. Thus, for the purposes of dataflow analysis and optimization, we can
632 * ignore the edge. Doing this reduces compile time, and increases the scope
633 * of the basic-block level optimization pass.
634 */
635 return cur_block;
636 }
637
buzbee311ca162013-02-28 15:56:43 -0800638 /*
639 * Split the potentially-throwing instruction into two parts.
640 * The first half will be a pseudo-op that captures the exception
641 * edges and terminates the basic block. It always falls through.
642 * Then, create a new basic block that begins with the throwing instruction
643 * (minus exceptions). Note: this new basic block must NOT be entered into
644 * the block_map. If the potentially-throwing instruction is the target of a
645 * future branch, we need to find the check psuedo half. The new
646 * basic block containing the work portion of the instruction should
647 * only be entered via fallthrough from the block containing the
648 * pseudo exception edge MIR. Note also that this new block is
649 * not automatically terminated after the work portion, and may
650 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700651 *
652 * Note also that the dex_pc_to_block_map_ entry for the potentially
653 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800654 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100655 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800656 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700657 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100658 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700659 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800660 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700661 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700662 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800663 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700664 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800665 return new_block;
666}
667
668/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
669void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700670 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700671 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800672 current_code_item_ = code_item;
673 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
674 current_method_ = m_units_.size();
675 current_offset_ = 0;
676 // TODO: will need to snapshot stack image and use that as the mir context identification.
677 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000678 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
679 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800680 const uint16_t* code_ptr = current_code_item_->insns_;
681 const uint16_t* code_end =
682 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
683
684 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700685 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100686 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
687 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 -0700688
buzbee311ca162013-02-28 15:56:43 -0800689 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700690 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
691 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800692
693 // If this is the first method, set up default entry and exit blocks.
694 if (current_method_ == 0) {
695 DCHECK(entry_block_ == NULL);
696 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700697 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700698 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100699 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700700 DCHECK_EQ(null_block->id, NullBasicBlockId);
701 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100702 entry_block_ = CreateNewBB(kEntryBlock);
703 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800704 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
705 cu_->dex_file = &dex_file;
706 cu_->class_def_idx = class_def_idx;
707 cu_->method_idx = method_idx;
708 cu_->access_flags = access_flags;
709 cu_->invoke_type = invoke_type;
710 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800711 cu_->code_item = current_code_item_;
712 } else {
713 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
714 /*
715 * Will need to manage storage for ins & outs, push prevous state and update
716 * insert point.
717 */
718 }
719
720 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100721 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700722 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800723 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700724 // TODO: for inlining support, insert at the insert point rather than entry block.
725 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100726 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800727
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000728 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800729 ProcessTryCatchBlocks();
730
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000731 uint64_t merged_df_flags = 0u;
732
buzbee311ca162013-02-28 15:56:43 -0800733 /* Parse all instructions and put them into containing basic blocks */
734 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700735 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800736 insn->offset = current_offset_;
737 insn->m_unit_index = current_method_;
738 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800739 Instruction::Code opcode = insn->dalvikInsn.opcode;
740 if (opcode_count_ != NULL) {
741 opcode_count_[static_cast<int>(opcode)]++;
742 }
743
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700744 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800745 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800746
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700747 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000748 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800749
750 if (df_flags & DF_HAS_DEFS) {
751 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
752 }
753
buzbee1da1e2f2013-11-15 13:37:01 -0800754 if (df_flags & DF_LVN) {
755 cur_block->use_lvn = true; // Run local value numbering on this basic block.
756 }
757
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700758 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700759 if (opcode == Instruction::NOP) {
760 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
761 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
762 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
763 uint16_t following_raw_instruction = code_ptr[1];
764 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
765 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
766 (following_raw_instruction == Instruction::kArrayDataSignature)) {
767 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
768 }
769 }
770 if (width == 1) {
771 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700772 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700773 } else {
buzbee0d829482013-10-11 15:24:55 -0700774 DCHECK(cur_block->fall_through == NullBasicBlockId);
775 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700776 // Unreachable instruction, mark for no continuation.
777 flags &= ~Instruction::kContinue;
778 }
779 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700780 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700781 }
782
buzbeeb48819d2013-09-14 16:15:25 -0700783 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100784 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700785
buzbee27247762013-07-28 12:03:58 -0700786 code_ptr += width;
787
buzbee311ca162013-02-28 15:56:43 -0800788 if (flags & Instruction::kBranch) {
789 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
790 width, flags, code_ptr, code_end);
791 } else if (flags & Instruction::kReturn) {
792 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700793 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100794 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800795 /*
796 * Terminate the current block if there are instructions
797 * afterwards.
798 */
799 if (code_ptr < code_end) {
800 /*
801 * Create a fallthrough block for real instructions
802 * (incl. NOP).
803 */
buzbee27247762013-07-28 12:03:58 -0700804 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
805 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800806 }
807 } else if (flags & Instruction::kThrow) {
808 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
809 code_ptr, code_end);
810 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800811 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800812 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700813 if (verify_flags & Instruction::kVerifyVarArgRange ||
814 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800815 /*
816 * The Quick backend's runtime model includes a gap between a method's
817 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
818 * which spans the gap is somewhat complicated, and should not happen
819 * in normal usage of dx. Punt to the interpreter.
820 */
821 int first_reg_in_range = insn->dalvikInsn.vC;
822 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
823 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
824 punt_to_interpreter_ = true;
825 }
826 }
buzbee311ca162013-02-28 15:56:43 -0800827 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700828 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800829 false, /* immed_pred_block_p */ NULL);
830 if (next_block) {
831 /*
832 * The next instruction could be the target of a previously parsed
833 * forward branch so a block is already created. If the current
834 * instruction is not an unconditional branch, connect them through
835 * the fall-through link.
836 */
buzbee0d829482013-10-11 15:24:55 -0700837 DCHECK(cur_block->fall_through == NullBasicBlockId ||
838 GetBasicBlock(cur_block->fall_through) == next_block ||
839 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800840
buzbee0d829482013-10-11 15:24:55 -0700841 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
842 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100843 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800844 }
845 cur_block = next_block;
846 }
847 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000848 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000849
buzbee311ca162013-02-28 15:56:43 -0800850 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
851 DumpCFG("/sdcard/1_post_parse_cfg/", true);
852 }
853
854 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700855 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800856 }
857}
858
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700859void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800860 DCHECK(opcode_count_ != NULL);
861 LOG(INFO) << "Opcode Count";
862 for (int i = 0; i < kNumPackedOpcodes; i++) {
863 if (opcode_count_[i] != 0) {
864 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
865 << " " << opcode_count_[i];
866 }
867 }
868}
869
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700870uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
871 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
872 return oat_data_flow_attributes_[opcode];
873}
874
875uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
876 DCHECK(mir != nullptr);
877 Instruction::Code opcode = mir->dalvikInsn.opcode;
878 return GetDataFlowAttributes(opcode);
879}
880
buzbee311ca162013-02-28 15:56:43 -0800881// TODO: use a configurable base prefix, and adjust callers to supply pass name.
882/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800883void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800884 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700885 static AtomicInteger cnt(0);
886
887 // Increment counter to get a unique file number.
888 cnt++;
889
buzbee311ca162013-02-28 15:56:43 -0800890 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
891 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700892 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800893 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700894 suffix == nullptr ? "" : suffix,
895 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800896 file = fopen(fname.c_str(), "w");
897 if (file == NULL) {
898 return;
899 }
900 fprintf(file, "digraph G {\n");
901
902 fprintf(file, " rankdir=TB\n");
903
904 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
905 int idx;
906
907 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100908 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700909 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700910 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800911 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700912 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800913 if (bb->block_type == kEntryBlock) {
914 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
915 } else if (bb->block_type == kExitBlock) {
916 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
917 } else if (bb->block_type == kDalvikByteCode) {
918 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
919 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700920 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800921 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
922 bb->first_mir_insn ? " | " : " ");
923 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
924 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700925 fprintf(file, " {%04x %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400926 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700927 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
928 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400929 extended_mir_op_names_[opcode - kMirOpFirst],
930 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
931 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700932 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700933 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700934 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
935 (mir->optimization_flags & MIR_IGNORE_CLINIT_CHECK) != 0 ? " no_clinit" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400936 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800937 }
938 fprintf(file, " }\"];\n\n");
939 } else if (bb->block_type == kExceptionHandling) {
940 char block_name[BLOCK_NAME_LEN];
941
942 GetBlockName(bb, block_name);
943 fprintf(file, " %s [shape=invhouse];\n", block_name);
944 }
945
946 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
947
buzbee0d829482013-10-11 15:24:55 -0700948 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800949 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700950 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800951 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
952 block_name1, block_name2);
953 }
buzbee0d829482013-10-11 15:24:55 -0700954 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800955 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700956 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800957 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
958 }
959
buzbee0d829482013-10-11 15:24:55 -0700960 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800961 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
962 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700963 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800964
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100965 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800966 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100967 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700968 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800969 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100970 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800971 successor_block_info->key,
972 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100973 (succ_id != last_succ_id) ? " | " : " ");
974 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800975 }
976 fprintf(file, " }\"];\n\n");
977
978 GetBlockName(bb, block_name1);
979 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
980 block_name1, bb->start_offset, bb->id);
981
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700982 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100984 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800986
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700987 GetBlockName(dest_block, block_name2);
988 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
989 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800990 }
991 }
992 fprintf(file, "\n");
993
994 if (cu_->verbose) {
995 /* Display the dominator tree */
996 GetBlockName(bb, block_name1);
997 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
998 block_name1, block_name1);
999 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001000 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001001 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1002 }
1003 }
1004 }
1005 fprintf(file, "}\n");
1006 fclose(file);
1007}
1008
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001009/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001010void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001011 // Insert it after the last MIR.
1012 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001013}
1014
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001015void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1016 // Insert it after the last MIR.
1017 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1018}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001019
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001020void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1021 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1022 MIR* new_mir = *it;
1023
1024 // Add a copy of each MIR.
1025 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1026 }
buzbee1fd33462013-03-25 13:40:45 -07001027}
1028
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001029/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001030void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001031 InsertMIRListAfter(current_mir, new_mir, new_mir);
1032}
buzbee1fd33462013-03-25 13:40:45 -07001033
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001034void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1035 // If no MIR, we are done.
1036 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1037 return;
buzbee1fd33462013-03-25 13:40:45 -07001038 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001039
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001040 // If insert_after is null, assume BB is empty.
1041 if (insert_after == nullptr) {
1042 first_mir_insn = first_list_mir;
1043 last_mir_insn = last_list_mir;
1044 last_list_mir->next = nullptr;
1045 } else {
1046 MIR* after_list = insert_after->next;
1047 insert_after->next = first_list_mir;
1048 last_list_mir->next = after_list;
1049 if (after_list == nullptr) {
1050 last_mir_insn = last_list_mir;
1051 }
1052 }
1053
1054 // Set this BB to be the basic block of the MIRs.
1055 MIR* last = last_list_mir->next;
1056 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1057 mir->bb = id;
1058 }
1059}
1060
1061/* Insert an MIR instruction to the head of a basic block. */
1062void BasicBlock::PrependMIR(MIR* mir) {
1063 InsertMIRListBefore(first_mir_insn, mir, mir);
1064}
1065
1066void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1067 // Insert it before the first MIR.
1068 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1069}
1070
1071void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1072 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1073 MIR* mir = *it;
1074
1075 InsertMIRListBefore(first_mir_insn, mir, mir);
1076 }
1077}
1078
1079/* Insert a MIR instruction before the specified MIR. */
1080void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1081 // Insert as a single element list.
1082 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001083}
1084
1085MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1086 MIR* current = first_mir_insn;
1087
1088 while (current != nullptr) {
1089 MIR* next = current->next;
1090
1091 if (next == mir) {
1092 return current;
1093 }
1094
1095 current = next;
1096 }
1097
1098 return nullptr;
1099}
1100
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001101void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1102 // If no MIR, we are done.
1103 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1104 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001105 }
1106
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001107 // If insert_before is null, assume BB is empty.
1108 if (insert_before == nullptr) {
1109 first_mir_insn = first_list_mir;
1110 last_mir_insn = last_list_mir;
1111 last_list_mir->next = nullptr;
1112 } else {
1113 if (first_mir_insn == insert_before) {
1114 last_list_mir->next = first_mir_insn;
1115 first_mir_insn = first_list_mir;
1116 } else {
1117 // Find the preceding MIR.
1118 MIR* before_list = FindPreviousMIR(insert_before);
1119 DCHECK(before_list != nullptr);
1120 before_list->next = first_list_mir;
1121 last_list_mir->next = insert_before;
1122 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001123 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001124
1125 // Set this BB to be the basic block of the MIRs.
1126 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1127 mir->bb = id;
1128 }
1129}
1130
1131bool BasicBlock::RemoveMIR(MIR* mir) {
1132 // Remove as a single element list.
1133 return RemoveMIRList(mir, mir);
1134}
1135
1136bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1137 if (first_list_mir == nullptr) {
1138 return false;
1139 }
1140
1141 // Try to find the MIR.
1142 MIR* before_list = nullptr;
1143 MIR* after_list = nullptr;
1144
1145 // If we are removing from the beginning of the MIR list.
1146 if (first_mir_insn == first_list_mir) {
1147 before_list = nullptr;
1148 } else {
1149 before_list = FindPreviousMIR(first_list_mir);
1150 if (before_list == nullptr) {
1151 // We did not find the mir.
1152 return false;
1153 }
1154 }
1155
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001156 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001157 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1158 mir->bb = NullBasicBlockId;
1159 }
1160
1161 after_list = last_list_mir->next;
1162
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001163 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001164 if (before_list == nullptr) {
1165 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001166 } else {
1167 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001168 }
1169
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001170 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001171 if (after_list == nullptr) {
1172 last_mir_insn = before_list;
1173 }
1174
1175 return true;
buzbee1fd33462013-03-25 13:40:45 -07001176}
1177
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001178MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001179 MIR* next_mir = nullptr;
1180
1181 if (current != nullptr) {
1182 next_mir = current->next;
1183 }
1184
1185 if (next_mir == nullptr) {
1186 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001187 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1188 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001189 }
1190 }
1191
1192 return next_mir;
1193}
1194
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001195static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1196 DCHECK(decoded_mir != nullptr);
1197 OpSize type = static_cast<OpSize>(type_size >> 16);
1198 uint16_t vect_size = (type_size & 0xFFFF);
1199
1200 // Now print the type and vector size.
1201 std::stringstream ss;
1202 ss << " (type:";
1203 ss << type;
1204 ss << " vectsize:";
1205 ss << vect_size;
1206 ss << ")";
1207
1208 decoded_mir->append(ss.str());
1209}
1210
1211void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1212 DCHECK(decoded_mir != nullptr);
1213 int opcode = mir->dalvikInsn.opcode;
1214 SSARepresentation* ssa_rep = mir->ssa_rep;
1215 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1216 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1217
1218 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1219
1220 switch (opcode) {
1221 case kMirOpPhi: {
1222 if (defs > 0 && uses > 0) {
1223 BasicBlockId* incoming = mir->meta.phi_incoming;
1224 decoded_mir->append(StringPrintf(" %s = (%s",
1225 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1226 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1227 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1228 for (int i = 1; i < uses; i++) {
1229 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1230 }
1231 decoded_mir->append(")");
1232 }
1233 break;
1234 }
1235 case kMirOpCopy:
1236 if (ssa_rep != nullptr) {
1237 decoded_mir->append(" ");
1238 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1239 if (defs > 1) {
1240 decoded_mir->append(", ");
1241 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1242 }
1243 decoded_mir->append(" = ");
1244 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1245 if (uses > 1) {
1246 decoded_mir->append(", ");
1247 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1248 }
1249 } else {
1250 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1251 }
1252 break;
1253 case kMirOpFusedCmplFloat:
1254 case kMirOpFusedCmpgFloat:
1255 case kMirOpFusedCmplDouble:
1256 case kMirOpFusedCmpgDouble:
1257 case kMirOpFusedCmpLong:
1258 if (ssa_rep != nullptr) {
1259 decoded_mir->append(" ");
1260 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1261 for (int i = 1; i < uses; i++) {
1262 decoded_mir->append(", ");
1263 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1264 }
1265 } else {
1266 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1267 }
1268 break;
1269 case kMirOpMoveVector:
1270 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1271 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1272 break;
1273 case kMirOpPackedAddition:
1274 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1275 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1276 break;
1277 case kMirOpPackedMultiply:
1278 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1279 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1280 break;
1281 case kMirOpPackedSubtract:
1282 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1283 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1284 break;
1285 case kMirOpPackedAnd:
1286 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1287 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1288 break;
1289 case kMirOpPackedOr:
1290 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1291 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1292 break;
1293 case kMirOpPackedXor:
1294 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1295 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1296 break;
1297 case kMirOpPackedShiftLeft:
1298 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1299 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1300 break;
1301 case kMirOpPackedUnsignedShiftRight:
1302 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1303 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1304 break;
1305 case kMirOpPackedSignedShiftRight:
1306 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1307 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1308 break;
1309 case kMirOpConstVector:
1310 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1311 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1312 break;
1313 case kMirOpPackedSet:
1314 if (ssa_rep != nullptr) {
1315 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1316 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1317 if (uses > 1) {
1318 decoded_mir->append(", ");
1319 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1320 }
1321 } else {
1322 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1323 }
1324 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1325 break;
1326 case kMirOpPackedAddReduce:
1327 if (ssa_rep != nullptr) {
1328 decoded_mir->append(" ");
1329 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1330 if (defs > 1) {
1331 decoded_mir->append(", ");
1332 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1333 }
1334 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1335 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1336 if (uses > 1) {
1337 decoded_mir->append(", ");
1338 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1339 }
1340 } else {
1341 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1342 }
1343 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1344 break;
1345 case kMirOpPackedReduce:
1346 if (ssa_rep != nullptr) {
1347 decoded_mir->append(" ");
1348 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1349 if (defs > 1) {
1350 decoded_mir->append(", ");
1351 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1352 }
1353 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1354 } else {
1355 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1356 }
1357 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1358 break;
1359 case kMirOpReserveVectorRegisters:
1360 case kMirOpReturnVectorRegisters:
1361 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1362 break;
1363 case kMirOpMemBarrier: {
1364 decoded_mir->append(" type:");
1365 std::stringstream ss;
1366 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1367 decoded_mir->append(ss.str());
1368 break;
1369 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001370 case kMirOpPackedArrayGet:
1371 case kMirOpPackedArrayPut:
1372 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1373 if (ssa_rep != nullptr) {
1374 decoded_mir->append(StringPrintf(", %s[%s]",
1375 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1376 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1377 } else {
1378 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1379 }
1380 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1381 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001382 default:
1383 break;
1384 }
1385}
1386
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001387char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001388 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001389 std::string str;
1390 int flags = 0;
1391 int opcode = insn.opcode;
1392 char* ret;
1393 bool nop = false;
1394 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001395 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001396
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001397 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001398 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1399 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1400 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001401 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001402 insn = mir->meta.throw_insn->dalvikInsn;
1403 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001404 opcode = insn.opcode;
1405 } else if (opcode == kMirOpNop) {
1406 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001407 // Recover original opcode.
1408 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1409 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001410 nop = true;
1411 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001412 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1413 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001414
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001415 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001416 // Note that this does not check the MIR's opcode in all cases. In cases where it
1417 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1418 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001419 } else {
1420 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001421 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001422 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001423
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001424 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001425 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1426 (dalvik_format == Instruction::k3rc));
1427 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001428 str.append(" ");
1429 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1430 if (defs > 1) {
1431 str.append(", ");
1432 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1433 }
buzbee1fd33462013-03-25 13:40:45 -07001434 if (uses != 0) {
1435 str.append(", ");
1436 }
1437 }
1438 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001439 str.append(" ");
1440 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001441 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1442 // For the listing, skip the high sreg.
1443 i++;
1444 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001445 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001446 str.append(",");
1447 }
1448 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001449
buzbee1fd33462013-03-25 13:40:45 -07001450 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001451 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001452 case Instruction::k21s:
1453 case Instruction::k31i:
1454 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001455 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001456 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001457 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001458 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001459 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001460 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001461 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001462 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001463 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001464 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001465 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001466 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001467 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001468 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001469 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001470 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001471 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001472 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001473 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001474 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001475
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001476 if ((flags & Instruction::kBranch) != 0) {
1477 // For branches, decode the instructions to print out the branch targets.
1478 int offset = 0;
1479 switch (dalvik_format) {
1480 case Instruction::k21t:
1481 offset = insn.vB;
1482 break;
1483 case Instruction::k22t:
1484 offset = insn.vC;
1485 break;
1486 case Instruction::k10t:
1487 case Instruction::k20t:
1488 case Instruction::k30t:
1489 offset = insn.vA;
1490 break;
1491 default:
1492 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001493 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001494 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001495 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001496 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1497 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001498
1499 if (nop) {
1500 str.append("]--optimized away");
1501 }
buzbee1fd33462013-03-25 13:40:45 -07001502 }
1503 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001504 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001505 strncpy(ret, str.c_str(), length);
1506 return ret;
1507}
1508
1509/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001510void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001511 static const struct { const char before; const char after; } match[] = {
1512 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1513 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1514 };
buzbee1fd33462013-03-25 13:40:45 -07001515 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1516 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1517 }
1518}
1519
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001520std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001521 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1522 // the arena. We should be smarter and just place straight into the arena, or compute the
1523 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001524 int vreg = SRegToVReg(ssa_reg);
1525 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1526 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1527 } else {
1528 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1529 }
buzbee1fd33462013-03-25 13:40:45 -07001530}
1531
1532// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001533std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001534 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001535 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001536 return GetSSAName(ssa_reg);
1537 }
1538 if (IsConst(reg_location_[ssa_reg])) {
1539 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001540 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001541 ConstantValueWide(reg_location_[ssa_reg]));
1542 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001543 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001544 ConstantValue(reg_location_[ssa_reg]));
1545 }
1546 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001547 int vreg = SRegToVReg(ssa_reg);
1548 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1549 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1550 } else {
1551 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1552 }
buzbee1fd33462013-03-25 13:40:45 -07001553 }
1554}
1555
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001556void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001557 switch (bb->block_type) {
1558 case kEntryBlock:
1559 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1560 break;
1561 case kExitBlock:
1562 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1563 break;
1564 case kDalvikByteCode:
1565 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1566 break;
1567 case kExceptionHandling:
1568 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1569 bb->id);
1570 break;
1571 default:
1572 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1573 break;
1574 }
1575}
1576
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001577const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001578 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001579 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1580 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1581}
1582
1583/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001584void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001585 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001586 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001587 "Entry Block",
1588 "Code Block",
1589 "Exit Block",
1590 "Exception Handling",
1591 "Catch Block"
1592 };
1593
1594 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001595 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001596 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001597
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001598 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001599 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1600 bb->id,
1601 block_type_names[bb->block_type],
1602 bb->start_offset,
1603 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1604 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001605 if (bb->taken != NullBasicBlockId) {
1606 LOG(INFO) << " Taken branch: block " << bb->taken
1607 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001608 }
buzbee0d829482013-10-11 15:24:55 -07001609 if (bb->fall_through != NullBasicBlockId) {
1610 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1611 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001612 }
1613 }
1614}
1615
1616/*
1617 * Build an array of location records for the incoming arguments.
1618 * Note: one location record per word of arguments, with dummy
1619 * high-word loc for wide arguments. Also pull up any following
1620 * MOVE_RESULT and incorporate it into the invoke.
1621 */
1622CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001623 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001624 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001625 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001626 MIR* move_result_mir = FindMoveResult(bb, mir);
1627 if (move_result_mir == NULL) {
1628 info->result.location = kLocInvalid;
1629 } else {
1630 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001631 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1632 }
1633 info->num_arg_words = mir->ssa_rep->num_uses;
1634 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001635 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001636 for (int i = 0; i < info->num_arg_words; i++) {
1637 info->args[i] = GetRawSrc(mir, i);
1638 }
1639 info->opt_flags = mir->optimization_flags;
1640 info->type = type;
1641 info->is_range = is_range;
1642 info->index = mir->dalvikInsn.vB;
1643 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001644 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001645 return info;
1646}
1647
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001648// Allocate a new MIR.
1649MIR* MIRGraph::NewMIR() {
1650 MIR* mir = new (arena_) MIR();
1651 return mir;
1652}
1653
buzbee862a7602013-04-05 10:58:54 -07001654// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001655BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001656 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001657
buzbee862a7602013-04-05 10:58:54 -07001658 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001659 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001660 block_id_map_.Put(block_id, block_id);
1661 return bb;
1662}
buzbee1fd33462013-03-25 13:40:45 -07001663
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001664void MIRGraph::InitializeConstantPropagation() {
1665 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001666 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001667}
1668
1669void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001670 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001671 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001672 use_counts_.clear();
1673 use_counts_.reserve(num_ssa_regs + 32);
1674 use_counts_.resize(num_ssa_regs, 0u);
1675 raw_use_counts_.clear();
1676 raw_use_counts_.reserve(num_ssa_regs + 32);
1677 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001678}
1679
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001680void MIRGraph::SSATransformationStart() {
1681 DCHECK(temp_scoped_alloc_.get() == nullptr);
1682 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001683 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001684 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1685 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1686
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001687 // Update the maximum number of reachable blocks.
1688 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001689}
1690
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001691void MIRGraph::SSATransformationEnd() {
1692 // Verify the dataflow information after the pass.
1693 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1694 VerifyDataflow();
1695 }
1696
1697 temp_bit_vector_size_ = 0u;
1698 temp_bit_vector_ = nullptr;
1699 DCHECK(temp_scoped_alloc_.get() != nullptr);
1700 temp_scoped_alloc_.reset();
1701}
1702
Vladimir Marko55fff042014-07-10 12:42:52 +01001703static BasicBlock* SelectTopologicalSortOrderFallBack(
1704 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1705 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1706 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1707 // No true loop head has been found but there may be true loop heads after the mess we need
1708 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1709 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1710 BasicBlock* fall_back = nullptr;
1711 size_t fall_back_num_reachable = 0u;
1712 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1713 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1714 AllNodesIterator iter(mir_graph);
1715 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1716 if (candidate->hidden || // Hidden, or
1717 candidate->visited || // already processed, or
1718 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1719 (current_loop != nullptr && // outside current loop.
1720 !current_loop->IsBitSet(candidate->id))) {
1721 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001722 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001723 DCHECK(tmp_stack->empty());
1724 tmp_stack->push_back(candidate->id);
1725 candidate_reachable.ClearAllBits();
1726 size_t num_reachable = 0u;
1727 while (!tmp_stack->empty()) {
1728 BasicBlockId current_id = tmp_stack->back();
1729 tmp_stack->pop_back();
1730 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1731 DCHECK(current_bb != nullptr);
1732 ChildBlockIterator child_iter(current_bb, mir_graph);
1733 BasicBlock* child_bb = child_iter.Next();
1734 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1735 DCHECK(!child_bb->hidden);
1736 if (child_bb->visited || // Already processed, or
1737 (current_loop != nullptr && // outside current loop.
1738 !current_loop->IsBitSet(child_bb->id))) {
1739 continue;
1740 }
1741 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1742 candidate_reachable.SetBit(child_bb->id);
1743 tmp_stack->push_back(child_bb->id);
1744 num_reachable += 1u;
1745 }
1746 }
1747 }
1748 if (fall_back_num_reachable < num_reachable) {
1749 fall_back_num_reachable = num_reachable;
1750 fall_back = candidate;
1751 }
1752 }
1753 return fall_back;
1754}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001755
Vladimir Marko55fff042014-07-10 12:42:52 +01001756// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1757static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1758 ArenaBitVector* reachable,
1759 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1760 // NOTE: Loop heads indicated by the "visited" flag.
1761 DCHECK(tmp_stack->empty());
1762 reachable->ClearAllBits();
1763 tmp_stack->push_back(bb_id);
1764 while (!tmp_stack->empty()) {
1765 BasicBlockId current_id = tmp_stack->back();
1766 tmp_stack->pop_back();
1767 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1768 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001769 for (BasicBlockId pred_id : current_bb->predecessors) {
1770 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1771 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001772 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1773 reachable->SetBit(pred_bb->id);
1774 tmp_stack->push_back(pred_bb->id);
1775 }
1776 }
1777 }
1778}
1779
1780void MIRGraph::ComputeTopologicalSortOrder() {
1781 ScopedArenaAllocator allocator(&cu_->arena_stack);
1782 unsigned int num_blocks = GetNumBlocks();
1783
1784 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1785 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1786 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1787 size_t max_nested_loops = 0u;
1788 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1789 loop_exit_blocks.ClearAllBits();
1790
1791 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001792 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001793 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001794 if (bb->hidden == true) {
1795 continue;
1796 }
1797
Vladimir Marko55fff042014-07-10 12:42:52 +01001798 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001799
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001800 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001801 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001802 q.push(bb);
1803 }
1804 }
1805
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001806 // Clear the topological order arrays.
1807 topological_order_.clear();
1808 topological_order_.reserve(num_blocks);
1809 topological_order_loop_ends_.clear();
1810 topological_order_loop_ends_.resize(num_blocks, 0u);
1811 topological_order_indexes_.clear();
1812 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001813
1814 // Mark all blocks as unvisited.
1815 ClearAllVisitedFlags();
1816
1817 // For loop heads, keep track from which blocks they are reachable not going through other
1818 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1819 // in this set go into the loop body, the other children are jumping over the loop.
1820 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1821 loop_head_reachable_from.resize(num_blocks, nullptr);
1822 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1823 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1824
1825 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001826 BasicBlock* bb = nullptr;
1827 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001828 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001829 // Get top.
1830 bb = q.front();
1831 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001832 if (bb->visited) {
1833 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1834 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001835 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1836 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001837 DCHECK_EQ(loop_head_stack.back(), bb->id);
1838 loop_head_stack.pop_back();
1839 ArenaBitVector* reachable =
1840 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1841 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1842 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1843 q.push(GetBasicBlock(candidate_id));
1844 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1845 // so clearing the bit has no effect on the iterator.
1846 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001847 }
1848 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001849 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001850 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001851 } else {
1852 // Find the new loop head.
1853 AllNodesIterator iter(this);
1854 while (true) {
1855 BasicBlock* candidate = iter.Next();
1856 if (candidate == nullptr) {
1857 // We did not find a true loop head, fall back to a reachable block in any loop.
1858 ArenaBitVector* current_loop =
1859 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1860 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1861 &allocator, &tmp_stack);
1862 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1863 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1864 LOG(INFO) << "Topological sort order: Using fall-back in "
1865 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1866 << " @0x" << std::hex << bb->start_offset
1867 << ", num_blocks = " << std::dec << num_blocks;
1868 }
1869 break;
1870 }
1871 if (candidate->hidden || // Hidden, or
1872 candidate->visited || // already processed, or
1873 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1874 (!loop_head_stack.empty() && // outside current loop.
1875 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1876 continue;
1877 }
1878
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001879 for (BasicBlockId pred_id : candidate->predecessors) {
1880 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1881 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001882 if (pred_bb != candidate && !pred_bb->visited &&
1883 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001884 candidate = nullptr; // Set candidate to null to indicate failure.
1885 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001886 }
1887 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001888 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001889 bb = candidate;
1890 break;
1891 }
1892 }
1893 // Compute blocks from which the loop head is reachable and process those blocks first.
1894 ArenaBitVector* reachable =
1895 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1896 loop_head_reachable_from[bb->id] = reachable;
1897 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1898 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1899 loop_head_stack.push_back(bb->id);
1900 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001901 }
1902
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001903 DCHECK_EQ(bb->hidden, false);
1904 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001905 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001906
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001907 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001908 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1909 topological_order_indexes_[bb->id] = idx;
1910 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001911
Vladimir Marko55fff042014-07-10 12:42:52 +01001912 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001913 ChildBlockIterator succIter(bb, this);
1914 BasicBlock* successor = succIter.Next();
1915 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001916 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001917 continue;
1918 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001919
Vladimir Marko55fff042014-07-10 12:42:52 +01001920 // One more predecessor was visited.
1921 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001922 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001923 if (loop_head_stack.empty() ||
1924 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1925 q.push(successor);
1926 } else {
1927 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1928 loop_exit_blocks.SetBit(successor->id);
1929 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001930 }
1931 }
1932 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001933
1934 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001935 topological_order_loop_head_stack_.clear();
1936 topological_order_loop_head_stack_.reserve(max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001937}
1938
1939bool BasicBlock::IsExceptionBlock() const {
1940 if (block_type == kExceptionHandling) {
1941 return true;
1942 }
1943 return false;
1944}
1945
Wei Jin04f4d8a2014-05-29 18:04:29 -07001946bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1947 BasicBlock* target = GetBasicBlock(target_id);
1948
1949 if (source == nullptr || target == nullptr)
1950 return false;
1951
1952 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001953 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1954 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001955 if (bb == source)
1956 return true; // The block has been inserted by a suspend check before.
1957 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1958 return true;
1959 }
1960
1961 return false;
1962}
1963
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001964ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1965 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1966 visited_taken_(false), have_successors_(false) {
1967 // Check if we actually do have successors.
1968 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1969 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001970 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001971 }
1972}
1973
1974BasicBlock* ChildBlockIterator::Next() {
1975 // We check if we have a basic block. If we don't we cannot get next child.
1976 if (basic_block_ == nullptr) {
1977 return nullptr;
1978 }
1979
1980 // If we haven't visited fallthrough, return that.
1981 if (visited_fallthrough_ == false) {
1982 visited_fallthrough_ = true;
1983
1984 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1985 if (result != nullptr) {
1986 return result;
1987 }
1988 }
1989
1990 // If we haven't visited taken, return that.
1991 if (visited_taken_ == false) {
1992 visited_taken_ = true;
1993
1994 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1995 if (result != nullptr) {
1996 return result;
1997 }
1998 }
1999
2000 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2001 if (have_successors_ == true) {
2002 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002003 auto end = basic_block_->successor_blocks.cend();
2004 while (successor_iter_ != end) {
2005 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2006 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002007 // If block was replaced by zero block, take next one.
2008 if (successor_block_info->block != NullBasicBlockId) {
2009 return mir_graph_->GetBasicBlock(successor_block_info->block);
2010 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002011 }
2012 }
2013
2014 // We do not have anything.
2015 return nullptr;
2016}
2017
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002018BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2019 MIRGraph* mir_graph = c_unit->mir_graph.get();
2020 return Copy(mir_graph);
2021}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002022
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002023BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2024 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002025
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002026 // We don't do a memcpy style copy here because it would lead to a lot of things
2027 // to clean up. Let us do it by hand instead.
2028 // Copy in taken and fallthrough.
2029 result_bb->fall_through = fall_through;
2030 result_bb->taken = taken;
2031
2032 // Copy successor links if needed.
2033 ArenaAllocator* arena = mir_graph->GetArena();
2034
2035 result_bb->successor_block_list_type = successor_block_list_type;
2036 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002037 result_bb->successor_blocks.reserve(successor_blocks.size());
2038 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2039 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2040 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002041 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002042 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002043 }
2044 }
2045
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002046 // Copy offset, method.
2047 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002048
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002049 // Now copy instructions.
2050 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2051 // Get a copy first.
2052 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002053
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002054 // Append it.
2055 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002056 }
2057
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002058 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002059}
2060
2061MIR* MIR::Copy(MIRGraph* mir_graph) {
2062 MIR* res = mir_graph->NewMIR();
2063 *res = *this;
2064
2065 // Remove links
2066 res->next = nullptr;
2067 res->bb = NullBasicBlockId;
2068 res->ssa_rep = nullptr;
2069
2070 return res;
2071}
2072
2073MIR* MIR::Copy(CompilationUnit* c_unit) {
2074 return Copy(c_unit->mir_graph.get());
2075}
2076
2077uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2078 // Default result.
2079 int res = 0;
2080
2081 // We are basically setting the iputs to their igets counterparts.
2082 switch (opcode) {
2083 case Instruction::IPUT:
2084 case Instruction::IPUT_OBJECT:
2085 case Instruction::IPUT_BOOLEAN:
2086 case Instruction::IPUT_BYTE:
2087 case Instruction::IPUT_CHAR:
2088 case Instruction::IPUT_SHORT:
2089 case Instruction::IPUT_QUICK:
2090 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002091 case Instruction::IPUT_BOOLEAN_QUICK:
2092 case Instruction::IPUT_BYTE_QUICK:
2093 case Instruction::IPUT_CHAR_QUICK:
2094 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002095 case Instruction::APUT:
2096 case Instruction::APUT_OBJECT:
2097 case Instruction::APUT_BOOLEAN:
2098 case Instruction::APUT_BYTE:
2099 case Instruction::APUT_CHAR:
2100 case Instruction::APUT_SHORT:
2101 case Instruction::SPUT:
2102 case Instruction::SPUT_OBJECT:
2103 case Instruction::SPUT_BOOLEAN:
2104 case Instruction::SPUT_BYTE:
2105 case Instruction::SPUT_CHAR:
2106 case Instruction::SPUT_SHORT:
2107 // Skip the VR containing what to store.
2108 res = 1;
2109 break;
2110 case Instruction::IPUT_WIDE:
2111 case Instruction::IPUT_WIDE_QUICK:
2112 case Instruction::APUT_WIDE:
2113 case Instruction::SPUT_WIDE:
2114 // Skip the two VRs containing what to store.
2115 res = 2;
2116 break;
2117 default:
2118 // Do nothing in the general case.
2119 break;
2120 }
2121
2122 return res;
2123}
2124
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002125/**
2126 * @brief Given a decoded instruction, it checks whether the instruction
2127 * sets a constant and if it does, more information is provided about the
2128 * constant being set.
2129 * @param ptr_value pointer to a 64-bit holder for the constant.
2130 * @param wide Updated by function whether a wide constant is being set by bytecode.
2131 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2132 */
2133bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2134 bool sets_const = true;
2135 int64_t value = vB;
2136
2137 DCHECK(ptr_value != nullptr);
2138 DCHECK(wide != nullptr);
2139
2140 switch (opcode) {
2141 case Instruction::CONST_4:
2142 case Instruction::CONST_16:
2143 case Instruction::CONST:
2144 *wide = false;
2145 value <<= 32; // In order to get the sign extend.
2146 value >>= 32;
2147 break;
2148 case Instruction::CONST_HIGH16:
2149 *wide = false;
2150 value <<= 48; // In order to get the sign extend.
2151 value >>= 32;
2152 break;
2153 case Instruction::CONST_WIDE_16:
2154 case Instruction::CONST_WIDE_32:
2155 *wide = true;
2156 value <<= 32; // In order to get the sign extend.
2157 value >>= 32;
2158 break;
2159 case Instruction::CONST_WIDE:
2160 *wide = true;
2161 value = vB_wide;
2162 break;
2163 case Instruction::CONST_WIDE_HIGH16:
2164 *wide = true;
2165 value <<= 48; // In order to get the sign extend.
2166 break;
2167 default:
2168 sets_const = false;
2169 break;
2170 }
2171
2172 if (sets_const) {
2173 *ptr_value = value;
2174 }
2175
2176 return sets_const;
2177}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002178
2179void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2180 // Reset flags for all MIRs in bb.
2181 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2182 mir->optimization_flags &= (~reset_flags);
2183 }
2184}
2185
2186void BasicBlock::Hide(CompilationUnit* c_unit) {
2187 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2188 block_type = kDalvikByteCode;
2189
2190 // Mark it as hidden.
2191 hidden = true;
2192
2193 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2194 // are updated to know that they no longer have a parent.
2195 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2196 mir->bb = NullBasicBlockId;
2197 }
2198 first_mir_insn = nullptr;
2199 last_mir_insn = nullptr;
2200
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002201 MIRGraph* mir_graph = c_unit->mir_graph.get();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002202 for (BasicBlockId pred_id : predecessors) {
2203 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2204 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002205
2206 // Sadly we have to go through the children by hand here.
2207 pred_bb->ReplaceChild(id, NullBasicBlockId);
2208 }
2209
2210 // Iterate through children of bb we are hiding.
2211 ChildBlockIterator successorChildIter(this, mir_graph);
2212
2213 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002214 // Erase this predecessor from child.
2215 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002216 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002217
2218 // Remove link to children.
2219 taken = NullBasicBlockId;
2220 fall_through = NullBasicBlockId;
2221 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002222}
2223
2224bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2225 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2226 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2227 // then it is not live out of this BB.
2228 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2229
2230 int last_ssa_reg = -1;
2231
2232 // Walk through the MIRs backwards.
2233 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2234 // Get ssa rep.
2235 SSARepresentation *ssa_rep = mir->ssa_rep;
2236
2237 // Go through the defines for this MIR.
2238 for (int i = 0; i < ssa_rep->num_defs; i++) {
2239 DCHECK(ssa_rep->defs != nullptr);
2240
2241 // Get the ssa reg.
2242 int def_ssa_reg = ssa_rep->defs[i];
2243
2244 // Get dalvik reg.
2245 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2246
2247 // Compare dalvik regs.
2248 if (dalvik_reg == def_dalvik_reg) {
2249 // We found a def of the register that we are being asked about.
2250 // Remember it.
2251 last_ssa_reg = def_ssa_reg;
2252 }
2253 }
2254 }
2255
2256 if (last_ssa_reg == -1) {
2257 // If we get to this point we couldn't find a define of register user asked about.
2258 // Let's assume the user knows what he's doing so we can be safe and say that if we
2259 // couldn't find a def, it is live out.
2260 return true;
2261 }
2262
2263 // If it is not -1, we found a match, is it ssa_reg?
2264 return (ssa_reg == last_ssa_reg);
2265}
2266
2267bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2268 // We need to check taken, fall_through, and successor_blocks to replace.
2269 bool found = false;
2270 if (taken == old_bb) {
2271 taken = new_bb;
2272 found = true;
2273 }
2274
2275 if (fall_through == old_bb) {
2276 fall_through = new_bb;
2277 found = true;
2278 }
2279
2280 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002281 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002282 if (successor_block_info->block == old_bb) {
2283 successor_block_info->block = new_bb;
2284 found = true;
2285 }
2286 }
2287 }
2288
2289 return found;
2290}
2291
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002292void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2293 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2294 DCHECK(pos != predecessors.end());
2295 predecessors.erase(pos);
2296}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002297
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002298void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2299 DCHECK_NE(new_pred, NullBasicBlockId);
2300 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2301 if (pos != predecessors.end()) {
2302 *pos = new_pred;
2303 } else {
2304 // If not found, add it.
2305 predecessors.push_back(new_pred);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002306 }
2307}
2308
2309// Create a new basic block with block_id as num_blocks_ that is
2310// post-incremented.
2311BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2312 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002313 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002314 return res;
2315}
2316
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002317void MIRGraph::CalculateBasicBlockInformation() {
2318 PassDriverMEPostOpt driver(cu_);
2319 driver.Launch();
2320}
2321
2322void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002323 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002324}
2325
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002326int MIR::DecodedInstruction::FlagsOf() const {
2327 // Calculate new index.
2328 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2329
2330 // Check if it is an extended or not.
2331 if (idx < 0) {
2332 return Instruction::FlagsOf(opcode);
2333 }
2334
2335 // For extended, we use a switch.
2336 switch (static_cast<int>(opcode)) {
2337 case kMirOpPhi:
2338 return Instruction::kContinue;
2339 case kMirOpCopy:
2340 return Instruction::kContinue;
2341 case kMirOpFusedCmplFloat:
2342 return Instruction::kContinue | Instruction::kBranch;
2343 case kMirOpFusedCmpgFloat:
2344 return Instruction::kContinue | Instruction::kBranch;
2345 case kMirOpFusedCmplDouble:
2346 return Instruction::kContinue | Instruction::kBranch;
2347 case kMirOpFusedCmpgDouble:
2348 return Instruction::kContinue | Instruction::kBranch;
2349 case kMirOpFusedCmpLong:
2350 return Instruction::kContinue | Instruction::kBranch;
2351 case kMirOpNop:
2352 return Instruction::kContinue;
2353 case kMirOpNullCheck:
2354 return Instruction::kContinue | Instruction::kThrow;
2355 case kMirOpRangeCheck:
2356 return Instruction::kContinue | Instruction::kThrow;
2357 case kMirOpDivZeroCheck:
2358 return Instruction::kContinue | Instruction::kThrow;
2359 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002360 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002361 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002362 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002363 case kMirOpSelect:
2364 return Instruction::kContinue;
2365 case kMirOpConstVector:
2366 return Instruction::kContinue;
2367 case kMirOpMoveVector:
2368 return Instruction::kContinue;
2369 case kMirOpPackedMultiply:
2370 return Instruction::kContinue;
2371 case kMirOpPackedAddition:
2372 return Instruction::kContinue;
2373 case kMirOpPackedSubtract:
2374 return Instruction::kContinue;
2375 case kMirOpPackedShiftLeft:
2376 return Instruction::kContinue;
2377 case kMirOpPackedSignedShiftRight:
2378 return Instruction::kContinue;
2379 case kMirOpPackedUnsignedShiftRight:
2380 return Instruction::kContinue;
2381 case kMirOpPackedAnd:
2382 return Instruction::kContinue;
2383 case kMirOpPackedOr:
2384 return Instruction::kContinue;
2385 case kMirOpPackedXor:
2386 return Instruction::kContinue;
2387 case kMirOpPackedAddReduce:
2388 return Instruction::kContinue;
2389 case kMirOpPackedReduce:
2390 return Instruction::kContinue;
2391 case kMirOpPackedSet:
2392 return Instruction::kContinue;
2393 case kMirOpReserveVectorRegisters:
2394 return Instruction::kContinue;
2395 case kMirOpReturnVectorRegisters:
2396 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002397 case kMirOpMemBarrier:
2398 return Instruction::kContinue;
2399 case kMirOpPackedArrayGet:
2400 return Instruction::kContinue | Instruction::kThrow;
2401 case kMirOpPackedArrayPut:
2402 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002403 default:
2404 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2405 return 0;
2406 }
2407}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002408} // namespace art