blob: 25c159f2a10725f9cf32f13bac1d3f5d75c7aa1b [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2011 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
Ian Rogerse77493c2014-08-20 15:08:45 -070017#include "base/bit_vector-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080018#include "base/logging.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080019#include "base/scoped_arena_containers.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070020#include "dataflow_iterator-inl.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080021#include "dex/verified_method.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080022#include "dex_flags.h"
23#include "driver/compiler_driver.h"
24#include "driver/dex_compilation_unit.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010025#include "global_value_numbering.h"
Vladimir Marko7a01dc22015-01-02 17:00:44 +000026#include "gvn_dead_code_elimination.h"
buzbee311ca162013-02-28 15:56:43 -080027#include "local_value_numbering.h"
Vladimir Markoaf6925b2014-10-31 16:37:32 +000028#include "mir_field_info.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080029#include "mirror/string.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070030#include "quick/dex_file_method_inliner.h"
31#include "quick/dex_file_to_method_inliner_map.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080033#include "type_inference.h"
buzbee311ca162013-02-28 15:56:43 -080034
35namespace art {
36
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070037static unsigned int Predecessors(BasicBlock* bb) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +010038 return bb->predecessors.size();
buzbee311ca162013-02-28 15:56:43 -080039}
40
41/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070042void MIRGraph::SetConstant(int32_t ssa_reg, int32_t value) {
buzbee862a7602013-04-05 10:58:54 -070043 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080044 constant_values_[ssa_reg] = value;
Vladimir Marko066f9e42015-01-16 16:04:43 +000045 reg_location_[ssa_reg].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080046}
47
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070048void MIRGraph::SetConstantWide(int32_t ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070049 is_constant_v_->SetBit(ssa_reg);
Serguei Katkov597da1f2014-07-15 17:25:46 +070050 is_constant_v_->SetBit(ssa_reg + 1);
buzbee311ca162013-02-28 15:56:43 -080051 constant_values_[ssa_reg] = Low32Bits(value);
52 constant_values_[ssa_reg + 1] = High32Bits(value);
Vladimir Marko066f9e42015-01-16 16:04:43 +000053 reg_location_[ssa_reg].is_const = true;
54 reg_location_[ssa_reg + 1].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080055}
56
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -080057void MIRGraph::DoConstantPropagation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080058 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080059
Mathieu Chartier2cebb242015-04-21 16:50:40 -070060 for (mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070061 // Skip pass if BB has MIR without SSA representation.
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070062 if (mir->ssa_rep == nullptr) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070063 return;
64 }
65
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070066 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -080067
Ian Rogers29a26482014-05-02 15:27:29 -070068 MIR::DecodedInstruction* d_insn = &mir->dalvikInsn;
buzbee311ca162013-02-28 15:56:43 -080069
70 if (!(df_attributes & DF_HAS_DEFS)) continue;
71
72 /* Handle instructions that set up constants directly */
73 if (df_attributes & DF_SETS_CONST) {
74 if (df_attributes & DF_DA) {
75 int32_t vB = static_cast<int32_t>(d_insn->vB);
76 switch (d_insn->opcode) {
77 case Instruction::CONST_4:
78 case Instruction::CONST_16:
79 case Instruction::CONST:
80 SetConstant(mir->ssa_rep->defs[0], vB);
81 break;
82 case Instruction::CONST_HIGH16:
83 SetConstant(mir->ssa_rep->defs[0], vB << 16);
84 break;
85 case Instruction::CONST_WIDE_16:
86 case Instruction::CONST_WIDE_32:
87 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
88 break;
89 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070090 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080091 break;
92 case Instruction::CONST_WIDE_HIGH16:
93 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
94 break;
95 default:
96 break;
97 }
98 }
99 /* Handle instructions that set up constants directly */
100 } else if (df_attributes & DF_IS_MOVE) {
101 int i;
102
103 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -0700104 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -0800105 }
106 /* Move a register holding a constant to another register */
107 if (i == mir->ssa_rep->num_uses) {
108 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
109 if (df_attributes & DF_A_WIDE) {
110 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
111 }
112 }
113 }
114 }
115 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -0800116}
117
buzbee311ca162013-02-28 15:56:43 -0800118/* Advance to next strictly dominated MIR node in an extended basic block */
buzbee0d829482013-10-11 15:24:55 -0700119MIR* MIRGraph::AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800120 BasicBlock* bb = *p_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700121 if (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800122 mir = mir->next;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700123 while (mir == nullptr) {
buzbee0d829482013-10-11 15:24:55 -0700124 bb = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700125 if ((bb == nullptr) || Predecessors(bb) != 1) {
Serguei Katkovea392162015-01-29 17:08:05 +0600126 // mir is null and we cannot proceed further.
127 break;
buzbee311ca162013-02-28 15:56:43 -0800128 } else {
Serguei Katkovea392162015-01-29 17:08:05 +0600129 *p_bb = bb;
130 mir = bb->first_mir_insn;
buzbee311ca162013-02-28 15:56:43 -0800131 }
132 }
133 }
134 return mir;
135}
136
137/*
138 * To be used at an invoke mir. If the logically next mir node represents
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700139 * a move-result, return it. Else, return nullptr. If a move-result exists,
buzbee311ca162013-02-28 15:56:43 -0800140 * it is required to immediately follow the invoke with no intervening
141 * opcodes or incoming arcs. However, if the result of the invoke is not
142 * used, a move-result may not be present.
143 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700144MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800145 BasicBlock* tbb = bb;
146 mir = AdvanceMIR(&tbb, mir);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700147 while (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800148 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
149 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
150 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
151 break;
152 }
153 // Keep going if pseudo op, otherwise terminate
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700154 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800155 mir = AdvanceMIR(&tbb, mir);
buzbee35ba7f32014-05-31 08:59:01 -0700156 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700157 mir = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800158 }
159 }
160 return mir;
161}
162
buzbee0d829482013-10-11 15:24:55 -0700163BasicBlock* MIRGraph::NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800164 if (bb->block_type == kDead) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700165 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800166 }
167 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
168 || (bb->block_type == kExitBlock));
buzbee0d829482013-10-11 15:24:55 -0700169 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
170 BasicBlock* bb_fall_through = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700171 if (((bb_fall_through == nullptr) && (bb_taken != nullptr)) &&
buzbee0d829482013-10-11 15:24:55 -0700172 ((bb_taken->block_type == kDalvikByteCode) || (bb_taken->block_type == kExitBlock))) {
buzbeecbcfaf32013-08-19 07:37:40 -0700173 // Follow simple unconditional branches.
buzbee0d829482013-10-11 15:24:55 -0700174 bb = bb_taken;
buzbeecbcfaf32013-08-19 07:37:40 -0700175 } else {
176 // Follow simple fallthrough
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700177 bb = (bb_taken != nullptr) ? nullptr : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700178 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700179 if (bb == nullptr || (Predecessors(bb) != 1)) {
180 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800181 }
182 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
183 return bb;
184}
185
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700186static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800188 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
189 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
190 if (mir->ssa_rep->uses[i] == ssa_name) {
191 return mir;
192 }
193 }
194 }
195 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700196 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800197}
198
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700199static SelectInstructionKind SelectKind(MIR* mir) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700200 // Work with the case when mir is null.
Chao-ying Fu8ac41af2014-10-01 16:53:04 -0700201 if (mir == nullptr) {
202 return kSelectNone;
203 }
buzbee311ca162013-02-28 15:56:43 -0800204 switch (mir->dalvikInsn.opcode) {
205 case Instruction::MOVE:
206 case Instruction::MOVE_OBJECT:
207 case Instruction::MOVE_16:
208 case Instruction::MOVE_OBJECT_16:
209 case Instruction::MOVE_FROM16:
210 case Instruction::MOVE_OBJECT_FROM16:
211 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700212 case Instruction::CONST:
213 case Instruction::CONST_4:
214 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800215 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700216 case Instruction::GOTO:
217 case Instruction::GOTO_16:
218 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800219 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700220 default:
221 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800222 }
buzbee311ca162013-02-28 15:56:43 -0800223}
224
Vladimir Markoa1a70742014-03-03 10:28:05 +0000225static constexpr ConditionCode kIfCcZConditionCodes[] = {
226 kCondEq, kCondNe, kCondLt, kCondGe, kCondGt, kCondLe
227};
228
Andreas Gampe785d2f22014-11-03 22:57:30 -0800229static_assert(arraysize(kIfCcZConditionCodes) == Instruction::IF_LEZ - Instruction::IF_EQZ + 1,
230 "if_ccz_ccodes_size1");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000231
Vladimir Markoa1a70742014-03-03 10:28:05 +0000232static constexpr ConditionCode ConditionCodeForIfCcZ(Instruction::Code opcode) {
233 return kIfCcZConditionCodes[opcode - Instruction::IF_EQZ];
234}
235
Andreas Gampe785d2f22014-11-03 22:57:30 -0800236static_assert(ConditionCodeForIfCcZ(Instruction::IF_EQZ) == kCondEq, "if_eqz ccode");
237static_assert(ConditionCodeForIfCcZ(Instruction::IF_NEZ) == kCondNe, "if_nez ccode");
238static_assert(ConditionCodeForIfCcZ(Instruction::IF_LTZ) == kCondLt, "if_ltz ccode");
239static_assert(ConditionCodeForIfCcZ(Instruction::IF_GEZ) == kCondGe, "if_gez ccode");
240static_assert(ConditionCodeForIfCcZ(Instruction::IF_GTZ) == kCondGt, "if_gtz ccode");
241static_assert(ConditionCodeForIfCcZ(Instruction::IF_LEZ) == kCondLe, "if_lez ccode");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000242
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700243int MIRGraph::GetSSAUseCount(int s_reg) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100244 DCHECK_LT(static_cast<size_t>(s_reg), ssa_subscripts_.size());
245 return raw_use_counts_[s_reg];
buzbee311ca162013-02-28 15:56:43 -0800246}
247
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700248size_t MIRGraph::GetNumBytesForSpecialTemps() const {
249 // This logic is written with assumption that Method* is only special temp.
250 DCHECK_EQ(max_available_special_compiler_temps_, 1u);
251 return sizeof(StackReference<mirror::ArtMethod>);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800252}
253
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700254size_t MIRGraph::GetNumAvailableVRTemps() {
255 // First take into account all temps reserved for backend.
256 if (max_available_non_special_compiler_temps_ < reserved_temps_for_backend_) {
257 return 0;
258 }
259
260 // Calculate remaining ME temps available.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700261 size_t remaining_me_temps = max_available_non_special_compiler_temps_ -
262 reserved_temps_for_backend_;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700263
264 if (num_non_special_compiler_temps_ >= remaining_me_temps) {
265 return 0;
266 } else {
267 return remaining_me_temps - num_non_special_compiler_temps_;
268 }
269}
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000270
271// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800272static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700273 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000274 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800275
276CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700277 // Once the compiler temps have been committed, new ones cannot be requested anymore.
278 DCHECK_EQ(compiler_temps_committed_, false);
279 // Make sure that reserved for BE set is sane.
280 DCHECK_LE(reserved_temps_for_backend_, max_available_non_special_compiler_temps_);
281
282 bool verbose = cu_->verbose;
283 const char* ct_type_str = nullptr;
284
285 if (verbose) {
286 switch (ct_type) {
287 case kCompilerTempBackend:
288 ct_type_str = "backend";
289 break;
290 case kCompilerTempSpecialMethodPtr:
291 ct_type_str = "method*";
292 break;
293 case kCompilerTempVR:
294 ct_type_str = "VR";
295 break;
296 default:
297 ct_type_str = "unknown";
298 break;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800299 }
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700300 LOG(INFO) << "CompilerTemps: A compiler temp of type " << ct_type_str << " that is "
301 << (wide ? "wide is being requested." : "not wide is being requested.");
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800302 }
303
304 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000305 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800306
307 // Create the type of temp requested. Special temps need special handling because
308 // they have a specific virtual register assignment.
309 if (ct_type == kCompilerTempSpecialMethodPtr) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700310 // This has a special location on stack which is 32-bit or 64-bit depending
311 // on mode. However, we don't want to overlap with non-special section
312 // and thus even for 64-bit, we allow only a non-wide temp to be requested.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800313 DCHECK_EQ(wide, false);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800314
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700315 // The vreg is always the first special temp for method ptr.
316 compiler_temp->v_reg = GetFirstSpecialTempVR();
317
318 } else if (ct_type == kCompilerTempBackend) {
319 requested_backend_temp_ = true;
320
321 // Make sure that we are not exceeding temps reserved for BE.
322 // Since VR temps cannot be requested once the BE temps are requested, we
323 // allow reservation of VR temps as well for BE. We
324 size_t available_temps = reserved_temps_for_backend_ + GetNumAvailableVRTemps();
Vladimir Markocc234812015-04-07 09:36:09 +0100325 size_t needed_temps = wide ? 2u : 1u;
326 if (available_temps < needed_temps) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700327 if (verbose) {
Vladimir Markocc234812015-04-07 09:36:09 +0100328 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
329 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700330 }
331 return nullptr;
332 }
333
334 // Update the remaining reserved temps since we have now used them.
335 // Note that the code below is actually subtracting to remove them from reserve
336 // once they have been claimed. It is careful to not go below zero.
Vladimir Markocc234812015-04-07 09:36:09 +0100337 reserved_temps_for_backend_ =
338 std::max(reserved_temps_for_backend_, needed_temps) - needed_temps;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700339
340 // The new non-special compiler temp must receive a unique v_reg.
341 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
342 num_non_special_compiler_temps_++;
343 } else if (ct_type == kCompilerTempVR) {
344 // Once we start giving out BE temps, we don't allow anymore ME temps to be requested.
345 // This is done in order to prevent problems with ssa since these structures are allocated
346 // and managed by the ME.
347 DCHECK_EQ(requested_backend_temp_, false);
348
349 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
350 size_t available_temps = GetNumAvailableVRTemps();
351 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
352 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700353 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
354 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700355 }
356 return nullptr;
357 }
358
359 // The new non-special compiler temp must receive a unique v_reg.
360 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
361 num_non_special_compiler_temps_++;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800362 } else {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700363 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << ct_type_str << ".";
364 }
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800365
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700366 // We allocate an sreg as well to make developer life easier.
367 // However, if this is requested from an ME pass that will recalculate ssa afterwards,
368 // this sreg is no longer valid. The caller should be aware of this.
369 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
370
371 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700372 LOG(INFO) << "CompilerTemps: New temp of type " << ct_type_str << " with v"
373 << compiler_temp->v_reg << " and s" << compiler_temp->s_reg_low << " has been created.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700374 }
375
376 if (wide) {
377 // Only non-special temps are handled as wide for now.
378 // Note that the number of non special temps is incremented below.
379 DCHECK(ct_type == kCompilerTempBackend || ct_type == kCompilerTempVR);
380
381 // Ensure that the two registers are consecutive.
382 int ssa_reg_low = compiler_temp->s_reg_low;
383 int ssa_reg_high = AddNewSReg(compiler_temp->v_reg + 1);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800384 num_non_special_compiler_temps_++;
385
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700386 if (verbose) {
387 LOG(INFO) << "CompilerTemps: The wide part of temp of type " << ct_type_str << " is v"
388 << compiler_temp->v_reg + 1 << " and s" << ssa_reg_high << ".";
389 }
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700390
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700391 if (reg_location_ != nullptr) {
392 reg_location_[ssa_reg_high] = temp_loc;
393 reg_location_[ssa_reg_high].high_word = true;
394 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
395 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800396 }
397 }
398
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700399 // If the register locations have already been allocated, add the information
400 // about the temp. We will not overflow because they have been initialized
401 // to support the maximum number of temps. For ME temps that have multiple
402 // ssa versions, the structures below will be expanded on the post pass cleanup.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800403 if (reg_location_ != nullptr) {
404 int ssa_reg_low = compiler_temp->s_reg_low;
405 reg_location_[ssa_reg_low] = temp_loc;
406 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
407 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800408 }
409
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800410 return compiler_temp;
411}
buzbee311ca162013-02-28 15:56:43 -0800412
Vladimir Markocc234812015-04-07 09:36:09 +0100413void MIRGraph::RemoveLastCompilerTemp(CompilerTempType ct_type, bool wide, CompilerTemp* temp) {
414 // Once the compiler temps have been committed, it's too late for any modifications.
415 DCHECK_EQ(compiler_temps_committed_, false);
416
417 size_t used_temps = wide ? 2u : 1u;
418
419 if (ct_type == kCompilerTempBackend) {
420 DCHECK(requested_backend_temp_);
421
422 // Make the temps available to backend again.
423 reserved_temps_for_backend_ += used_temps;
424 } else if (ct_type == kCompilerTempVR) {
425 DCHECK(!requested_backend_temp_);
426 } else {
427 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << static_cast<int>(ct_type);
428 }
429
430 // Reduce the number of non-special compiler temps.
431 DCHECK_LE(used_temps, num_non_special_compiler_temps_);
432 num_non_special_compiler_temps_ -= used_temps;
433
434 // Check that this was really the last temp.
435 DCHECK_EQ(static_cast<size_t>(temp->v_reg),
436 GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_);
437
438 if (cu_->verbose) {
439 LOG(INFO) << "Last temporary has been removed.";
440 }
441}
442
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000443static bool EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
444 bool is_taken;
445 switch (opcode) {
446 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
447 case Instruction::IF_NE: is_taken = (src1 != src2); break;
448 case Instruction::IF_LT: is_taken = (src1 < src2); break;
449 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
450 case Instruction::IF_GT: is_taken = (src1 > src2); break;
451 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
452 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
453 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
454 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
455 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
456 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
457 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
458 default:
459 LOG(FATAL) << "Unexpected opcode " << opcode;
460 UNREACHABLE();
461 }
462 return is_taken;
463}
464
buzbee311ca162013-02-28 15:56:43 -0800465/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700466bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800467 if (bb->block_type == kDead) {
468 return true;
469 }
Ningsheng Jiana262f772014-11-25 16:48:07 +0800470 // Currently multiply-accumulate backend supports are only available on arm32 and arm64.
471 if (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2) {
472 MultiplyAddOpt(bb);
473 }
Vladimir Marko415ac882014-09-30 18:09:14 +0100474 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kLocalValueNumbering)) == 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100475 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100476 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700477 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800478 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100479 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko415ac882014-09-30 18:09:14 +0100480 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get(),
481 GlobalValueNumbering::kModeLvn));
Vladimir Markob19955d2014-07-29 12:04:10 +0100482 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
483 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800484 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700485 while (bb != nullptr) {
486 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800487 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800488 if (use_lvn) {
489 local_valnum->GetValueNumber(mir);
490 }
buzbee311ca162013-02-28 15:56:43 -0800491 // Look for interesting opcodes, skip otherwise
492 Instruction::Code opcode = mir->dalvikInsn.opcode;
493 switch (opcode) {
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000494 case Instruction::IF_EQ:
495 case Instruction::IF_NE:
496 case Instruction::IF_LT:
497 case Instruction::IF_GE:
498 case Instruction::IF_GT:
499 case Instruction::IF_LE:
500 if (!IsConst(mir->ssa_rep->uses[1])) {
501 break;
502 }
503 FALLTHROUGH_INTENDED;
504 case Instruction::IF_EQZ:
505 case Instruction::IF_NEZ:
506 case Instruction::IF_LTZ:
507 case Instruction::IF_GEZ:
508 case Instruction::IF_GTZ:
509 case Instruction::IF_LEZ:
510 // Result known at compile time?
511 if (IsConst(mir->ssa_rep->uses[0])) {
512 int32_t rhs = (mir->ssa_rep->num_uses == 2) ? ConstantValue(mir->ssa_rep->uses[1]) : 0;
513 bool is_taken = EvaluateBranch(opcode, ConstantValue(mir->ssa_rep->uses[0]), rhs);
514 BasicBlockId edge_to_kill = is_taken ? bb->fall_through : bb->taken;
515 if (is_taken) {
516 // Replace with GOTO.
517 bb->fall_through = NullBasicBlockId;
518 mir->dalvikInsn.opcode = Instruction::GOTO;
519 mir->dalvikInsn.vA =
520 IsInstructionIfCc(opcode) ? mir->dalvikInsn.vC : mir->dalvikInsn.vB;
521 } else {
522 // Make NOP.
523 bb->taken = NullBasicBlockId;
524 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
525 }
526 mir->ssa_rep->num_uses = 0;
527 BasicBlock* successor_to_unlink = GetBasicBlock(edge_to_kill);
528 successor_to_unlink->ErasePredecessor(bb->id);
Vladimir Marko341e4252014-12-19 10:29:51 +0000529 // We have changed the graph structure.
530 dfs_orders_up_to_date_ = false;
531 domination_up_to_date_ = false;
532 topological_order_up_to_date_ = false;
533 // Keep MIR SSA rep, the worst that can happen is a Phi with just 1 input.
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000534 }
535 break;
buzbee311ca162013-02-28 15:56:43 -0800536 case Instruction::CMPL_FLOAT:
537 case Instruction::CMPL_DOUBLE:
538 case Instruction::CMPG_FLOAT:
539 case Instruction::CMPG_DOUBLE:
540 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700541 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800542 // Bitcode doesn't allow this optimization.
543 break;
544 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700545 if (mir->next != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800546 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800547 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700548 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800549 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
550 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000551 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700552 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800553 case Instruction::CMPL_FLOAT:
554 mir_next->dalvikInsn.opcode =
555 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
556 break;
557 case Instruction::CMPL_DOUBLE:
558 mir_next->dalvikInsn.opcode =
559 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
560 break;
561 case Instruction::CMPG_FLOAT:
562 mir_next->dalvikInsn.opcode =
563 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
564 break;
565 case Instruction::CMPG_DOUBLE:
566 mir_next->dalvikInsn.opcode =
567 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
568 break;
569 case Instruction::CMP_LONG:
570 mir_next->dalvikInsn.opcode =
571 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
572 break;
573 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
574 }
575 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Zheng Xub218c852014-12-08 18:18:01 +0800576 // Clear use count of temp VR.
577 use_counts_[mir->ssa_rep->defs[0]] = 0;
578 raw_use_counts_[mir->ssa_rep->defs[0]] = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700579 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800580 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
581 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
buzbee311ca162013-02-28 15:56:43 -0800582 mir_next->ssa_rep->num_defs = 0;
583 mir->ssa_rep->num_uses = 0;
584 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700585 // Copy in the decoded instruction information for potential SSA re-creation.
586 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
587 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800588 }
589 }
590 break;
buzbee311ca162013-02-28 15:56:43 -0800591 default:
592 break;
593 }
594 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800595 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800596 // TUNING: expand to support IF_xx compare & branches
Elliott Hughes956af0f2014-12-11 14:34:28 -0800597 if ((cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100598 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000599 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700600 BasicBlock* ft = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700601 DCHECK(ft != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700602 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
603 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800604
buzbee0d829482013-10-11 15:24:55 -0700605 BasicBlock* tk = GetBasicBlock(bb->taken);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700606 DCHECK(tk != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700607 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
608 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800609
610 /*
611 * In the select pattern, the taken edge goes to a block that unconditionally
612 * transfers to the rejoin block and the fall_though edge goes to a block that
613 * unconditionally falls through to the rejoin block.
614 */
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700615 if ((tk_ft == nullptr) && (ft_tk == nullptr) && (tk_tk == ft_ft) &&
buzbee311ca162013-02-28 15:56:43 -0800616 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
617 /*
Vladimir Marko8b858e12014-11-27 14:52:37 +0000618 * Okay - we have the basic diamond shape.
buzbee311ca162013-02-28 15:56:43 -0800619 */
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100620
621 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800622 // Are the block bodies something we can handle?
623 if ((ft->first_mir_insn == ft->last_mir_insn) &&
624 (tk->first_mir_insn != tk->last_mir_insn) &&
625 (tk->first_mir_insn->next == tk->last_mir_insn) &&
626 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
627 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
628 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
629 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
630 // Almost there. Are the instructions targeting the same vreg?
631 MIR* if_true = tk->first_mir_insn;
632 MIR* if_false = ft->first_mir_insn;
633 // It's possible that the target of the select isn't used - skip those (rare) cases.
634 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700635 if ((phi != nullptr) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
buzbee311ca162013-02-28 15:56:43 -0800636 /*
637 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
638 * Phi node in the merge block and delete it (while using the SSA name
639 * of the merge as the target of the SELECT. Delete both taken and
640 * fallthrough blocks, and set fallthrough to merge block.
641 * NOTE: not updating other dataflow info (no longer used at this point).
642 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
643 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000644 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800645 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
646 bool const_form = (SelectKind(if_true) == kSelectConst);
647 if ((SelectKind(if_true) == kSelectMove)) {
648 if (IsConst(if_true->ssa_rep->uses[0]) &&
649 IsConst(if_false->ssa_rep->uses[0])) {
650 const_form = true;
651 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
652 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
653 }
654 }
655 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800656 /*
657 * TODO: If both constants are the same value, then instead of generating
658 * a select, we should simply generate a const bytecode. This should be
659 * considered after inlining which can lead to CFG of this form.
660 */
buzbee311ca162013-02-28 15:56:43 -0800661 // "true" set val in vB
662 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
663 // "false" set val in vC
664 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
665 } else {
666 DCHECK_EQ(SelectKind(if_true), kSelectMove);
667 DCHECK_EQ(SelectKind(if_false), kSelectMove);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000668 int32_t* src_ssa = arena_->AllocArray<int32_t>(3, kArenaAllocDFInfo);
buzbee311ca162013-02-28 15:56:43 -0800669 src_ssa[0] = mir->ssa_rep->uses[0];
670 src_ssa[1] = if_true->ssa_rep->uses[0];
671 src_ssa[2] = if_false->ssa_rep->uses[0];
672 mir->ssa_rep->uses = src_ssa;
673 mir->ssa_rep->num_uses = 3;
674 }
Vladimir Markoc91df2d2015-04-23 09:29:21 +0000675 AllocateSSADefData(mir, 1);
buzbee311ca162013-02-28 15:56:43 -0800676 /*
677 * There is usually a Phi node in the join block for our two cases. If the
678 * Phi node only contains our two cases as input, we will use the result
679 * SSA name of the Phi node as our select result and delete the Phi. If
680 * the Phi node has more than two operands, we will arbitrarily use the SSA
Vladimir Marko341e4252014-12-19 10:29:51 +0000681 * name of the "false" path, delete the SSA name of the "true" path from the
buzbee311ca162013-02-28 15:56:43 -0800682 * Phi node (and fix up the incoming arc list).
683 */
684 if (phi->ssa_rep->num_uses == 2) {
685 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000686 // Rather than changing the Phi to kMirOpNop, remove it completely.
687 // This avoids leaving other Phis after kMirOpNop (i.e. a non-Phi) insn.
688 tk_tk->RemoveMIR(phi);
689 int dead_false_def = if_false->ssa_rep->defs[0];
690 raw_use_counts_[dead_false_def] = use_counts_[dead_false_def] = 0;
buzbee311ca162013-02-28 15:56:43 -0800691 } else {
Vladimir Marko341e4252014-12-19 10:29:51 +0000692 int live_def = if_false->ssa_rep->defs[0];
buzbee311ca162013-02-28 15:56:43 -0800693 mir->ssa_rep->defs[0] = live_def;
buzbee311ca162013-02-28 15:56:43 -0800694 }
Vladimir Marko341e4252014-12-19 10:29:51 +0000695 int dead_true_def = if_true->ssa_rep->defs[0];
696 raw_use_counts_[dead_true_def] = use_counts_[dead_true_def] = 0;
Vladimir Marko6e071832015-03-25 11:13:39 +0000697 // Update ending vreg->sreg map for GC maps generation.
698 int def_vreg = SRegToVReg(mir->ssa_rep->defs[0]);
699 bb->data_flow_info->vreg_to_ssa_map_exit[def_vreg] = mir->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000700 // We want to remove ft and tk and link bb directly to ft_ft. First, we need
701 // to update all Phi inputs correctly with UpdatePredecessor(ft->id, bb->id)
702 // since the live_def above comes from ft->first_mir_insn (if_false).
703 DCHECK(if_false == ft->first_mir_insn);
704 ft_ft->UpdatePredecessor(ft->id, bb->id);
705 // Correct the rest of the links between bb, ft and ft_ft.
706 ft->ErasePredecessor(bb->id);
707 ft->fall_through = NullBasicBlockId;
708 bb->fall_through = ft_ft->id;
709 // Now we can kill tk and ft.
710 tk->Kill(this);
711 ft->Kill(this);
712 // NOTE: DFS order, domination info and topological order are still usable
713 // despite the newly dead blocks.
buzbee311ca162013-02-28 15:56:43 -0800714 }
715 }
716 }
717 }
718 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700719 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) :
720 nullptr;
buzbee311ca162013-02-28 15:56:43 -0800721 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100722 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100723 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
724 }
buzbee311ca162013-02-28 15:56:43 -0800725
buzbee311ca162013-02-28 15:56:43 -0800726 return true;
727}
728
buzbee311ca162013-02-28 15:56:43 -0800729/* Collect stats on number of checks removed */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700730void MIRGraph::CountChecks(class BasicBlock* bb) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700731 if (bb->data_flow_info != nullptr) {
732 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
733 if (mir->ssa_rep == nullptr) {
buzbee862a7602013-04-05 10:58:54 -0700734 continue;
buzbee311ca162013-02-28 15:56:43 -0800735 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700736 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700737 if (df_attributes & DF_HAS_NULL_CHKS) {
738 checkstats_->null_checks++;
739 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
740 checkstats_->null_checks_eliminated++;
741 }
742 }
743 if (df_attributes & DF_HAS_RANGE_CHKS) {
744 checkstats_->range_checks++;
745 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
746 checkstats_->range_checks_eliminated++;
747 }
buzbee311ca162013-02-28 15:56:43 -0800748 }
749 }
750 }
buzbee311ca162013-02-28 15:56:43 -0800751}
752
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700753/* Try to make common case the fallthrough path. */
buzbee0d829482013-10-11 15:24:55 -0700754bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700755 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback.
buzbee311ca162013-02-28 15:56:43 -0800756 if (!bb->explicit_throw) {
757 return false;
758 }
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700759
760 // If we visited it, we are done.
761 if (bb->visited) {
762 return false;
763 }
764 bb->visited = true;
765
buzbee311ca162013-02-28 15:56:43 -0800766 BasicBlock* walker = bb;
767 while (true) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700768 // Check termination conditions.
buzbee311ca162013-02-28 15:56:43 -0800769 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
770 break;
771 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100772 DCHECK(!walker->predecessors.empty());
773 BasicBlock* prev = GetBasicBlock(walker->predecessors[0]);
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700774
775 // If we visited the predecessor, we are done.
776 if (prev->visited) {
777 return false;
778 }
779 prev->visited = true;
780
buzbee311ca162013-02-28 15:56:43 -0800781 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700782 if (GetBasicBlock(prev->fall_through) == walker) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700783 // Already done - return.
buzbee311ca162013-02-28 15:56:43 -0800784 break;
785 }
buzbee0d829482013-10-11 15:24:55 -0700786 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700787 // Got one. Flip it and exit.
buzbee311ca162013-02-28 15:56:43 -0800788 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
789 switch (opcode) {
790 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
791 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
792 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
793 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
794 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
795 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
796 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
797 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
798 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
799 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
800 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
801 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
802 default: LOG(FATAL) << "Unexpected opcode " << opcode;
803 }
804 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700805 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800806 prev->taken = prev->fall_through;
807 prev->fall_through = t_bb;
808 break;
809 }
810 walker = prev;
811 }
812 return false;
813}
814
815/* Combine any basic blocks terminated by instructions that we now know can't throw */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700816void MIRGraph::CombineBlocks(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800817 // Loop here to allow combining a sequence of blocks
Vladimir Marko312eb252014-10-07 15:01:57 +0100818 while ((bb->block_type == kDalvikByteCode) &&
819 (bb->last_mir_insn != nullptr) &&
820 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) == kMirOpCheck)) {
821 MIR* mir = bb->last_mir_insn;
822 DCHECK(bb->first_mir_insn != nullptr);
823
Vladimir Marko315cc202014-12-18 17:01:02 +0000824 // Get the paired insn and check if it can still throw.
Vladimir Marko312eb252014-10-07 15:01:57 +0100825 MIR* throw_insn = mir->meta.throw_insn;
Vladimir Marko315cc202014-12-18 17:01:02 +0000826 if (CanThrow(throw_insn)) {
buzbee311ca162013-02-28 15:56:43 -0800827 break;
828 }
829
buzbee311ca162013-02-28 15:56:43 -0800830 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700831 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800832 DCHECK(!bb_next->catch_entry);
Vladimir Marko312eb252014-10-07 15:01:57 +0100833 DCHECK_EQ(bb_next->predecessors.size(), 1u);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700834
835 // Now move instructions from bb_next to bb. Start off with doing a sanity check
836 // that kMirOpCheck's throw instruction is first one in the bb_next.
buzbee311ca162013-02-28 15:56:43 -0800837 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700838 // Now move all instructions (throw instruction to last one) from bb_next to bb.
839 MIR* last_to_move = bb_next->last_mir_insn;
840 bb_next->RemoveMIRList(throw_insn, last_to_move);
841 bb->InsertMIRListAfter(bb->last_mir_insn, throw_insn, last_to_move);
842 // The kMirOpCheck instruction is not needed anymore.
843 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
844 bb->RemoveMIR(mir);
845
Vladimir Marko312eb252014-10-07 15:01:57 +0100846 // Before we overwrite successors, remove their predecessor links to bb.
847 bb_next->ErasePredecessor(bb->id);
848 if (bb->taken != NullBasicBlockId) {
849 DCHECK_EQ(bb->successor_block_list_type, kNotUsed);
850 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
851 // bb->taken will be overwritten below.
852 DCHECK_EQ(bb_taken->block_type, kExceptionHandling);
853 DCHECK_EQ(bb_taken->predecessors.size(), 1u);
854 DCHECK_EQ(bb_taken->predecessors[0], bb->id);
855 bb_taken->predecessors.clear();
856 bb_taken->block_type = kDead;
857 DCHECK(bb_taken->data_flow_info == nullptr);
858 } else {
859 DCHECK_EQ(bb->successor_block_list_type, kCatch);
860 for (SuccessorBlockInfo* succ_info : bb->successor_blocks) {
861 if (succ_info->block != NullBasicBlockId) {
862 BasicBlock* succ_bb = GetBasicBlock(succ_info->block);
863 DCHECK(succ_bb->catch_entry);
864 succ_bb->ErasePredecessor(bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100865 }
866 }
867 }
buzbee311ca162013-02-28 15:56:43 -0800868 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700869 bb->successor_block_list_type = bb_next->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100870 bb->successor_blocks.swap(bb_next->successor_blocks); // Swap instead of copying.
Vladimir Marko312eb252014-10-07 15:01:57 +0100871 bb_next->successor_block_list_type = kNotUsed;
buzbee311ca162013-02-28 15:56:43 -0800872 // Use the ending block linkage from the next block
873 bb->fall_through = bb_next->fall_through;
Vladimir Marko312eb252014-10-07 15:01:57 +0100874 bb_next->fall_through = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800875 bb->taken = bb_next->taken;
Vladimir Marko312eb252014-10-07 15:01:57 +0100876 bb_next->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800877 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900878 * If lower-half of pair of blocks to combine contained
879 * a return or a conditional branch or an explicit throw,
880 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800881 */
882 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900883 bb->conditional_branch = bb_next->conditional_branch;
884 bb->explicit_throw = bb_next->explicit_throw;
Vladimir Marko312eb252014-10-07 15:01:57 +0100885 // Merge the use_lvn flag.
886 bb->use_lvn |= bb_next->use_lvn;
887
888 // Kill the unused block.
889 bb_next->data_flow_info = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800890
891 /*
892 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
893 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
Vladimir Marko312eb252014-10-07 15:01:57 +0100894 * NOTE: GVN uses bb->data_flow_info->live_in_v which is unaffected by the block merge.
buzbee311ca162013-02-28 15:56:43 -0800895 */
896
Vladimir Marko312eb252014-10-07 15:01:57 +0100897 // Kill bb_next and remap now-dead id to parent.
buzbee311ca162013-02-28 15:56:43 -0800898 bb_next->block_type = kDead;
Vladimir Marko312eb252014-10-07 15:01:57 +0100899 bb_next->data_flow_info = nullptr; // Must be null for dead blocks. (Relied on by the GVN.)
buzbee1fd33462013-03-25 13:40:45 -0700900 block_id_map_.Overwrite(bb_next->id, bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100901 // Update predecessors in children.
902 ChildBlockIterator iter(bb, this);
903 for (BasicBlock* child = iter.Next(); child != nullptr; child = iter.Next()) {
904 child->UpdatePredecessor(bb_next->id, bb->id);
905 }
906
Vladimir Markoffda4992014-12-18 17:05:58 +0000907 // DFS orders, domination and topological order are not up to date anymore.
Vladimir Marko312eb252014-10-07 15:01:57 +0100908 dfs_orders_up_to_date_ = false;
Vladimir Markoffda4992014-12-18 17:05:58 +0000909 domination_up_to_date_ = false;
910 topological_order_up_to_date_ = false;
buzbee311ca162013-02-28 15:56:43 -0800911
912 // Now, loop back and see if we can keep going
913 }
buzbee311ca162013-02-28 15:56:43 -0800914}
915
Vladimir Marko67c72b82014-10-09 12:26:10 +0100916bool MIRGraph::EliminateNullChecksGate() {
917 if ((cu_->disable_opt & (1 << kNullCheckElimination)) != 0 ||
918 (merged_df_flags_ & DF_HAS_NULL_CHKS) == 0) {
919 return false;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000920 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100921
Vladimir Marko67c72b82014-10-09 12:26:10 +0100922 DCHECK(temp_scoped_alloc_.get() == nullptr);
923 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700924 temp_.nce.num_vregs = GetNumOfCodeAndTempVRs();
Vladimir Markof585e542014-11-21 13:41:32 +0000925 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
926 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000927 temp_.nce.ending_vregs_to_check_matrix =
928 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +0000929 std::fill_n(temp_.nce.ending_vregs_to_check_matrix, GetNumBlocks(), nullptr);
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700930
931 // reset MIR_MARK
932 AllNodesIterator iter(this);
933 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700934 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700935 mir->optimization_flags &= ~MIR_MARK;
936 }
937 }
938
Vladimir Marko67c72b82014-10-09 12:26:10 +0100939 return true;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000940}
941
buzbee1da1e2f2013-11-15 13:37:01 -0800942/*
Vladimir Marko67c72b82014-10-09 12:26:10 +0100943 * Eliminate unnecessary null checks for a basic block.
buzbee1da1e2f2013-11-15 13:37:01 -0800944 */
Vladimir Marko67c72b82014-10-09 12:26:10 +0100945bool MIRGraph::EliminateNullChecks(BasicBlock* bb) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100946 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
947 // Ignore the kExitBlock as well.
948 DCHECK(bb->first_mir_insn == nullptr);
949 return false;
950 }
buzbee311ca162013-02-28 15:56:43 -0800951
Vladimir Markof585e542014-11-21 13:41:32 +0000952 ArenaBitVector* vregs_to_check = temp_.nce.work_vregs_to_check;
Vladimir Marko67c72b82014-10-09 12:26:10 +0100953 /*
954 * Set initial state. Catch blocks don't need any special treatment.
955 */
956 if (bb->block_type == kEntryBlock) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100957 vregs_to_check->ClearAllBits();
Vladimir Marko67c72b82014-10-09 12:26:10 +0100958 // Assume all ins are objects.
959 for (uint16_t in_reg = GetFirstInVR();
960 in_reg < GetNumOfCodeVRs(); in_reg++) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100961 vregs_to_check->SetBit(in_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100962 }
963 if ((cu_->access_flags & kAccStatic) == 0) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100964 // If non-static method, mark "this" as non-null.
Vladimir Marko67c72b82014-10-09 12:26:10 +0100965 int this_reg = GetFirstInVR();
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100966 vregs_to_check->ClearBit(this_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100967 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100968 } else {
969 DCHECK_EQ(bb->block_type, kDalvikByteCode);
970 // Starting state is union of all incoming arcs.
971 bool copied_first = false;
972 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +0000973 if (temp_.nce.ending_vregs_to_check_matrix[pred_id] == nullptr) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100974 continue;
975 }
976 BasicBlock* pred_bb = GetBasicBlock(pred_id);
977 DCHECK(pred_bb != nullptr);
978 MIR* null_check_insn = nullptr;
979 if (pred_bb->block_type == kDalvikByteCode) {
980 // Check to see if predecessor had an explicit null-check.
981 MIR* last_insn = pred_bb->last_mir_insn;
982 if (last_insn != nullptr) {
983 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
984 if ((last_opcode == Instruction::IF_EQZ && pred_bb->fall_through == bb->id) ||
985 (last_opcode == Instruction::IF_NEZ && pred_bb->taken == bb->id)) {
986 // Remember the null check insn if there's no other predecessor requiring null check.
987 if (!copied_first || !vregs_to_check->IsBitSet(last_insn->dalvikInsn.vA)) {
988 null_check_insn = last_insn;
989 }
buzbee1da1e2f2013-11-15 13:37:01 -0800990 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700991 }
992 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100993 if (!copied_first) {
994 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +0000995 vregs_to_check->Copy(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100996 } else {
Vladimir Markof585e542014-11-21 13:41:32 +0000997 vregs_to_check->Union(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100998 }
999 if (null_check_insn != nullptr) {
1000 vregs_to_check->ClearBit(null_check_insn->dalvikInsn.vA);
Vladimir Marko67c72b82014-10-09 12:26:10 +01001001 }
1002 }
1003 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
buzbee311ca162013-02-28 15:56:43 -08001004 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001005 // At this point, vregs_to_check shows which sregs have an object definition with
Vladimir Marko67c72b82014-10-09 12:26:10 +01001006 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -08001007
1008 // Walk through the instruction in the block, updating as necessary
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001009 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beylercc794c32014-05-02 09:34:13 -07001010 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -08001011
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -07001012 if ((df_attributes & DF_NULL_TRANSFER_N) != 0u) {
1013 // The algorithm was written in a phi agnostic way.
1014 continue;
1015 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001016
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001017 // Might need a null check?
1018 if (df_attributes & DF_HAS_NULL_CHKS) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001019 int src_vreg;
1020 if (df_attributes & DF_NULL_CHK_OUT0) {
1021 DCHECK_NE(df_attributes & DF_IS_INVOKE, 0u);
1022 src_vreg = mir->dalvikInsn.vC;
1023 } else if (df_attributes & DF_NULL_CHK_B) {
1024 DCHECK_NE(df_attributes & DF_REF_B, 0u);
1025 src_vreg = mir->dalvikInsn.vB;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001026 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001027 DCHECK_NE(df_attributes & DF_NULL_CHK_A, 0u);
1028 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1029 src_vreg = mir->dalvikInsn.vA;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001030 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001031 if (!vregs_to_check->IsBitSet(src_vreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001032 // Eliminate the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001033 mir->optimization_flags |= MIR_MARK;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001034 } else {
1035 // Do the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001036 mir->optimization_flags &= ~MIR_MARK;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001037 // Mark src_vreg as null-checked.
1038 vregs_to_check->ClearBit(src_vreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001039 }
1040 }
1041
1042 if ((df_attributes & DF_A_WIDE) ||
1043 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
1044 continue;
1045 }
1046
1047 /*
1048 * First, mark all object definitions as requiring null check.
1049 * Note: we can't tell if a CONST definition might be used as an object, so treat
1050 * them all as object definitions.
1051 */
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001052 if ((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A) ||
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001053 (df_attributes & DF_SETS_CONST)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001054 vregs_to_check->SetBit(mir->dalvikInsn.vA);
buzbee4db179d2013-10-23 12:16:39 -07001055 }
1056
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001057 // Then, remove mark from all object definitions we know are non-null.
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001058 if (df_attributes & DF_NON_NULL_DST) {
1059 // Mark target of NEW* as non-null
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001060 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1061 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001062 }
1063
buzbee311ca162013-02-28 15:56:43 -08001064 // Mark non-null returns from invoke-style NEW*
1065 if (df_attributes & DF_NON_NULL_RET) {
1066 MIR* next_mir = mir->next;
1067 // Next should be an MOVE_RESULT_OBJECT
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001068 if (UNLIKELY(next_mir == nullptr)) {
1069 // The MethodVerifier makes sure there's no MOVE_RESULT at the catch entry or branch
1070 // target, so the MOVE_RESULT cannot be broken away into another block.
1071 LOG(WARNING) << "Unexpected end of block following new";
1072 } else if (UNLIKELY(next_mir->dalvikInsn.opcode != Instruction::MOVE_RESULT_OBJECT)) {
1073 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee311ca162013-02-28 15:56:43 -08001074 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001075 // Mark as null checked.
1076 vregs_to_check->ClearBit(next_mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001077 }
1078 }
1079
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001080 // Propagate null check state on register copies.
1081 if (df_attributes & DF_NULL_TRANSFER_0) {
1082 DCHECK_EQ(df_attributes | ~(DF_DA | DF_REF_A | DF_UB | DF_REF_B), static_cast<uint64_t>(-1));
1083 if (vregs_to_check->IsBitSet(mir->dalvikInsn.vB)) {
1084 vregs_to_check->SetBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001085 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001086 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001087 }
1088 }
buzbee311ca162013-02-28 15:56:43 -08001089 }
1090
1091 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +00001092 bool nce_changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001093 ArenaBitVector* old_ending_ssa_regs_to_check = temp_.nce.ending_vregs_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001094 if (old_ending_ssa_regs_to_check == nullptr) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001095 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001096 nce_changed = vregs_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001097 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001098 // Create a new vregs_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001099 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1100 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001101 } else if (!vregs_to_check->SameBitsSet(old_ending_ssa_regs_to_check)) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001102 nce_changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001103 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
1104 temp_.nce.work_vregs_to_check = old_ending_ssa_regs_to_check; // Reuse for next BB.
buzbee311ca162013-02-28 15:56:43 -08001105 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001106 return nce_changed;
buzbee311ca162013-02-28 15:56:43 -08001107}
1108
Vladimir Marko67c72b82014-10-09 12:26:10 +01001109void MIRGraph::EliminateNullChecksEnd() {
1110 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001111 temp_.nce.num_vregs = 0u;
1112 temp_.nce.work_vregs_to_check = nullptr;
1113 temp_.nce.ending_vregs_to_check_matrix = nullptr;
Vladimir Marko67c72b82014-10-09 12:26:10 +01001114 DCHECK(temp_scoped_alloc_.get() != nullptr);
1115 temp_scoped_alloc_.reset();
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001116
1117 // converge MIR_MARK with MIR_IGNORE_NULL_CHECK
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001118 AllNodesIterator iter(this);
1119 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001120 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001121 constexpr int kMarkToIgnoreNullCheckShift = kMIRMark - kMIRIgnoreNullCheck;
Andreas Gampe785d2f22014-11-03 22:57:30 -08001122 static_assert(kMarkToIgnoreNullCheckShift > 0, "Not a valid right-shift");
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001123 uint16_t mirMarkAdjustedToIgnoreNullCheck =
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001124 (mir->optimization_flags & MIR_MARK) >> kMarkToIgnoreNullCheckShift;
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001125 mir->optimization_flags |= mirMarkAdjustedToIgnoreNullCheck;
1126 }
1127 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001128}
1129
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001130void MIRGraph::InferTypesStart() {
1131 DCHECK(temp_scoped_alloc_ != nullptr);
1132 temp_.ssa.ti = new (temp_scoped_alloc_.get()) TypeInference(this, temp_scoped_alloc_.get());
1133}
1134
Vladimir Marko67c72b82014-10-09 12:26:10 +01001135/*
1136 * Perform type and size inference for a basic block.
1137 */
1138bool MIRGraph::InferTypes(BasicBlock* bb) {
1139 if (bb->data_flow_info == nullptr) return false;
1140
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001141 DCHECK(temp_.ssa.ti != nullptr);
1142 return temp_.ssa.ti->Apply(bb);
1143}
Vladimir Marko67c72b82014-10-09 12:26:10 +01001144
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001145void MIRGraph::InferTypesEnd() {
1146 DCHECK(temp_.ssa.ti != nullptr);
1147 temp_.ssa.ti->Finish();
1148 delete temp_.ssa.ti;
1149 temp_.ssa.ti = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001150}
1151
1152bool MIRGraph::EliminateClassInitChecksGate() {
1153 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001154 (merged_df_flags_ & DF_CLINIT) == 0) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001155 return false;
1156 }
1157
Vladimir Markobfea9c22014-01-17 17:49:33 +00001158 DCHECK(temp_scoped_alloc_.get() == nullptr);
1159 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1160
1161 // Each insn we use here has at least 2 code units, offset/2 will be a unique index.
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001162 const size_t end = (GetNumDalvikInsns() + 1u) / 2u;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001163 temp_.cice.indexes = temp_scoped_alloc_->AllocArray<uint16_t>(end, kArenaAllocGrowableArray);
Vladimir Markof585e542014-11-21 13:41:32 +00001164 std::fill_n(temp_.cice.indexes, end, 0xffffu);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001165
1166 uint32_t unique_class_count = 0u;
1167 {
1168 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
1169 // ScopedArenaAllocator.
1170
1171 // Embed the map value in the entry to save space.
1172 struct MapEntry {
1173 // Map key: the class identified by the declaring dex file and type index.
1174 const DexFile* declaring_dex_file;
1175 uint16_t declaring_class_idx;
1176 // Map value: index into bit vectors of classes requiring initialization checks.
1177 uint16_t index;
1178 };
1179 struct MapEntryComparator {
1180 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
1181 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
1182 return lhs.declaring_class_idx < rhs.declaring_class_idx;
1183 }
1184 return lhs.declaring_dex_file < rhs.declaring_dex_file;
1185 }
1186 };
1187
Vladimir Markobfea9c22014-01-17 17:49:33 +00001188 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +01001189 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
1190 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001191
1192 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1193 AllNodesIterator iter(this);
1194 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001195 if (bb->block_type == kDalvikByteCode) {
1196 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001197 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001198 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001199 if (!field_info.IsReferrersClass()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001200 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1201 MapEntry entry = {
1202 // Treat unresolved fields as if each had its own class.
1203 field_info.IsResolved() ? field_info.DeclaringDexFile()
1204 : nullptr,
1205 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1206 : field_info.FieldIndex(),
1207 static_cast<uint16_t>(class_to_index_map.size())
1208 };
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001209 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001210 // Using offset/2 for index into temp_.cice.indexes.
1211 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001212 }
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001213 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001214 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1215 DCHECK(method_info.IsStatic());
1216 if (method_info.FastPath() && !method_info.IsReferrersClass()) {
1217 MapEntry entry = {
1218 method_info.DeclaringDexFile(),
1219 method_info.DeclaringClassIndex(),
1220 static_cast<uint16_t>(class_to_index_map.size())
1221 };
1222 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001223 // Using offset/2 for index into temp_.cice.indexes.
1224 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001225 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001226 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001227 }
1228 }
1229 }
1230 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1231 }
1232
1233 if (unique_class_count == 0u) {
1234 // All SGET/SPUTs refer to initialized classes. Nothing to do.
Vladimir Markof585e542014-11-21 13:41:32 +00001235 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001236 temp_scoped_alloc_.reset();
1237 return false;
1238 }
1239
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001240 // 2 bits for each class: is class initialized, is class in dex cache.
Vladimir Markof585e542014-11-21 13:41:32 +00001241 temp_.cice.num_class_bits = 2u * unique_class_count;
1242 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1243 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001244 temp_.cice.ending_classes_to_check_matrix =
1245 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +00001246 std::fill_n(temp_.cice.ending_classes_to_check_matrix, GetNumBlocks(), nullptr);
1247 DCHECK_GT(temp_.cice.num_class_bits, 0u);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001248 return true;
1249}
1250
1251/*
1252 * Eliminate unnecessary class initialization checks for a basic block.
1253 */
1254bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1255 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001256 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
1257 // Ignore the kExitBlock as well.
1258 DCHECK(bb->first_mir_insn == nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001259 return false;
1260 }
1261
1262 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001263 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001264 */
Vladimir Markof585e542014-11-21 13:41:32 +00001265 ArenaBitVector* classes_to_check = temp_.cice.work_classes_to_check;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001266 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001267 if (bb->block_type == kEntryBlock) {
Vladimir Markof585e542014-11-21 13:41:32 +00001268 classes_to_check->SetInitialBits(temp_.cice.num_class_bits);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001269 } else {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001270 // Starting state is union of all incoming arcs.
1271 bool copied_first = false;
1272 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +00001273 if (temp_.cice.ending_classes_to_check_matrix[pred_id] == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001274 continue;
1275 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001276 if (!copied_first) {
1277 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001278 classes_to_check->Copy(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001279 } else {
Vladimir Markof585e542014-11-21 13:41:32 +00001280 classes_to_check->Union(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001281 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001282 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001283 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001284 }
1285 // At this point, classes_to_check shows which classes need clinit checks.
1286
1287 // Walk through the instruction in the block, updating as necessary
1288 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markof585e542014-11-21 13:41:32 +00001289 uint16_t index = temp_.cice.indexes[mir->offset / 2u];
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001290 if (index != 0xffffu) {
1291 bool check_initialization = false;
1292 bool check_dex_cache = false;
1293
1294 // NOTE: index != 0xffff does not guarantee that this is an SGET/SPUT/INVOKE_STATIC.
1295 // Dex instructions with width 1 can have the same offset/2.
1296
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001297 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001298 check_initialization = true;
1299 check_dex_cache = true;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001300 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001301 check_initialization = true;
1302 // NOTE: INVOKE_STATIC doesn't guarantee that the type will be in the dex cache.
1303 }
1304
1305 if (check_dex_cache) {
1306 uint32_t check_dex_cache_index = 2u * index + 1u;
1307 if (!classes_to_check->IsBitSet(check_dex_cache_index)) {
1308 // Eliminate the class init check.
1309 mir->optimization_flags |= MIR_CLASS_IS_IN_DEX_CACHE;
1310 } else {
1311 // Do the class init check.
1312 mir->optimization_flags &= ~MIR_CLASS_IS_IN_DEX_CACHE;
1313 }
1314 classes_to_check->ClearBit(check_dex_cache_index);
1315 }
1316 if (check_initialization) {
1317 uint32_t check_clinit_index = 2u * index;
1318 if (!classes_to_check->IsBitSet(check_clinit_index)) {
1319 // Eliminate the class init check.
1320 mir->optimization_flags |= MIR_CLASS_IS_INITIALIZED;
1321 } else {
1322 // Do the class init check.
1323 mir->optimization_flags &= ~MIR_CLASS_IS_INITIALIZED;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001324 }
1325 // Mark the class as initialized.
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001326 classes_to_check->ClearBit(check_clinit_index);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001327 }
1328 }
1329 }
1330
1331 // Did anything change?
1332 bool changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001333 ArenaBitVector* old_ending_classes_to_check = temp_.cice.ending_classes_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001334 if (old_ending_classes_to_check == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001335 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001336 changed = classes_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001337 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001338 // Create a new classes_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001339 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1340 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Marko5229cf12014-10-09 14:57:59 +01001341 } else if (!classes_to_check->Equal(old_ending_classes_to_check)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001342 changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001343 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
1344 temp_.cice.work_classes_to_check = old_ending_classes_to_check; // Reuse for next BB.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001345 }
1346 return changed;
1347}
1348
1349void MIRGraph::EliminateClassInitChecksEnd() {
1350 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001351 temp_.cice.num_class_bits = 0u;
1352 temp_.cice.work_classes_to_check = nullptr;
1353 temp_.cice.ending_classes_to_check_matrix = nullptr;
1354 DCHECK(temp_.cice.indexes != nullptr);
1355 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001356 DCHECK(temp_scoped_alloc_.get() != nullptr);
1357 temp_scoped_alloc_.reset();
1358}
1359
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001360static void DisableGVNDependentOptimizations(CompilationUnit* cu) {
1361 cu->disable_opt |= (1u << kGvnDeadCodeElimination);
1362}
1363
Vladimir Marko95a05972014-05-30 10:01:32 +01001364bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko415ac882014-09-30 18:09:14 +01001365 if (GlobalValueNumbering::Skip(cu_)) {
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001366 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001367 return false;
1368 }
1369
1370 DCHECK(temp_scoped_alloc_ == nullptr);
1371 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001372 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001373 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001374 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001375 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
Vladimir Markof585e542014-11-21 13:41:32 +00001376 DCHECK(temp_.gvn.gvn == nullptr);
1377 temp_.gvn.gvn = new (temp_scoped_alloc_.get()) GlobalValueNumbering(
1378 cu_, temp_scoped_alloc_.get(), GlobalValueNumbering::kModeGvn);
Vladimir Marko95a05972014-05-30 10:01:32 +01001379 return true;
1380}
1381
1382bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
Vladimir Markof585e542014-11-21 13:41:32 +00001383 DCHECK(temp_.gvn.gvn != nullptr);
1384 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001385 if (lvn != nullptr) {
1386 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1387 lvn->GetValueNumber(mir);
1388 }
1389 }
Vladimir Markof585e542014-11-21 13:41:32 +00001390 bool change = (lvn != nullptr) && temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001391 return change;
1392}
1393
1394void MIRGraph::ApplyGlobalValueNumberingEnd() {
1395 // Perform modifications.
Vladimir Markof585e542014-11-21 13:41:32 +00001396 DCHECK(temp_.gvn.gvn != nullptr);
1397 if (temp_.gvn.gvn->Good()) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001398 temp_.gvn.gvn->StartPostProcessing();
Vladimir Marko415ac882014-09-30 18:09:14 +01001399 if (max_nested_loops_ != 0u) {
Vladimir Marko415ac882014-09-30 18:09:14 +01001400 TopologicalSortIterator iter(this);
1401 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1402 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
Vladimir Markof585e542014-11-21 13:41:32 +00001403 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb, &allocator);
Vladimir Marko415ac882014-09-30 18:09:14 +01001404 if (lvn != nullptr) {
1405 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1406 lvn->GetValueNumber(mir);
1407 }
Vladimir Markof585e542014-11-21 13:41:32 +00001408 bool change = temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko415ac882014-09-30 18:09:14 +01001409 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001410 }
Vladimir Marko95a05972014-05-30 10:01:32 +01001411 }
1412 }
Vladimir Marko415ac882014-09-30 18:09:14 +01001413 // GVN was successful, running the LVN would be useless.
1414 cu_->disable_opt |= (1u << kLocalValueNumbering);
Vladimir Marko95a05972014-05-30 10:01:32 +01001415 } else {
1416 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001417 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001418 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001419}
1420
1421bool MIRGraph::EliminateDeadCodeGate() {
Vladimir Markoad677272015-04-20 10:48:13 +01001422 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0 || temp_.gvn.gvn == nullptr) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001423 return false;
1424 }
1425 DCHECK(temp_scoped_alloc_ != nullptr);
1426 temp_.gvn.dce = new (temp_scoped_alloc_.get()) GvnDeadCodeElimination(temp_.gvn.gvn,
1427 temp_scoped_alloc_.get());
1428 return true;
1429}
1430
1431bool MIRGraph::EliminateDeadCode(BasicBlock* bb) {
1432 DCHECK(temp_scoped_alloc_ != nullptr);
1433 DCHECK(temp_.gvn.gvn != nullptr);
1434 if (bb->block_type != kDalvikByteCode) {
1435 return false;
1436 }
1437 DCHECK(temp_.gvn.dce != nullptr);
1438 temp_.gvn.dce->Apply(bb);
1439 return false; // No need to repeat.
1440}
1441
1442void MIRGraph::EliminateDeadCodeEnd() {
Vladimir Markoad677272015-04-20 10:48:13 +01001443 if (kIsDebugBuild) {
1444 // DCE can make some previously dead vregs alive again. Make sure the obsolete
1445 // live-in information is not used anymore.
1446 AllNodesIterator iter(this);
1447 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1448 if (bb->data_flow_info != nullptr) {
1449 bb->data_flow_info->live_in_v = nullptr;
1450 }
1451 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001452 }
Vladimir Markoad677272015-04-20 10:48:13 +01001453}
1454
1455void MIRGraph::GlobalValueNumberingCleanup() {
1456 delete temp_.gvn.dce;
1457 temp_.gvn.dce = nullptr;
Vladimir Markof585e542014-11-21 13:41:32 +00001458 delete temp_.gvn.gvn;
1459 temp_.gvn.gvn = nullptr;
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001460 temp_.gvn.ifield_ids = nullptr;
1461 temp_.gvn.sfield_ids = nullptr;
Vladimir Marko95a05972014-05-30 10:01:32 +01001462 DCHECK(temp_scoped_alloc_ != nullptr);
1463 temp_scoped_alloc_.reset();
1464}
1465
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001466void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1467 uint32_t method_index = invoke->meta.method_lowering_info;
Vladimir Markof585e542014-11-21 13:41:32 +00001468 if (temp_.smi.processed_indexes->IsBitSet(method_index)) {
1469 iget_or_iput->meta.ifield_lowering_info = temp_.smi.lowering_infos[method_index];
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001470 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1471 return;
1472 }
1473
1474 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1475 MethodReference target = method_info.GetTargetMethod();
1476 DexCompilationUnit inlined_unit(
1477 cu_, cu_->class_loader, cu_->class_linker, *target.dex_file,
1478 nullptr /* code_item not used */, 0u /* class_def_idx not used */, target.dex_method_index,
1479 0u /* access_flags not used */, nullptr /* verified_method not used */);
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001480 DexMemAccessType type = IGetOrIPutMemAccessType(iget_or_iput->dalvikInsn.opcode);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001481 MirIFieldLoweringInfo inlined_field_info(field_idx, type, false);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001482 MirIFieldLoweringInfo::Resolve(cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
1483 DCHECK(inlined_field_info.IsResolved());
1484
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001485 uint32_t field_info_index = ifield_lowering_infos_.size();
1486 ifield_lowering_infos_.push_back(inlined_field_info);
Vladimir Markof585e542014-11-21 13:41:32 +00001487 temp_.smi.processed_indexes->SetBit(method_index);
1488 temp_.smi.lowering_infos[method_index] = field_info_index;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001489 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1490}
1491
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001492bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001493 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001494 method_lowering_infos_.size() == 0u) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001495 return false;
1496 }
1497 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1498 // This isn't the Quick compiler.
1499 return false;
1500 }
1501 return true;
1502}
1503
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001504void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001505 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1506 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1507
1508 DCHECK(temp_scoped_alloc_.get() == nullptr);
1509 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001510 temp_.smi.num_indexes = method_lowering_infos_.size();
1511 temp_.smi.processed_indexes = new (temp_scoped_alloc_.get()) ArenaBitVector(
1512 temp_scoped_alloc_.get(), temp_.smi.num_indexes, false, kBitMapMisc);
1513 temp_.smi.processed_indexes->ClearAllBits();
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001514 temp_.smi.lowering_infos =
1515 temp_scoped_alloc_->AllocArray<uint16_t>(temp_.smi.num_indexes, kArenaAllocGrowableArray);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001516}
1517
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001518void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001519 if (bb->block_type != kDalvikByteCode) {
1520 return;
1521 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001522 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001523 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001524 continue;
1525 }
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001526 if (!(mir->dalvikInsn.FlagsOf() & Instruction::kInvoke)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001527 continue;
1528 }
1529 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
Vladimir Marko87b7c522015-04-08 10:01:01 +01001530 if (!method_info.FastPath() || !method_info.IsSpecial()) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001531 continue;
1532 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001533
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001534 InvokeType sharp_type = method_info.GetSharpType();
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001535 if ((sharp_type != kDirect) && (sharp_type != kStatic)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001536 continue;
1537 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001538
1539 if (sharp_type == kStatic) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001540 bool needs_clinit = !method_info.IsClassInitialized() &&
1541 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) == 0);
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001542 if (needs_clinit) {
1543 continue;
1544 }
1545 }
1546
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001547 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1548 MethodReference target = method_info.GetTargetMethod();
1549 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1550 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001551 if (cu_->verbose || cu_->print_pass) {
1552 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001553 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index,
1554 *target.dex_file)
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001555 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1556 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001557 }
1558 }
1559 }
1560}
1561
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001562void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Markof585e542014-11-21 13:41:32 +00001563 // Clean up temporaries.
1564 DCHECK(temp_.smi.lowering_infos != nullptr);
1565 temp_.smi.lowering_infos = nullptr;
1566 temp_.smi.num_indexes = 0u;
1567 DCHECK(temp_.smi.processed_indexes != nullptr);
1568 temp_.smi.processed_indexes = nullptr;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001569 DCHECK(temp_scoped_alloc_.get() != nullptr);
1570 temp_scoped_alloc_.reset();
1571}
1572
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001573void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001574 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001575 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001576 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001577 AllNodesIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001578 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
buzbee311ca162013-02-28 15:56:43 -08001579 CountChecks(bb);
1580 }
1581 if (stats->null_checks > 0) {
1582 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1583 float checks = static_cast<float>(stats->null_checks);
1584 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1585 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1586 << (eliminated/checks) * 100.0 << "%";
1587 }
1588 if (stats->range_checks > 0) {
1589 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1590 float checks = static_cast<float>(stats->range_checks);
1591 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1592 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1593 << (eliminated/checks) * 100.0 << "%";
1594 }
1595}
1596
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001597bool MIRGraph::BuildExtendedBBList(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001598 if (bb->visited) return false;
1599 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1600 || (bb->block_type == kExitBlock))) {
1601 // Ignore special blocks
1602 bb->visited = true;
1603 return false;
1604 }
1605 // Must be head of extended basic block.
1606 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001607 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001608 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001609 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001610 // Visit blocks strictly dominated by this head.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001611 while (bb != nullptr) {
buzbee311ca162013-02-28 15:56:43 -08001612 bb->visited = true;
1613 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001614 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001615 bb = NextDominatedBlock(bb);
1616 }
buzbee1da1e2f2013-11-15 13:37:01 -08001617 if (terminated_by_return || do_local_value_numbering) {
1618 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001619 bb = start_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001620 while (bb != nullptr) {
buzbee1da1e2f2013-11-15 13:37:01 -08001621 bb->use_lvn = do_local_value_numbering;
1622 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001623 bb = NextDominatedBlock(bb);
1624 }
1625 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001626 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001627}
1628
Vladimir Markoffda4992014-12-18 17:05:58 +00001629void MIRGraph::BasicBlockOptimizationStart() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001630 if ((cu_->disable_opt & (1 << kLocalValueNumbering)) == 0) {
1631 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001632 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001633 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001634 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001635 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
1636 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001637}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001638
Vladimir Markoffda4992014-12-18 17:05:58 +00001639void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001640 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1641 ClearAllVisitedFlags();
1642 PreOrderDfsIterator iter2(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001643 for (BasicBlock* bb = iter2.Next(); bb != nullptr; bb = iter2.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001644 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001645 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001646 // Perform extended basic block optimizations.
1647 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1648 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1649 }
1650 } else {
1651 PreOrderDfsIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001652 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001653 BasicBlockOpt(bb);
1654 }
buzbee311ca162013-02-28 15:56:43 -08001655 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001656}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001657
Vladimir Markoffda4992014-12-18 17:05:58 +00001658void MIRGraph::BasicBlockOptimizationEnd() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001659 // Clean up after LVN.
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001660 temp_.gvn.ifield_ids = nullptr;
1661 temp_.gvn.sfield_ids = nullptr;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001662 temp_scoped_alloc_.reset();
buzbee311ca162013-02-28 15:56:43 -08001663}
1664
Jeff Hao848f70a2014-01-15 13:49:50 -08001665void MIRGraph::StringChange() {
1666 AllNodesIterator iter(this);
1667 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1668 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1669 // Look for new instance opcodes, skip otherwise
1670 Instruction::Code opcode = mir->dalvikInsn.opcode;
1671 if (opcode == Instruction::NEW_INSTANCE) {
1672 uint32_t type_idx = mir->dalvikInsn.vB;
1673 if (cu_->compiler_driver->IsStringTypeIndex(type_idx, cu_->dex_file)) {
1674 // Change NEW_INSTANCE and throwing half of the insn (if it exists) into CONST_4 of 0
1675 mir->dalvikInsn.opcode = Instruction::CONST_4;
1676 mir->dalvikInsn.vB = 0;
1677 MIR* check_mir = GetBasicBlock(bb->predecessors[0])->last_mir_insn;
1678 if (check_mir != nullptr &&
1679 static_cast<int>(check_mir->dalvikInsn.opcode) == kMirOpCheck) {
1680 check_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1681 check_mir->dalvikInsn.vB = 0;
1682 }
1683 }
1684 } else if ((opcode == Instruction::INVOKE_DIRECT) ||
1685 (opcode == Instruction::INVOKE_DIRECT_RANGE)) {
1686 uint32_t method_idx = mir->dalvikInsn.vB;
1687 DexFileMethodInliner* inliner =
1688 cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(cu_->dex_file);
1689 if (inliner->IsStringInitMethodIndex(method_idx)) {
1690 bool is_range = (opcode == Instruction::INVOKE_DIRECT_RANGE);
1691 uint32_t orig_this_reg = is_range ? mir->dalvikInsn.vC : mir->dalvikInsn.arg[0];
1692 // Remove this pointer from string init and change to static call.
1693 mir->dalvikInsn.vA--;
1694 if (!is_range) {
1695 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC;
1696 for (uint32_t i = 0; i < mir->dalvikInsn.vA; i++) {
1697 mir->dalvikInsn.arg[i] = mir->dalvikInsn.arg[i + 1];
1698 }
1699 } else {
1700 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC_RANGE;
1701 mir->dalvikInsn.vC++;
1702 }
1703 // Insert a move-result instruction to the original this pointer reg.
1704 MIR* move_result_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1705 move_result_mir->dalvikInsn.opcode = Instruction::MOVE_RESULT_OBJECT;
1706 move_result_mir->dalvikInsn.vA = orig_this_reg;
1707 move_result_mir->offset = mir->offset;
1708 move_result_mir->m_unit_index = mir->m_unit_index;
1709 bb->InsertMIRAfter(mir, move_result_mir);
1710 // Add additional moves if this pointer was copied to other registers.
1711 const VerifiedMethod* verified_method =
1712 cu_->compiler_driver->GetVerifiedMethod(cu_->dex_file, cu_->method_idx);
1713 DCHECK(verified_method != nullptr);
1714 const SafeMap<uint32_t, std::set<uint32_t>>& string_init_map =
1715 verified_method->GetStringInitPcRegMap();
1716 auto map_it = string_init_map.find(mir->offset);
1717 if (map_it != string_init_map.end()) {
1718 const std::set<uint32_t>& reg_set = map_it->second;
1719 for (auto set_it = reg_set.begin(); set_it != reg_set.end(); ++set_it) {
1720 MIR* move_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1721 move_mir->dalvikInsn.opcode = Instruction::MOVE_OBJECT;
1722 move_mir->dalvikInsn.vA = *set_it;
1723 move_mir->dalvikInsn.vB = orig_this_reg;
1724 move_mir->offset = mir->offset;
1725 move_mir->m_unit_index = mir->m_unit_index;
1726 bb->InsertMIRAfter(move_result_mir, move_mir);
1727 }
1728 }
1729 }
1730 }
1731 }
1732 }
1733}
1734
1735
Vladimir Marko8b858e12014-11-27 14:52:37 +00001736bool MIRGraph::EliminateSuspendChecksGate() {
1737 if ((cu_->disable_opt & (1 << kSuspendCheckElimination)) != 0 || // Disabled.
1738 GetMaxNestedLoops() == 0u || // Nothing to do.
1739 GetMaxNestedLoops() >= 32u || // Only 32 bits in suspend_checks_in_loops_[.].
1740 // Exclude 32 as well to keep bit shifts well-defined.
1741 !HasInvokes()) { // No invokes to actually eliminate any suspend checks.
1742 return false;
1743 }
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001744 suspend_checks_in_loops_ = arena_->AllocArray<uint32_t>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Marko8b858e12014-11-27 14:52:37 +00001745 return true;
1746}
1747
1748bool MIRGraph::EliminateSuspendChecks(BasicBlock* bb) {
1749 if (bb->block_type != kDalvikByteCode) {
1750 return false;
1751 }
1752 DCHECK_EQ(GetTopologicalSortOrderLoopHeadStack()->size(), bb->nesting_depth);
1753 if (bb->nesting_depth == 0u) {
1754 // Out of loops.
1755 DCHECK_EQ(suspend_checks_in_loops_[bb->id], 0u); // The array was zero-initialized.
1756 return false;
1757 }
1758 uint32_t suspend_checks_in_loops = (1u << bb->nesting_depth) - 1u; // Start with all loop heads.
1759 bool found_invoke = false;
1760 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko87b7c522015-04-08 10:01:01 +01001761 if ((IsInstructionInvoke(mir->dalvikInsn.opcode) ||
1762 IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) &&
1763 !GetMethodLoweringInfo(mir).IsIntrinsic()) {
Vladimir Marko8b858e12014-11-27 14:52:37 +00001764 // Non-intrinsic invoke, rely on a suspend point in the invoked method.
1765 found_invoke = true;
1766 break;
1767 }
1768 }
1769 if (!found_invoke) {
1770 // Intersect suspend checks from predecessors.
1771 uint16_t bb_topo_idx = topological_order_indexes_[bb->id];
1772 uint32_t pred_mask_union = 0u;
1773 for (BasicBlockId pred_id : bb->predecessors) {
1774 uint16_t pred_topo_idx = topological_order_indexes_[pred_id];
1775 if (pred_topo_idx < bb_topo_idx) {
1776 // Determine the loop depth of the predecessors relative to this block.
1777 size_t pred_loop_depth = topological_order_loop_head_stack_.size();
1778 while (pred_loop_depth != 0u &&
1779 pred_topo_idx < topological_order_loop_head_stack_[pred_loop_depth - 1].first) {
1780 --pred_loop_depth;
1781 }
1782 DCHECK_LE(pred_loop_depth, GetBasicBlock(pred_id)->nesting_depth);
1783 uint32_t pred_mask = (1u << pred_loop_depth) - 1u;
1784 // Intersect pred_mask bits in suspend_checks_in_loops with
1785 // suspend_checks_in_loops_[pred_id].
1786 uint32_t pred_loops_without_checks = pred_mask & ~suspend_checks_in_loops_[pred_id];
1787 suspend_checks_in_loops = suspend_checks_in_loops & ~pred_loops_without_checks;
1788 pred_mask_union |= pred_mask;
1789 }
1790 }
1791 DCHECK_EQ(((1u << (IsLoopHead(bb->id) ? bb->nesting_depth - 1u: bb->nesting_depth)) - 1u),
1792 pred_mask_union);
1793 suspend_checks_in_loops &= pred_mask_union;
1794 }
1795 suspend_checks_in_loops_[bb->id] = suspend_checks_in_loops;
1796 if (suspend_checks_in_loops == 0u) {
1797 return false;
1798 }
1799 // Apply MIR_IGNORE_SUSPEND_CHECK if appropriate.
1800 if (bb->taken != NullBasicBlockId) {
1801 DCHECK(bb->last_mir_insn != nullptr);
1802 DCHECK(IsInstructionIfCc(bb->last_mir_insn->dalvikInsn.opcode) ||
1803 IsInstructionIfCcZ(bb->last_mir_insn->dalvikInsn.opcode) ||
1804 IsInstructionGoto(bb->last_mir_insn->dalvikInsn.opcode) ||
1805 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) >= kMirOpFusedCmplFloat &&
1806 static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) <= kMirOpFusedCmpLong));
1807 if (!IsSuspendCheckEdge(bb, bb->taken) &&
1808 (bb->fall_through == NullBasicBlockId || !IsSuspendCheckEdge(bb, bb->fall_through))) {
1809 bb->last_mir_insn->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
1810 }
1811 } else if (bb->fall_through != NullBasicBlockId && IsSuspendCheckEdge(bb, bb->fall_through)) {
1812 // We've got a fall-through suspend edge. Add an artificial GOTO to force suspend check.
1813 MIR* mir = NewMIR();
1814 mir->dalvikInsn.opcode = Instruction::GOTO;
1815 mir->dalvikInsn.vA = 0; // Branch offset.
1816 mir->offset = GetBasicBlock(bb->fall_through)->start_offset;
1817 mir->m_unit_index = current_method_;
1818 mir->ssa_rep = reinterpret_cast<SSARepresentation*>(
1819 arena_->Alloc(sizeof(SSARepresentation), kArenaAllocDFInfo)); // Zero-initialized.
1820 bb->AppendMIR(mir);
1821 std::swap(bb->fall_through, bb->taken); // The fall-through has become taken.
1822 }
1823 return true;
1824}
1825
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001826bool MIRGraph::CanThrow(MIR* mir) const {
Ningsheng Jiana262f772014-11-25 16:48:07 +08001827 if ((mir->dalvikInsn.FlagsOf() & Instruction::kThrow) == 0) {
1828 return false;
1829 }
1830 const int opt_flags = mir->optimization_flags;
1831 uint64_t df_attributes = GetDataFlowAttributes(mir);
1832
Vladimir Marko315cc202014-12-18 17:01:02 +00001833 // First, check if the insn can still throw NPE.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001834 if (((df_attributes & DF_HAS_NULL_CHKS) != 0) && ((opt_flags & MIR_IGNORE_NULL_CHECK) == 0)) {
1835 return true;
1836 }
Vladimir Marko315cc202014-12-18 17:01:02 +00001837
1838 // Now process specific instructions.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001839 if ((df_attributes & DF_IFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001840 // The IGET/IPUT family. We have processed the IGET/IPUT null check above.
1841 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1842 // If not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001843 const MirIFieldLoweringInfo& field_info = GetIFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001844 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
1845 return !fast;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001846 } else if ((df_attributes & DF_SFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001847 // The SGET/SPUT family. Check for potentially throwing class initialization.
1848 // Also, if not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001849 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001850 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
Ningsheng Jiana262f772014-11-25 16:48:07 +08001851 bool is_class_initialized = field_info.IsClassInitialized() ||
1852 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0);
Vladimir Marko315cc202014-12-18 17:01:02 +00001853 return !(fast && is_class_initialized);
1854 } else if ((df_attributes & DF_HAS_RANGE_CHKS) != 0) {
1855 // Only AGET/APUT have range checks. We have processed the AGET/APUT null check above.
1856 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1857 // Non-throwing only if range check has been eliminated.
1858 return ((opt_flags & MIR_IGNORE_RANGE_CHECK) == 0);
Vladimir Marko22fe45d2015-03-18 11:33:58 +00001859 } else if (mir->dalvikInsn.opcode == Instruction::CHECK_CAST &&
1860 (opt_flags & MIR_IGNORE_CHECK_CAST) != 0) {
1861 return false;
Vladimir Marko315cc202014-12-18 17:01:02 +00001862 } else if (mir->dalvikInsn.opcode == Instruction::ARRAY_LENGTH ||
Vladimir Marko315cc202014-12-18 17:01:02 +00001863 static_cast<int>(mir->dalvikInsn.opcode) == kMirOpNullCheck) {
1864 // No more checks for these (null check was processed above).
1865 return false;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001866 }
1867 return true;
1868}
1869
1870bool MIRGraph::HasAntiDependency(MIR* first, MIR* second) {
1871 DCHECK(first->ssa_rep != nullptr);
1872 DCHECK(second->ssa_rep != nullptr);
1873 if ((second->ssa_rep->num_defs > 0) && (first->ssa_rep->num_uses > 0)) {
1874 int vreg0 = SRegToVReg(second->ssa_rep->defs[0]);
1875 int vreg1 = (second->ssa_rep->num_defs == 2) ?
1876 SRegToVReg(second->ssa_rep->defs[1]) : INVALID_VREG;
1877 for (int i = 0; i < first->ssa_rep->num_uses; i++) {
1878 int32_t use = SRegToVReg(first->ssa_rep->uses[i]);
1879 if (use == vreg0 || use == vreg1) {
1880 return true;
1881 }
1882 }
1883 }
1884 return false;
1885}
1886
1887void MIRGraph::CombineMultiplyAdd(MIR* mul_mir, MIR* add_mir, bool mul_is_first_addend,
1888 bool is_wide, bool is_sub) {
1889 if (is_wide) {
1890 if (is_sub) {
1891 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubLong);
1892 } else {
1893 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddLong);
1894 }
1895 } else {
1896 if (is_sub) {
1897 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubInt);
1898 } else {
1899 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddInt);
1900 }
1901 }
1902 add_mir->ssa_rep->num_uses = is_wide ? 6 : 3;
1903 int32_t addend0 = INVALID_SREG;
1904 int32_t addend1 = INVALID_SREG;
1905 if (is_wide) {
1906 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[2] : add_mir->ssa_rep->uses[0];
1907 addend1 = mul_is_first_addend ? add_mir->ssa_rep->uses[3] : add_mir->ssa_rep->uses[1];
1908 } else {
1909 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[1] : add_mir->ssa_rep->uses[0];
1910 }
1911
1912 AllocateSSAUseData(add_mir, add_mir->ssa_rep->num_uses);
1913 add_mir->ssa_rep->uses[0] = mul_mir->ssa_rep->uses[0];
1914 add_mir->ssa_rep->uses[1] = mul_mir->ssa_rep->uses[1];
1915 // Clear the original multiply product ssa use count, as it is not used anymore.
1916 raw_use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1917 use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1918 if (is_wide) {
1919 DCHECK_EQ(add_mir->ssa_rep->num_uses, 6);
1920 add_mir->ssa_rep->uses[2] = mul_mir->ssa_rep->uses[2];
1921 add_mir->ssa_rep->uses[3] = mul_mir->ssa_rep->uses[3];
1922 add_mir->ssa_rep->uses[4] = addend0;
1923 add_mir->ssa_rep->uses[5] = addend1;
1924 raw_use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1925 use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1926 } else {
1927 DCHECK_EQ(add_mir->ssa_rep->num_uses, 3);
1928 add_mir->ssa_rep->uses[2] = addend0;
1929 }
1930 // Copy in the decoded instruction information.
1931 add_mir->dalvikInsn.vB = SRegToVReg(add_mir->ssa_rep->uses[0]);
1932 if (is_wide) {
1933 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[2]);
1934 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[4]);
1935 } else {
1936 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[1]);
1937 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[2]);
1938 }
1939 // Original multiply MIR is set to Nop.
1940 mul_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1941}
1942
1943void MIRGraph::MultiplyAddOpt(BasicBlock* bb) {
1944 if (bb->block_type == kDead) {
1945 return;
1946 }
1947 ScopedArenaAllocator allocator(&cu_->arena_stack);
1948 ScopedArenaSafeMap<uint32_t, MIR*> ssa_mul_map(std::less<uint32_t>(), allocator.Adapter());
1949 ScopedArenaSafeMap<uint32_t, MIR*>::iterator map_it;
1950 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1951 Instruction::Code opcode = mir->dalvikInsn.opcode;
1952 bool is_sub = true;
1953 bool is_candidate_multiply = false;
1954 switch (opcode) {
1955 case Instruction::MUL_INT:
1956 case Instruction::MUL_INT_2ADDR:
1957 is_candidate_multiply = true;
1958 break;
1959 case Instruction::MUL_LONG:
1960 case Instruction::MUL_LONG_2ADDR:
1961 if (cu_->target64) {
1962 is_candidate_multiply = true;
1963 }
1964 break;
1965 case Instruction::ADD_INT:
1966 case Instruction::ADD_INT_2ADDR:
1967 is_sub = false;
1968 FALLTHROUGH_INTENDED;
1969 case Instruction::SUB_INT:
1970 case Instruction::SUB_INT_2ADDR:
1971 if (((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end()) && !is_sub) {
1972 // a*b+c
1973 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1974 false /* is_wide */, false /* is_sub */);
1975 ssa_mul_map.erase(mir->ssa_rep->uses[0]);
1976 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[1])) != ssa_mul_map.end()) {
1977 // c+a*b or c-a*b
1978 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1979 false /* is_wide */, is_sub);
1980 ssa_mul_map.erase(map_it);
1981 }
1982 break;
1983 case Instruction::ADD_LONG:
1984 case Instruction::ADD_LONG_2ADDR:
1985 is_sub = false;
1986 FALLTHROUGH_INTENDED;
1987 case Instruction::SUB_LONG:
1988 case Instruction::SUB_LONG_2ADDR:
1989 if (!cu_->target64) {
1990 break;
1991 }
1992 if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end() && !is_sub) {
1993 // a*b+c
1994 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1995 true /* is_wide */, false /* is_sub */);
1996 ssa_mul_map.erase(map_it);
1997 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[2])) != ssa_mul_map.end()) {
1998 // c+a*b or c-a*b
1999 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
2000 true /* is_wide */, is_sub);
2001 ssa_mul_map.erase(map_it);
2002 }
2003 break;
2004 default:
2005 if (!ssa_mul_map.empty() && CanThrow(mir)) {
2006 // Should not combine multiply and add MIRs across potential exception.
2007 ssa_mul_map.clear();
2008 }
2009 break;
2010 }
2011
2012 // Exclude the case when an MIR writes a vreg which is previous candidate multiply MIR's uses.
2013 // It is because that current RA may allocate the same physical register to them. For this
2014 // kind of cases, the multiplier has been updated, we should not use updated value to the
2015 // multiply-add insn.
2016 if (ssa_mul_map.size() > 0) {
2017 for (auto it = ssa_mul_map.begin(); it != ssa_mul_map.end();) {
2018 MIR* mul = it->second;
2019 if (HasAntiDependency(mul, mir)) {
2020 it = ssa_mul_map.erase(it);
2021 } else {
2022 ++it;
2023 }
2024 }
2025 }
2026
2027 if (is_candidate_multiply &&
2028 (GetRawUseCount(mir->ssa_rep->defs[0]) == 1) && (mir->next != nullptr)) {
2029 ssa_mul_map.Put(mir->ssa_rep->defs[0], mir);
2030 }
2031 }
2032}
2033
buzbee311ca162013-02-28 15:56:43 -08002034} // namespace art