blob: eb4915b821597f18525faaaa281d51ed0d701206 [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"
Mathieu Chartier736b5602015-09-02 14:54:11 -070020#include "class_linker-inl.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070021#include "dataflow_iterator-inl.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080022#include "dex/verified_method.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080023#include "dex_flags.h"
24#include "driver/compiler_driver.h"
25#include "driver/dex_compilation_unit.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010026#include "global_value_numbering.h"
Vladimir Marko7a01dc22015-01-02 17:00:44 +000027#include "gvn_dead_code_elimination.h"
buzbee311ca162013-02-28 15:56:43 -080028#include "local_value_numbering.h"
Vladimir Markoaf6925b2014-10-31 16:37:32 +000029#include "mir_field_info.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080030#include "mirror/string.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070031#include "quick/dex_file_method_inliner.h"
32#include "quick/dex_file_to_method_inliner_map.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070033#include "stack.h"
Mathieu Chartier736b5602015-09-02 14:54:11 -070034#include "thread-inl.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080035#include "type_inference.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010036#include "utils.h"
buzbee311ca162013-02-28 15:56:43 -080037
38namespace art {
39
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070040static unsigned int Predecessors(BasicBlock* bb) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +010041 return bb->predecessors.size();
buzbee311ca162013-02-28 15:56:43 -080042}
43
44/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070045void MIRGraph::SetConstant(int32_t ssa_reg, int32_t value) {
buzbee862a7602013-04-05 10:58:54 -070046 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080047 constant_values_[ssa_reg] = value;
Vladimir Marko066f9e42015-01-16 16:04:43 +000048 reg_location_[ssa_reg].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080049}
50
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070051void MIRGraph::SetConstantWide(int32_t ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070052 is_constant_v_->SetBit(ssa_reg);
Serguei Katkov597da1f2014-07-15 17:25:46 +070053 is_constant_v_->SetBit(ssa_reg + 1);
buzbee311ca162013-02-28 15:56:43 -080054 constant_values_[ssa_reg] = Low32Bits(value);
55 constant_values_[ssa_reg + 1] = High32Bits(value);
Vladimir Marko066f9e42015-01-16 16:04:43 +000056 reg_location_[ssa_reg].is_const = true;
57 reg_location_[ssa_reg + 1].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080058}
59
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -080060void MIRGraph::DoConstantPropagation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080061 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080062
Mathieu Chartier2cebb242015-04-21 16:50:40 -070063 for (mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070064 // Skip pass if BB has MIR without SSA representation.
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070065 if (mir->ssa_rep == nullptr) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070066 return;
67 }
68
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070069 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -080070
Ian Rogers29a26482014-05-02 15:27:29 -070071 MIR::DecodedInstruction* d_insn = &mir->dalvikInsn;
buzbee311ca162013-02-28 15:56:43 -080072
73 if (!(df_attributes & DF_HAS_DEFS)) continue;
74
75 /* Handle instructions that set up constants directly */
76 if (df_attributes & DF_SETS_CONST) {
77 if (df_attributes & DF_DA) {
78 int32_t vB = static_cast<int32_t>(d_insn->vB);
79 switch (d_insn->opcode) {
80 case Instruction::CONST_4:
81 case Instruction::CONST_16:
82 case Instruction::CONST:
83 SetConstant(mir->ssa_rep->defs[0], vB);
84 break;
85 case Instruction::CONST_HIGH16:
86 SetConstant(mir->ssa_rep->defs[0], vB << 16);
87 break;
88 case Instruction::CONST_WIDE_16:
89 case Instruction::CONST_WIDE_32:
90 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
91 break;
92 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070093 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080094 break;
95 case Instruction::CONST_WIDE_HIGH16:
96 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
97 break;
98 default:
99 break;
100 }
101 }
102 /* Handle instructions that set up constants directly */
103 } else if (df_attributes & DF_IS_MOVE) {
104 int i;
105
106 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -0700107 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -0800108 }
109 /* Move a register holding a constant to another register */
110 if (i == mir->ssa_rep->num_uses) {
111 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
112 if (df_attributes & DF_A_WIDE) {
113 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
114 }
115 }
116 }
117 }
118 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -0800119}
120
buzbee311ca162013-02-28 15:56:43 -0800121/* Advance to next strictly dominated MIR node in an extended basic block */
buzbee0d829482013-10-11 15:24:55 -0700122MIR* MIRGraph::AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800123 BasicBlock* bb = *p_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 if (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800125 mir = mir->next;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 while (mir == nullptr) {
buzbee0d829482013-10-11 15:24:55 -0700127 bb = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700128 if ((bb == nullptr) || Predecessors(bb) != 1) {
Serguei Katkovea392162015-01-29 17:08:05 +0600129 // mir is null and we cannot proceed further.
130 break;
buzbee311ca162013-02-28 15:56:43 -0800131 } else {
Serguei Katkovea392162015-01-29 17:08:05 +0600132 *p_bb = bb;
133 mir = bb->first_mir_insn;
buzbee311ca162013-02-28 15:56:43 -0800134 }
135 }
136 }
137 return mir;
138}
139
140/*
141 * To be used at an invoke mir. If the logically next mir node represents
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700142 * a move-result, return it. Else, return nullptr. If a move-result exists,
buzbee311ca162013-02-28 15:56:43 -0800143 * it is required to immediately follow the invoke with no intervening
144 * opcodes or incoming arcs. However, if the result of the invoke is not
145 * used, a move-result may not be present.
146 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700147MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800148 BasicBlock* tbb = bb;
149 mir = AdvanceMIR(&tbb, mir);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700150 while (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800151 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
152 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
153 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
154 break;
155 }
156 // Keep going if pseudo op, otherwise terminate
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700157 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800158 mir = AdvanceMIR(&tbb, mir);
buzbee35ba7f32014-05-31 08:59:01 -0700159 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700160 mir = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800161 }
162 }
163 return mir;
164}
165
buzbee0d829482013-10-11 15:24:55 -0700166BasicBlock* MIRGraph::NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800167 if (bb->block_type == kDead) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700168 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800169 }
170 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
171 || (bb->block_type == kExitBlock));
buzbee0d829482013-10-11 15:24:55 -0700172 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
173 BasicBlock* bb_fall_through = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700174 if (((bb_fall_through == nullptr) && (bb_taken != nullptr)) &&
buzbee0d829482013-10-11 15:24:55 -0700175 ((bb_taken->block_type == kDalvikByteCode) || (bb_taken->block_type == kExitBlock))) {
buzbeecbcfaf32013-08-19 07:37:40 -0700176 // Follow simple unconditional branches.
buzbee0d829482013-10-11 15:24:55 -0700177 bb = bb_taken;
buzbeecbcfaf32013-08-19 07:37:40 -0700178 } else {
179 // Follow simple fallthrough
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180 bb = (bb_taken != nullptr) ? nullptr : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700181 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (bb == nullptr || (Predecessors(bb) != 1)) {
183 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800184 }
185 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
186 return bb;
187}
188
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700189static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700190 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800191 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
192 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
193 if (mir->ssa_rep->uses[i] == ssa_name) {
194 return mir;
195 }
196 }
197 }
198 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700199 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800200}
201
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700202static SelectInstructionKind SelectKind(MIR* mir) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700203 // Work with the case when mir is null.
Chao-ying Fu8ac41af2014-10-01 16:53:04 -0700204 if (mir == nullptr) {
205 return kSelectNone;
206 }
buzbee311ca162013-02-28 15:56:43 -0800207 switch (mir->dalvikInsn.opcode) {
208 case Instruction::MOVE:
209 case Instruction::MOVE_OBJECT:
210 case Instruction::MOVE_16:
211 case Instruction::MOVE_OBJECT_16:
212 case Instruction::MOVE_FROM16:
213 case Instruction::MOVE_OBJECT_FROM16:
214 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700215 case Instruction::CONST:
216 case Instruction::CONST_4:
217 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800218 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700219 case Instruction::GOTO:
220 case Instruction::GOTO_16:
221 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800222 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700223 default:
224 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800225 }
buzbee311ca162013-02-28 15:56:43 -0800226}
227
Vladimir Markoa1a70742014-03-03 10:28:05 +0000228static constexpr ConditionCode kIfCcZConditionCodes[] = {
229 kCondEq, kCondNe, kCondLt, kCondGe, kCondGt, kCondLe
230};
231
Andreas Gampe785d2f22014-11-03 22:57:30 -0800232static_assert(arraysize(kIfCcZConditionCodes) == Instruction::IF_LEZ - Instruction::IF_EQZ + 1,
233 "if_ccz_ccodes_size1");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000234
Vladimir Markoa1a70742014-03-03 10:28:05 +0000235static constexpr ConditionCode ConditionCodeForIfCcZ(Instruction::Code opcode) {
236 return kIfCcZConditionCodes[opcode - Instruction::IF_EQZ];
237}
238
Andreas Gampe785d2f22014-11-03 22:57:30 -0800239static_assert(ConditionCodeForIfCcZ(Instruction::IF_EQZ) == kCondEq, "if_eqz ccode");
240static_assert(ConditionCodeForIfCcZ(Instruction::IF_NEZ) == kCondNe, "if_nez ccode");
241static_assert(ConditionCodeForIfCcZ(Instruction::IF_LTZ) == kCondLt, "if_ltz ccode");
242static_assert(ConditionCodeForIfCcZ(Instruction::IF_GEZ) == kCondGe, "if_gez ccode");
243static_assert(ConditionCodeForIfCcZ(Instruction::IF_GTZ) == kCondGt, "if_gtz ccode");
244static_assert(ConditionCodeForIfCcZ(Instruction::IF_LEZ) == kCondLe, "if_lez ccode");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000245
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700246int MIRGraph::GetSSAUseCount(int s_reg) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100247 DCHECK_LT(static_cast<size_t>(s_reg), ssa_subscripts_.size());
248 return raw_use_counts_[s_reg];
buzbee311ca162013-02-28 15:56:43 -0800249}
250
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700251size_t MIRGraph::GetNumBytesForSpecialTemps() const {
252 // This logic is written with assumption that Method* is only special temp.
253 DCHECK_EQ(max_available_special_compiler_temps_, 1u);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700254 return InstructionSetPointerSize(cu_->instruction_set);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800255}
256
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700257size_t MIRGraph::GetNumAvailableVRTemps() {
258 // First take into account all temps reserved for backend.
259 if (max_available_non_special_compiler_temps_ < reserved_temps_for_backend_) {
260 return 0;
261 }
262
263 // Calculate remaining ME temps available.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700264 size_t remaining_me_temps = max_available_non_special_compiler_temps_ -
265 reserved_temps_for_backend_;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700266
267 if (num_non_special_compiler_temps_ >= remaining_me_temps) {
268 return 0;
269 } else {
270 return remaining_me_temps - num_non_special_compiler_temps_;
271 }
272}
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000273
274// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800275static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700276 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000277 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800278
279CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700280 // Once the compiler temps have been committed, new ones cannot be requested anymore.
281 DCHECK_EQ(compiler_temps_committed_, false);
282 // Make sure that reserved for BE set is sane.
283 DCHECK_LE(reserved_temps_for_backend_, max_available_non_special_compiler_temps_);
284
285 bool verbose = cu_->verbose;
286 const char* ct_type_str = nullptr;
287
288 if (verbose) {
289 switch (ct_type) {
290 case kCompilerTempBackend:
291 ct_type_str = "backend";
292 break;
293 case kCompilerTempSpecialMethodPtr:
294 ct_type_str = "method*";
295 break;
296 case kCompilerTempVR:
297 ct_type_str = "VR";
298 break;
299 default:
300 ct_type_str = "unknown";
301 break;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800302 }
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700303 LOG(INFO) << "CompilerTemps: A compiler temp of type " << ct_type_str << " that is "
304 << (wide ? "wide is being requested." : "not wide is being requested.");
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800305 }
306
307 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000308 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800309
310 // Create the type of temp requested. Special temps need special handling because
311 // they have a specific virtual register assignment.
312 if (ct_type == kCompilerTempSpecialMethodPtr) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700313 // This has a special location on stack which is 32-bit or 64-bit depending
314 // on mode. However, we don't want to overlap with non-special section
315 // and thus even for 64-bit, we allow only a non-wide temp to be requested.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800316 DCHECK_EQ(wide, false);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800317
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700318 // The vreg is always the first special temp for method ptr.
319 compiler_temp->v_reg = GetFirstSpecialTempVR();
320
Mathieu Chartiere401d142015-04-22 13:56:20 -0700321 CHECK(reg_location_ == nullptr);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700322 } else if (ct_type == kCompilerTempBackend) {
323 requested_backend_temp_ = true;
324
325 // Make sure that we are not exceeding temps reserved for BE.
326 // Since VR temps cannot be requested once the BE temps are requested, we
327 // allow reservation of VR temps as well for BE. We
328 size_t available_temps = reserved_temps_for_backend_ + GetNumAvailableVRTemps();
Vladimir Markocc234812015-04-07 09:36:09 +0100329 size_t needed_temps = wide ? 2u : 1u;
330 if (available_temps < needed_temps) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700331 if (verbose) {
Vladimir Markocc234812015-04-07 09:36:09 +0100332 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
333 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700334 }
335 return nullptr;
336 }
337
338 // Update the remaining reserved temps since we have now used them.
339 // Note that the code below is actually subtracting to remove them from reserve
340 // once they have been claimed. It is careful to not go below zero.
Vladimir Markocc234812015-04-07 09:36:09 +0100341 reserved_temps_for_backend_ =
342 std::max(reserved_temps_for_backend_, needed_temps) - needed_temps;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700343
344 // The new non-special compiler temp must receive a unique v_reg.
345 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
346 num_non_special_compiler_temps_++;
347 } else if (ct_type == kCompilerTempVR) {
348 // Once we start giving out BE temps, we don't allow anymore ME temps to be requested.
349 // This is done in order to prevent problems with ssa since these structures are allocated
350 // and managed by the ME.
351 DCHECK_EQ(requested_backend_temp_, false);
352
353 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
354 size_t available_temps = GetNumAvailableVRTemps();
355 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
356 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700357 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
358 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700359 }
360 return nullptr;
361 }
362
363 // The new non-special compiler temp must receive a unique v_reg.
364 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
365 num_non_special_compiler_temps_++;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800366 } else {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700367 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << ct_type_str << ".";
368 }
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800369
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700370 // We allocate an sreg as well to make developer life easier.
371 // However, if this is requested from an ME pass that will recalculate ssa afterwards,
372 // this sreg is no longer valid. The caller should be aware of this.
373 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
374
375 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700376 LOG(INFO) << "CompilerTemps: New temp of type " << ct_type_str << " with v"
377 << compiler_temp->v_reg << " and s" << compiler_temp->s_reg_low << " has been created.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700378 }
379
380 if (wide) {
381 // Only non-special temps are handled as wide for now.
382 // Note that the number of non special temps is incremented below.
383 DCHECK(ct_type == kCompilerTempBackend || ct_type == kCompilerTempVR);
384
385 // Ensure that the two registers are consecutive.
386 int ssa_reg_low = compiler_temp->s_reg_low;
387 int ssa_reg_high = AddNewSReg(compiler_temp->v_reg + 1);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800388 num_non_special_compiler_temps_++;
389
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700390 if (verbose) {
391 LOG(INFO) << "CompilerTemps: The wide part of temp of type " << ct_type_str << " is v"
392 << compiler_temp->v_reg + 1 << " and s" << ssa_reg_high << ".";
393 }
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700394
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700395 if (reg_location_ != nullptr) {
396 reg_location_[ssa_reg_high] = temp_loc;
397 reg_location_[ssa_reg_high].high_word = true;
398 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
399 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800400 }
401 }
402
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700403 // If the register locations have already been allocated, add the information
404 // about the temp. We will not overflow because they have been initialized
405 // to support the maximum number of temps. For ME temps that have multiple
406 // ssa versions, the structures below will be expanded on the post pass cleanup.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800407 if (reg_location_ != nullptr) {
408 int ssa_reg_low = compiler_temp->s_reg_low;
409 reg_location_[ssa_reg_low] = temp_loc;
410 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
411 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800412 }
413
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800414 return compiler_temp;
415}
buzbee311ca162013-02-28 15:56:43 -0800416
Vladimir Markocc234812015-04-07 09:36:09 +0100417void MIRGraph::RemoveLastCompilerTemp(CompilerTempType ct_type, bool wide, CompilerTemp* temp) {
418 // Once the compiler temps have been committed, it's too late for any modifications.
419 DCHECK_EQ(compiler_temps_committed_, false);
420
421 size_t used_temps = wide ? 2u : 1u;
422
423 if (ct_type == kCompilerTempBackend) {
424 DCHECK(requested_backend_temp_);
425
426 // Make the temps available to backend again.
427 reserved_temps_for_backend_ += used_temps;
428 } else if (ct_type == kCompilerTempVR) {
429 DCHECK(!requested_backend_temp_);
430 } else {
431 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << static_cast<int>(ct_type);
432 }
433
434 // Reduce the number of non-special compiler temps.
435 DCHECK_LE(used_temps, num_non_special_compiler_temps_);
436 num_non_special_compiler_temps_ -= used_temps;
437
438 // Check that this was really the last temp.
439 DCHECK_EQ(static_cast<size_t>(temp->v_reg),
440 GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_);
441
442 if (cu_->verbose) {
443 LOG(INFO) << "Last temporary has been removed.";
444 }
445}
446
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000447static bool EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
448 bool is_taken;
449 switch (opcode) {
450 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
451 case Instruction::IF_NE: is_taken = (src1 != src2); break;
452 case Instruction::IF_LT: is_taken = (src1 < src2); break;
453 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
454 case Instruction::IF_GT: is_taken = (src1 > src2); break;
455 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
456 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
457 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
458 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
459 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
460 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
461 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
462 default:
463 LOG(FATAL) << "Unexpected opcode " << opcode;
464 UNREACHABLE();
465 }
466 return is_taken;
467}
468
buzbee311ca162013-02-28 15:56:43 -0800469/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700470bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800471 if (bb->block_type == kDead) {
472 return true;
473 }
Ningsheng Jiana262f772014-11-25 16:48:07 +0800474 // Currently multiply-accumulate backend supports are only available on arm32 and arm64.
475 if (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2) {
476 MultiplyAddOpt(bb);
477 }
Vladimir Marko415ac882014-09-30 18:09:14 +0100478 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kLocalValueNumbering)) == 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100479 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100480 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700481 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800482 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100483 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko415ac882014-09-30 18:09:14 +0100484 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get(),
485 GlobalValueNumbering::kModeLvn));
Vladimir Markob19955d2014-07-29 12:04:10 +0100486 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
487 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800488 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700489 while (bb != nullptr) {
490 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800491 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800492 if (use_lvn) {
493 local_valnum->GetValueNumber(mir);
494 }
buzbee311ca162013-02-28 15:56:43 -0800495 // Look for interesting opcodes, skip otherwise
496 Instruction::Code opcode = mir->dalvikInsn.opcode;
497 switch (opcode) {
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000498 case Instruction::IF_EQ:
499 case Instruction::IF_NE:
500 case Instruction::IF_LT:
501 case Instruction::IF_GE:
502 case Instruction::IF_GT:
503 case Instruction::IF_LE:
504 if (!IsConst(mir->ssa_rep->uses[1])) {
505 break;
506 }
507 FALLTHROUGH_INTENDED;
508 case Instruction::IF_EQZ:
509 case Instruction::IF_NEZ:
510 case Instruction::IF_LTZ:
511 case Instruction::IF_GEZ:
512 case Instruction::IF_GTZ:
513 case Instruction::IF_LEZ:
514 // Result known at compile time?
515 if (IsConst(mir->ssa_rep->uses[0])) {
516 int32_t rhs = (mir->ssa_rep->num_uses == 2) ? ConstantValue(mir->ssa_rep->uses[1]) : 0;
517 bool is_taken = EvaluateBranch(opcode, ConstantValue(mir->ssa_rep->uses[0]), rhs);
518 BasicBlockId edge_to_kill = is_taken ? bb->fall_through : bb->taken;
519 if (is_taken) {
520 // Replace with GOTO.
521 bb->fall_through = NullBasicBlockId;
522 mir->dalvikInsn.opcode = Instruction::GOTO;
523 mir->dalvikInsn.vA =
524 IsInstructionIfCc(opcode) ? mir->dalvikInsn.vC : mir->dalvikInsn.vB;
525 } else {
526 // Make NOP.
527 bb->taken = NullBasicBlockId;
528 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
529 }
530 mir->ssa_rep->num_uses = 0;
531 BasicBlock* successor_to_unlink = GetBasicBlock(edge_to_kill);
532 successor_to_unlink->ErasePredecessor(bb->id);
Vladimir Marko341e4252014-12-19 10:29:51 +0000533 // We have changed the graph structure.
534 dfs_orders_up_to_date_ = false;
535 domination_up_to_date_ = false;
536 topological_order_up_to_date_ = false;
537 // Keep MIR SSA rep, the worst that can happen is a Phi with just 1 input.
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000538 }
539 break;
buzbee311ca162013-02-28 15:56:43 -0800540 case Instruction::CMPL_FLOAT:
541 case Instruction::CMPL_DOUBLE:
542 case Instruction::CMPG_FLOAT:
543 case Instruction::CMPG_DOUBLE:
544 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700545 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800546 // Bitcode doesn't allow this optimization.
547 break;
548 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700549 if (mir->next != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800550 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800551 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700552 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800553 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
554 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000555 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700556 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800557 case Instruction::CMPL_FLOAT:
558 mir_next->dalvikInsn.opcode =
559 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
560 break;
561 case Instruction::CMPL_DOUBLE:
562 mir_next->dalvikInsn.opcode =
563 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
564 break;
565 case Instruction::CMPG_FLOAT:
566 mir_next->dalvikInsn.opcode =
567 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
568 break;
569 case Instruction::CMPG_DOUBLE:
570 mir_next->dalvikInsn.opcode =
571 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
572 break;
573 case Instruction::CMP_LONG:
574 mir_next->dalvikInsn.opcode =
575 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
576 break;
577 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
578 }
579 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Zheng Xub218c852014-12-08 18:18:01 +0800580 // Clear use count of temp VR.
581 use_counts_[mir->ssa_rep->defs[0]] = 0;
582 raw_use_counts_[mir->ssa_rep->defs[0]] = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700583 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800584 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
585 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
buzbee311ca162013-02-28 15:56:43 -0800586 mir_next->ssa_rep->num_defs = 0;
587 mir->ssa_rep->num_uses = 0;
588 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700589 // Copy in the decoded instruction information for potential SSA re-creation.
590 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
591 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800592 }
593 }
594 break;
buzbee311ca162013-02-28 15:56:43 -0800595 default:
596 break;
597 }
598 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800599 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800600 // TUNING: expand to support IF_xx compare & branches
Elliott Hughes956af0f2014-12-11 14:34:28 -0800601 if ((cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100602 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000603 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700604 BasicBlock* ft = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700605 DCHECK(ft != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700606 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
607 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800608
buzbee0d829482013-10-11 15:24:55 -0700609 BasicBlock* tk = GetBasicBlock(bb->taken);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700610 DCHECK(tk != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700611 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
612 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800613
614 /*
615 * In the select pattern, the taken edge goes to a block that unconditionally
616 * transfers to the rejoin block and the fall_though edge goes to a block that
617 * unconditionally falls through to the rejoin block.
618 */
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700619 if ((tk_ft == nullptr) && (ft_tk == nullptr) && (tk_tk == ft_ft) &&
buzbee311ca162013-02-28 15:56:43 -0800620 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
621 /*
Vladimir Marko8b858e12014-11-27 14:52:37 +0000622 * Okay - we have the basic diamond shape.
buzbee311ca162013-02-28 15:56:43 -0800623 */
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100624
625 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800626 // Are the block bodies something we can handle?
627 if ((ft->first_mir_insn == ft->last_mir_insn) &&
628 (tk->first_mir_insn != tk->last_mir_insn) &&
629 (tk->first_mir_insn->next == tk->last_mir_insn) &&
630 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
631 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
632 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
633 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
634 // Almost there. Are the instructions targeting the same vreg?
635 MIR* if_true = tk->first_mir_insn;
636 MIR* if_false = ft->first_mir_insn;
637 // It's possible that the target of the select isn't used - skip those (rare) cases.
638 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700639 if ((phi != nullptr) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
buzbee311ca162013-02-28 15:56:43 -0800640 /*
641 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
642 * Phi node in the merge block and delete it (while using the SSA name
643 * of the merge as the target of the SELECT. Delete both taken and
644 * fallthrough blocks, and set fallthrough to merge block.
645 * NOTE: not updating other dataflow info (no longer used at this point).
646 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
647 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000648 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800649 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
650 bool const_form = (SelectKind(if_true) == kSelectConst);
651 if ((SelectKind(if_true) == kSelectMove)) {
652 if (IsConst(if_true->ssa_rep->uses[0]) &&
653 IsConst(if_false->ssa_rep->uses[0])) {
654 const_form = true;
655 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
656 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
657 }
658 }
659 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800660 /*
661 * TODO: If both constants are the same value, then instead of generating
662 * a select, we should simply generate a const bytecode. This should be
663 * considered after inlining which can lead to CFG of this form.
664 */
buzbee311ca162013-02-28 15:56:43 -0800665 // "true" set val in vB
666 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
667 // "false" set val in vC
668 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
669 } else {
670 DCHECK_EQ(SelectKind(if_true), kSelectMove);
671 DCHECK_EQ(SelectKind(if_false), kSelectMove);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000672 int32_t* src_ssa = arena_->AllocArray<int32_t>(3, kArenaAllocDFInfo);
buzbee311ca162013-02-28 15:56:43 -0800673 src_ssa[0] = mir->ssa_rep->uses[0];
674 src_ssa[1] = if_true->ssa_rep->uses[0];
675 src_ssa[2] = if_false->ssa_rep->uses[0];
676 mir->ssa_rep->uses = src_ssa;
677 mir->ssa_rep->num_uses = 3;
678 }
Vladimir Markoc91df2d2015-04-23 09:29:21 +0000679 AllocateSSADefData(mir, 1);
buzbee311ca162013-02-28 15:56:43 -0800680 /*
681 * There is usually a Phi node in the join block for our two cases. If the
682 * Phi node only contains our two cases as input, we will use the result
683 * SSA name of the Phi node as our select result and delete the Phi. If
684 * the Phi node has more than two operands, we will arbitrarily use the SSA
Vladimir Marko341e4252014-12-19 10:29:51 +0000685 * name of the "false" path, delete the SSA name of the "true" path from the
buzbee311ca162013-02-28 15:56:43 -0800686 * Phi node (and fix up the incoming arc list).
687 */
688 if (phi->ssa_rep->num_uses == 2) {
689 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000690 // Rather than changing the Phi to kMirOpNop, remove it completely.
691 // This avoids leaving other Phis after kMirOpNop (i.e. a non-Phi) insn.
692 tk_tk->RemoveMIR(phi);
693 int dead_false_def = if_false->ssa_rep->defs[0];
694 raw_use_counts_[dead_false_def] = use_counts_[dead_false_def] = 0;
buzbee311ca162013-02-28 15:56:43 -0800695 } else {
Vladimir Marko341e4252014-12-19 10:29:51 +0000696 int live_def = if_false->ssa_rep->defs[0];
buzbee311ca162013-02-28 15:56:43 -0800697 mir->ssa_rep->defs[0] = live_def;
buzbee311ca162013-02-28 15:56:43 -0800698 }
Vladimir Marko341e4252014-12-19 10:29:51 +0000699 int dead_true_def = if_true->ssa_rep->defs[0];
700 raw_use_counts_[dead_true_def] = use_counts_[dead_true_def] = 0;
Vladimir Marko6e071832015-03-25 11:13:39 +0000701 // Update ending vreg->sreg map for GC maps generation.
702 int def_vreg = SRegToVReg(mir->ssa_rep->defs[0]);
703 bb->data_flow_info->vreg_to_ssa_map_exit[def_vreg] = mir->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000704 // We want to remove ft and tk and link bb directly to ft_ft. First, we need
705 // to update all Phi inputs correctly with UpdatePredecessor(ft->id, bb->id)
706 // since the live_def above comes from ft->first_mir_insn (if_false).
707 DCHECK(if_false == ft->first_mir_insn);
708 ft_ft->UpdatePredecessor(ft->id, bb->id);
709 // Correct the rest of the links between bb, ft and ft_ft.
710 ft->ErasePredecessor(bb->id);
711 ft->fall_through = NullBasicBlockId;
712 bb->fall_through = ft_ft->id;
713 // Now we can kill tk and ft.
714 tk->Kill(this);
715 ft->Kill(this);
716 // NOTE: DFS order, domination info and topological order are still usable
717 // despite the newly dead blocks.
buzbee311ca162013-02-28 15:56:43 -0800718 }
719 }
720 }
721 }
722 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700723 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) :
724 nullptr;
buzbee311ca162013-02-28 15:56:43 -0800725 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100726 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100727 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
728 }
buzbee311ca162013-02-28 15:56:43 -0800729
buzbee311ca162013-02-28 15:56:43 -0800730 return true;
731}
732
buzbee311ca162013-02-28 15:56:43 -0800733/* Collect stats on number of checks removed */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700734void MIRGraph::CountChecks(class BasicBlock* bb) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700735 if (bb->data_flow_info != nullptr) {
736 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
737 if (mir->ssa_rep == nullptr) {
buzbee862a7602013-04-05 10:58:54 -0700738 continue;
buzbee311ca162013-02-28 15:56:43 -0800739 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700740 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700741 if (df_attributes & DF_HAS_NULL_CHKS) {
742 checkstats_->null_checks++;
743 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
744 checkstats_->null_checks_eliminated++;
745 }
746 }
747 if (df_attributes & DF_HAS_RANGE_CHKS) {
748 checkstats_->range_checks++;
749 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
750 checkstats_->range_checks_eliminated++;
751 }
buzbee311ca162013-02-28 15:56:43 -0800752 }
753 }
754 }
buzbee311ca162013-02-28 15:56:43 -0800755}
756
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700757/* Try to make common case the fallthrough path. */
buzbee0d829482013-10-11 15:24:55 -0700758bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700759 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback.
buzbee311ca162013-02-28 15:56:43 -0800760 if (!bb->explicit_throw) {
761 return false;
762 }
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700763
764 // If we visited it, we are done.
765 if (bb->visited) {
766 return false;
767 }
768 bb->visited = true;
769
buzbee311ca162013-02-28 15:56:43 -0800770 BasicBlock* walker = bb;
771 while (true) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700772 // Check termination conditions.
buzbee311ca162013-02-28 15:56:43 -0800773 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
774 break;
775 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100776 DCHECK(!walker->predecessors.empty());
777 BasicBlock* prev = GetBasicBlock(walker->predecessors[0]);
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700778
779 // If we visited the predecessor, we are done.
780 if (prev->visited) {
781 return false;
782 }
783 prev->visited = true;
784
buzbee311ca162013-02-28 15:56:43 -0800785 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700786 if (GetBasicBlock(prev->fall_through) == walker) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700787 // Already done - return.
buzbee311ca162013-02-28 15:56:43 -0800788 break;
789 }
buzbee0d829482013-10-11 15:24:55 -0700790 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700791 // Got one. Flip it and exit.
buzbee311ca162013-02-28 15:56:43 -0800792 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
793 switch (opcode) {
794 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
795 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
796 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
797 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
798 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
799 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
800 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
801 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
802 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
803 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
804 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
805 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
806 default: LOG(FATAL) << "Unexpected opcode " << opcode;
807 }
808 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700809 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800810 prev->taken = prev->fall_through;
811 prev->fall_through = t_bb;
812 break;
813 }
814 walker = prev;
815 }
816 return false;
817}
818
819/* Combine any basic blocks terminated by instructions that we now know can't throw */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700820void MIRGraph::CombineBlocks(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800821 // Loop here to allow combining a sequence of blocks
Vladimir Marko312eb252014-10-07 15:01:57 +0100822 while ((bb->block_type == kDalvikByteCode) &&
823 (bb->last_mir_insn != nullptr) &&
824 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) == kMirOpCheck)) {
825 MIR* mir = bb->last_mir_insn;
826 DCHECK(bb->first_mir_insn != nullptr);
827
Vladimir Marko315cc202014-12-18 17:01:02 +0000828 // Get the paired insn and check if it can still throw.
Vladimir Marko312eb252014-10-07 15:01:57 +0100829 MIR* throw_insn = mir->meta.throw_insn;
Vladimir Marko315cc202014-12-18 17:01:02 +0000830 if (CanThrow(throw_insn)) {
buzbee311ca162013-02-28 15:56:43 -0800831 break;
832 }
833
buzbee311ca162013-02-28 15:56:43 -0800834 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700835 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800836 DCHECK(!bb_next->catch_entry);
Vladimir Marko312eb252014-10-07 15:01:57 +0100837 DCHECK_EQ(bb_next->predecessors.size(), 1u);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700838
839 // Now move instructions from bb_next to bb. Start off with doing a sanity check
840 // that kMirOpCheck's throw instruction is first one in the bb_next.
buzbee311ca162013-02-28 15:56:43 -0800841 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700842 // Now move all instructions (throw instruction to last one) from bb_next to bb.
843 MIR* last_to_move = bb_next->last_mir_insn;
844 bb_next->RemoveMIRList(throw_insn, last_to_move);
845 bb->InsertMIRListAfter(bb->last_mir_insn, throw_insn, last_to_move);
846 // The kMirOpCheck instruction is not needed anymore.
847 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
848 bb->RemoveMIR(mir);
849
Vladimir Marko312eb252014-10-07 15:01:57 +0100850 // Before we overwrite successors, remove their predecessor links to bb.
851 bb_next->ErasePredecessor(bb->id);
852 if (bb->taken != NullBasicBlockId) {
853 DCHECK_EQ(bb->successor_block_list_type, kNotUsed);
854 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
855 // bb->taken will be overwritten below.
856 DCHECK_EQ(bb_taken->block_type, kExceptionHandling);
857 DCHECK_EQ(bb_taken->predecessors.size(), 1u);
858 DCHECK_EQ(bb_taken->predecessors[0], bb->id);
859 bb_taken->predecessors.clear();
860 bb_taken->block_type = kDead;
861 DCHECK(bb_taken->data_flow_info == nullptr);
862 } else {
863 DCHECK_EQ(bb->successor_block_list_type, kCatch);
864 for (SuccessorBlockInfo* succ_info : bb->successor_blocks) {
865 if (succ_info->block != NullBasicBlockId) {
866 BasicBlock* succ_bb = GetBasicBlock(succ_info->block);
867 DCHECK(succ_bb->catch_entry);
868 succ_bb->ErasePredecessor(bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100869 }
870 }
871 }
buzbee311ca162013-02-28 15:56:43 -0800872 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700873 bb->successor_block_list_type = bb_next->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100874 bb->successor_blocks.swap(bb_next->successor_blocks); // Swap instead of copying.
Vladimir Marko312eb252014-10-07 15:01:57 +0100875 bb_next->successor_block_list_type = kNotUsed;
buzbee311ca162013-02-28 15:56:43 -0800876 // Use the ending block linkage from the next block
877 bb->fall_through = bb_next->fall_through;
Vladimir Marko312eb252014-10-07 15:01:57 +0100878 bb_next->fall_through = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800879 bb->taken = bb_next->taken;
Vladimir Marko312eb252014-10-07 15:01:57 +0100880 bb_next->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800881 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900882 * If lower-half of pair of blocks to combine contained
883 * a return or a conditional branch or an explicit throw,
884 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800885 */
886 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900887 bb->conditional_branch = bb_next->conditional_branch;
888 bb->explicit_throw = bb_next->explicit_throw;
Vladimir Marko312eb252014-10-07 15:01:57 +0100889 // Merge the use_lvn flag.
890 bb->use_lvn |= bb_next->use_lvn;
891
892 // Kill the unused block.
893 bb_next->data_flow_info = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800894
895 /*
896 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
897 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
Vladimir Marko312eb252014-10-07 15:01:57 +0100898 * NOTE: GVN uses bb->data_flow_info->live_in_v which is unaffected by the block merge.
buzbee311ca162013-02-28 15:56:43 -0800899 */
900
Vladimir Marko312eb252014-10-07 15:01:57 +0100901 // Kill bb_next and remap now-dead id to parent.
buzbee311ca162013-02-28 15:56:43 -0800902 bb_next->block_type = kDead;
Vladimir Marko312eb252014-10-07 15:01:57 +0100903 bb_next->data_flow_info = nullptr; // Must be null for dead blocks. (Relied on by the GVN.)
buzbee1fd33462013-03-25 13:40:45 -0700904 block_id_map_.Overwrite(bb_next->id, bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100905 // Update predecessors in children.
906 ChildBlockIterator iter(bb, this);
907 for (BasicBlock* child = iter.Next(); child != nullptr; child = iter.Next()) {
908 child->UpdatePredecessor(bb_next->id, bb->id);
909 }
910
Vladimir Markoffda4992014-12-18 17:05:58 +0000911 // DFS orders, domination and topological order are not up to date anymore.
Vladimir Marko312eb252014-10-07 15:01:57 +0100912 dfs_orders_up_to_date_ = false;
Vladimir Markoffda4992014-12-18 17:05:58 +0000913 domination_up_to_date_ = false;
914 topological_order_up_to_date_ = false;
buzbee311ca162013-02-28 15:56:43 -0800915
916 // Now, loop back and see if we can keep going
917 }
buzbee311ca162013-02-28 15:56:43 -0800918}
919
Vladimir Marko67c72b82014-10-09 12:26:10 +0100920bool MIRGraph::EliminateNullChecksGate() {
921 if ((cu_->disable_opt & (1 << kNullCheckElimination)) != 0 ||
922 (merged_df_flags_ & DF_HAS_NULL_CHKS) == 0) {
923 return false;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000924 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100925
Vladimir Marko67c72b82014-10-09 12:26:10 +0100926 DCHECK(temp_scoped_alloc_.get() == nullptr);
927 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700928 temp_.nce.num_vregs = GetNumOfCodeAndTempVRs();
Vladimir Markof585e542014-11-21 13:41:32 +0000929 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
930 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000931 temp_.nce.ending_vregs_to_check_matrix =
932 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +0000933 std::fill_n(temp_.nce.ending_vregs_to_check_matrix, GetNumBlocks(), nullptr);
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700934
935 // reset MIR_MARK
936 AllNodesIterator iter(this);
937 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700938 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700939 mir->optimization_flags &= ~MIR_MARK;
940 }
941 }
942
Vladimir Marko67c72b82014-10-09 12:26:10 +0100943 return true;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000944}
945
buzbee1da1e2f2013-11-15 13:37:01 -0800946/*
Vladimir Marko67c72b82014-10-09 12:26:10 +0100947 * Eliminate unnecessary null checks for a basic block.
buzbee1da1e2f2013-11-15 13:37:01 -0800948 */
Vladimir Marko67c72b82014-10-09 12:26:10 +0100949bool MIRGraph::EliminateNullChecks(BasicBlock* bb) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100950 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
951 // Ignore the kExitBlock as well.
952 DCHECK(bb->first_mir_insn == nullptr);
953 return false;
954 }
buzbee311ca162013-02-28 15:56:43 -0800955
Vladimir Markof585e542014-11-21 13:41:32 +0000956 ArenaBitVector* vregs_to_check = temp_.nce.work_vregs_to_check;
Vladimir Marko67c72b82014-10-09 12:26:10 +0100957 /*
958 * Set initial state. Catch blocks don't need any special treatment.
959 */
960 if (bb->block_type == kEntryBlock) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100961 vregs_to_check->ClearAllBits();
Vladimir Marko67c72b82014-10-09 12:26:10 +0100962 // Assume all ins are objects.
963 for (uint16_t in_reg = GetFirstInVR();
964 in_reg < GetNumOfCodeVRs(); in_reg++) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100965 vregs_to_check->SetBit(in_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100966 }
967 if ((cu_->access_flags & kAccStatic) == 0) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100968 // If non-static method, mark "this" as non-null.
Vladimir Marko67c72b82014-10-09 12:26:10 +0100969 int this_reg = GetFirstInVR();
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100970 vregs_to_check->ClearBit(this_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100971 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100972 } else {
973 DCHECK_EQ(bb->block_type, kDalvikByteCode);
974 // Starting state is union of all incoming arcs.
975 bool copied_first = false;
976 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +0000977 if (temp_.nce.ending_vregs_to_check_matrix[pred_id] == nullptr) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100978 continue;
979 }
980 BasicBlock* pred_bb = GetBasicBlock(pred_id);
981 DCHECK(pred_bb != nullptr);
982 MIR* null_check_insn = nullptr;
Vladimir Markof11c4202015-06-19 12:58:22 +0100983 // Check to see if predecessor had an explicit null-check.
984 if (pred_bb->BranchesToSuccessorOnlyIfNotZero(bb->id)) {
985 // Remember the null check insn if there's no other predecessor requiring null check.
986 if (!copied_first || !vregs_to_check->IsBitSet(pred_bb->last_mir_insn->dalvikInsn.vA)) {
987 null_check_insn = pred_bb->last_mir_insn;
988 DCHECK(null_check_insn != nullptr);
Ian Rogers22fd6a02013-06-13 15:06:54 -0700989 }
990 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100991 if (!copied_first) {
992 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +0000993 vregs_to_check->Copy(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100994 } else {
Vladimir Markof585e542014-11-21 13:41:32 +0000995 vregs_to_check->Union(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100996 }
997 if (null_check_insn != nullptr) {
998 vregs_to_check->ClearBit(null_check_insn->dalvikInsn.vA);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100999 }
1000 }
1001 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
buzbee311ca162013-02-28 15:56:43 -08001002 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001003 // At this point, vregs_to_check shows which sregs have an object definition with
Vladimir Marko67c72b82014-10-09 12:26:10 +01001004 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -08001005
1006 // Walk through the instruction in the block, updating as necessary
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001007 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beylercc794c32014-05-02 09:34:13 -07001008 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -08001009
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -07001010 if ((df_attributes & DF_NULL_TRANSFER_N) != 0u) {
1011 // The algorithm was written in a phi agnostic way.
1012 continue;
1013 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001014
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001015 // Might need a null check?
1016 if (df_attributes & DF_HAS_NULL_CHKS) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001017 int src_vreg;
1018 if (df_attributes & DF_NULL_CHK_OUT0) {
1019 DCHECK_NE(df_attributes & DF_IS_INVOKE, 0u);
1020 src_vreg = mir->dalvikInsn.vC;
1021 } else if (df_attributes & DF_NULL_CHK_B) {
1022 DCHECK_NE(df_attributes & DF_REF_B, 0u);
1023 src_vreg = mir->dalvikInsn.vB;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001024 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001025 DCHECK_NE(df_attributes & DF_NULL_CHK_A, 0u);
1026 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1027 src_vreg = mir->dalvikInsn.vA;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001028 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001029 if (!vregs_to_check->IsBitSet(src_vreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001030 // Eliminate the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001031 mir->optimization_flags |= MIR_MARK;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001032 } else {
1033 // Do the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001034 mir->optimization_flags &= ~MIR_MARK;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001035 // Mark src_vreg as null-checked.
1036 vregs_to_check->ClearBit(src_vreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001037 }
1038 }
1039
1040 if ((df_attributes & DF_A_WIDE) ||
1041 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
1042 continue;
1043 }
1044
1045 /*
1046 * First, mark all object definitions as requiring null check.
1047 * Note: we can't tell if a CONST definition might be used as an object, so treat
1048 * them all as object definitions.
1049 */
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001050 if ((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A) ||
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001051 (df_attributes & DF_SETS_CONST)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001052 vregs_to_check->SetBit(mir->dalvikInsn.vA);
buzbee4db179d2013-10-23 12:16:39 -07001053 }
1054
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001055 // Then, remove mark from all object definitions we know are non-null.
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001056 if (df_attributes & DF_NON_NULL_DST) {
1057 // Mark target of NEW* as non-null
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001058 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1059 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001060 }
1061
buzbee311ca162013-02-28 15:56:43 -08001062 // Mark non-null returns from invoke-style NEW*
1063 if (df_attributes & DF_NON_NULL_RET) {
1064 MIR* next_mir = mir->next;
1065 // Next should be an MOVE_RESULT_OBJECT
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001066 if (UNLIKELY(next_mir == nullptr)) {
1067 // The MethodVerifier makes sure there's no MOVE_RESULT at the catch entry or branch
1068 // target, so the MOVE_RESULT cannot be broken away into another block.
1069 LOG(WARNING) << "Unexpected end of block following new";
1070 } else if (UNLIKELY(next_mir->dalvikInsn.opcode != Instruction::MOVE_RESULT_OBJECT)) {
1071 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee311ca162013-02-28 15:56:43 -08001072 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001073 // Mark as null checked.
1074 vregs_to_check->ClearBit(next_mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001075 }
1076 }
1077
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001078 // Propagate null check state on register copies.
1079 if (df_attributes & DF_NULL_TRANSFER_0) {
1080 DCHECK_EQ(df_attributes | ~(DF_DA | DF_REF_A | DF_UB | DF_REF_B), static_cast<uint64_t>(-1));
1081 if (vregs_to_check->IsBitSet(mir->dalvikInsn.vB)) {
1082 vregs_to_check->SetBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001083 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001084 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001085 }
1086 }
buzbee311ca162013-02-28 15:56:43 -08001087 }
1088
1089 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +00001090 bool nce_changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001091 ArenaBitVector* old_ending_ssa_regs_to_check = temp_.nce.ending_vregs_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001092 if (old_ending_ssa_regs_to_check == nullptr) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001093 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001094 nce_changed = vregs_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001095 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001096 // Create a new vregs_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001097 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1098 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001099 } else if (!vregs_to_check->SameBitsSet(old_ending_ssa_regs_to_check)) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001100 nce_changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001101 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
1102 temp_.nce.work_vregs_to_check = old_ending_ssa_regs_to_check; // Reuse for next BB.
buzbee311ca162013-02-28 15:56:43 -08001103 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001104 return nce_changed;
buzbee311ca162013-02-28 15:56:43 -08001105}
1106
Vladimir Marko67c72b82014-10-09 12:26:10 +01001107void MIRGraph::EliminateNullChecksEnd() {
1108 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001109 temp_.nce.num_vregs = 0u;
1110 temp_.nce.work_vregs_to_check = nullptr;
1111 temp_.nce.ending_vregs_to_check_matrix = nullptr;
Vladimir Marko67c72b82014-10-09 12:26:10 +01001112 DCHECK(temp_scoped_alloc_.get() != nullptr);
1113 temp_scoped_alloc_.reset();
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001114
1115 // converge MIR_MARK with MIR_IGNORE_NULL_CHECK
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001116 AllNodesIterator iter(this);
1117 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001118 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001119 constexpr int kMarkToIgnoreNullCheckShift = kMIRMark - kMIRIgnoreNullCheck;
Andreas Gampe785d2f22014-11-03 22:57:30 -08001120 static_assert(kMarkToIgnoreNullCheckShift > 0, "Not a valid right-shift");
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001121 uint16_t mirMarkAdjustedToIgnoreNullCheck =
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001122 (mir->optimization_flags & MIR_MARK) >> kMarkToIgnoreNullCheckShift;
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001123 mir->optimization_flags |= mirMarkAdjustedToIgnoreNullCheck;
1124 }
1125 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001126}
1127
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001128void MIRGraph::InferTypesStart() {
1129 DCHECK(temp_scoped_alloc_ != nullptr);
1130 temp_.ssa.ti = new (temp_scoped_alloc_.get()) TypeInference(this, temp_scoped_alloc_.get());
1131}
1132
Vladimir Marko67c72b82014-10-09 12:26:10 +01001133/*
1134 * Perform type and size inference for a basic block.
1135 */
1136bool MIRGraph::InferTypes(BasicBlock* bb) {
1137 if (bb->data_flow_info == nullptr) return false;
1138
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001139 DCHECK(temp_.ssa.ti != nullptr);
1140 return temp_.ssa.ti->Apply(bb);
1141}
Vladimir Marko67c72b82014-10-09 12:26:10 +01001142
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001143void MIRGraph::InferTypesEnd() {
1144 DCHECK(temp_.ssa.ti != nullptr);
1145 temp_.ssa.ti->Finish();
1146 delete temp_.ssa.ti;
1147 temp_.ssa.ti = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001148}
1149
1150bool MIRGraph::EliminateClassInitChecksGate() {
1151 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001152 (merged_df_flags_ & DF_CLINIT) == 0) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001153 return false;
1154 }
1155
Vladimir Markobfea9c22014-01-17 17:49:33 +00001156 DCHECK(temp_scoped_alloc_.get() == nullptr);
1157 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1158
1159 // 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 -07001160 const size_t end = (GetNumDalvikInsns() + 1u) / 2u;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001161 temp_.cice.indexes = temp_scoped_alloc_->AllocArray<uint16_t>(end, kArenaAllocGrowableArray);
Vladimir Markof585e542014-11-21 13:41:32 +00001162 std::fill_n(temp_.cice.indexes, end, 0xffffu);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001163
1164 uint32_t unique_class_count = 0u;
1165 {
1166 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
1167 // ScopedArenaAllocator.
1168
1169 // Embed the map value in the entry to save space.
1170 struct MapEntry {
1171 // Map key: the class identified by the declaring dex file and type index.
1172 const DexFile* declaring_dex_file;
1173 uint16_t declaring_class_idx;
1174 // Map value: index into bit vectors of classes requiring initialization checks.
1175 uint16_t index;
1176 };
1177 struct MapEntryComparator {
1178 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
1179 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
1180 return lhs.declaring_class_idx < rhs.declaring_class_idx;
1181 }
1182 return lhs.declaring_dex_file < rhs.declaring_dex_file;
1183 }
1184 };
1185
Vladimir Markobfea9c22014-01-17 17:49:33 +00001186 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +01001187 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
1188 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001189
1190 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1191 AllNodesIterator iter(this);
1192 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001193 if (bb->block_type == kDalvikByteCode) {
1194 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001195 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001196 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001197 if (!field_info.IsReferrersClass()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001198 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1199 MapEntry entry = {
1200 // Treat unresolved fields as if each had its own class.
1201 field_info.IsResolved() ? field_info.DeclaringDexFile()
1202 : nullptr,
1203 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1204 : field_info.FieldIndex(),
1205 static_cast<uint16_t>(class_to_index_map.size())
1206 };
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001207 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001208 // Using offset/2 for index into temp_.cice.indexes.
1209 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001210 }
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001211 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001212 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1213 DCHECK(method_info.IsStatic());
1214 if (method_info.FastPath() && !method_info.IsReferrersClass()) {
1215 MapEntry entry = {
1216 method_info.DeclaringDexFile(),
1217 method_info.DeclaringClassIndex(),
1218 static_cast<uint16_t>(class_to_index_map.size())
1219 };
1220 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001221 // Using offset/2 for index into temp_.cice.indexes.
1222 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001223 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001224 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001225 }
1226 }
1227 }
1228 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1229 }
1230
1231 if (unique_class_count == 0u) {
1232 // All SGET/SPUTs refer to initialized classes. Nothing to do.
Vladimir Markof585e542014-11-21 13:41:32 +00001233 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001234 temp_scoped_alloc_.reset();
1235 return false;
1236 }
1237
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001238 // 2 bits for each class: is class initialized, is class in dex cache.
Vladimir Markof585e542014-11-21 13:41:32 +00001239 temp_.cice.num_class_bits = 2u * unique_class_count;
1240 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1241 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001242 temp_.cice.ending_classes_to_check_matrix =
1243 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +00001244 std::fill_n(temp_.cice.ending_classes_to_check_matrix, GetNumBlocks(), nullptr);
1245 DCHECK_GT(temp_.cice.num_class_bits, 0u);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001246 return true;
1247}
1248
1249/*
1250 * Eliminate unnecessary class initialization checks for a basic block.
1251 */
1252bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1253 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001254 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
1255 // Ignore the kExitBlock as well.
1256 DCHECK(bb->first_mir_insn == nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001257 return false;
1258 }
1259
1260 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001261 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001262 */
Vladimir Markof585e542014-11-21 13:41:32 +00001263 ArenaBitVector* classes_to_check = temp_.cice.work_classes_to_check;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001264 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001265 if (bb->block_type == kEntryBlock) {
Vladimir Markof585e542014-11-21 13:41:32 +00001266 classes_to_check->SetInitialBits(temp_.cice.num_class_bits);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001267 } else {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001268 // Starting state is union of all incoming arcs.
1269 bool copied_first = false;
1270 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +00001271 if (temp_.cice.ending_classes_to_check_matrix[pred_id] == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001272 continue;
1273 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001274 if (!copied_first) {
1275 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001276 classes_to_check->Copy(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001277 } else {
Vladimir Markof585e542014-11-21 13:41:32 +00001278 classes_to_check->Union(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001279 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001280 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001281 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001282 }
1283 // At this point, classes_to_check shows which classes need clinit checks.
1284
1285 // Walk through the instruction in the block, updating as necessary
1286 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markof585e542014-11-21 13:41:32 +00001287 uint16_t index = temp_.cice.indexes[mir->offset / 2u];
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001288 if (index != 0xffffu) {
1289 bool check_initialization = false;
1290 bool check_dex_cache = false;
1291
1292 // NOTE: index != 0xffff does not guarantee that this is an SGET/SPUT/INVOKE_STATIC.
1293 // Dex instructions with width 1 can have the same offset/2.
1294
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001295 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001296 check_initialization = true;
1297 check_dex_cache = true;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001298 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001299 check_initialization = true;
1300 // NOTE: INVOKE_STATIC doesn't guarantee that the type will be in the dex cache.
1301 }
1302
1303 if (check_dex_cache) {
1304 uint32_t check_dex_cache_index = 2u * index + 1u;
1305 if (!classes_to_check->IsBitSet(check_dex_cache_index)) {
1306 // Eliminate the class init check.
1307 mir->optimization_flags |= MIR_CLASS_IS_IN_DEX_CACHE;
1308 } else {
1309 // Do the class init check.
1310 mir->optimization_flags &= ~MIR_CLASS_IS_IN_DEX_CACHE;
1311 }
1312 classes_to_check->ClearBit(check_dex_cache_index);
1313 }
1314 if (check_initialization) {
1315 uint32_t check_clinit_index = 2u * index;
1316 if (!classes_to_check->IsBitSet(check_clinit_index)) {
1317 // Eliminate the class init check.
1318 mir->optimization_flags |= MIR_CLASS_IS_INITIALIZED;
1319 } else {
1320 // Do the class init check.
1321 mir->optimization_flags &= ~MIR_CLASS_IS_INITIALIZED;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001322 }
1323 // Mark the class as initialized.
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001324 classes_to_check->ClearBit(check_clinit_index);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001325 }
1326 }
1327 }
1328
1329 // Did anything change?
1330 bool changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001331 ArenaBitVector* old_ending_classes_to_check = temp_.cice.ending_classes_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001332 if (old_ending_classes_to_check == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001333 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001334 changed = classes_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001335 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001336 // Create a new classes_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001337 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1338 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Marko5229cf12014-10-09 14:57:59 +01001339 } else if (!classes_to_check->Equal(old_ending_classes_to_check)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001340 changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001341 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
1342 temp_.cice.work_classes_to_check = old_ending_classes_to_check; // Reuse for next BB.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001343 }
1344 return changed;
1345}
1346
1347void MIRGraph::EliminateClassInitChecksEnd() {
1348 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001349 temp_.cice.num_class_bits = 0u;
1350 temp_.cice.work_classes_to_check = nullptr;
1351 temp_.cice.ending_classes_to_check_matrix = nullptr;
1352 DCHECK(temp_.cice.indexes != nullptr);
1353 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001354 DCHECK(temp_scoped_alloc_.get() != nullptr);
1355 temp_scoped_alloc_.reset();
1356}
1357
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001358static void DisableGVNDependentOptimizations(CompilationUnit* cu) {
1359 cu->disable_opt |= (1u << kGvnDeadCodeElimination);
1360}
1361
Vladimir Marko95a05972014-05-30 10:01:32 +01001362bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko415ac882014-09-30 18:09:14 +01001363 if (GlobalValueNumbering::Skip(cu_)) {
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001364 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001365 return false;
1366 }
1367
1368 DCHECK(temp_scoped_alloc_ == nullptr);
1369 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001370 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001371 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001372 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001373 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
Vladimir Markof585e542014-11-21 13:41:32 +00001374 DCHECK(temp_.gvn.gvn == nullptr);
1375 temp_.gvn.gvn = new (temp_scoped_alloc_.get()) GlobalValueNumbering(
1376 cu_, temp_scoped_alloc_.get(), GlobalValueNumbering::kModeGvn);
Vladimir Marko95a05972014-05-30 10:01:32 +01001377 return true;
1378}
1379
1380bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
Vladimir Markof585e542014-11-21 13:41:32 +00001381 DCHECK(temp_.gvn.gvn != nullptr);
1382 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001383 if (lvn != nullptr) {
1384 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1385 lvn->GetValueNumber(mir);
1386 }
1387 }
Vladimir Markof585e542014-11-21 13:41:32 +00001388 bool change = (lvn != nullptr) && temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001389 return change;
1390}
1391
1392void MIRGraph::ApplyGlobalValueNumberingEnd() {
1393 // Perform modifications.
Vladimir Markof585e542014-11-21 13:41:32 +00001394 DCHECK(temp_.gvn.gvn != nullptr);
1395 if (temp_.gvn.gvn->Good()) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001396 temp_.gvn.gvn->StartPostProcessing();
Vladimir Marko415ac882014-09-30 18:09:14 +01001397 if (max_nested_loops_ != 0u) {
Vladimir Marko415ac882014-09-30 18:09:14 +01001398 TopologicalSortIterator iter(this);
1399 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1400 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
Vladimir Markof585e542014-11-21 13:41:32 +00001401 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb, &allocator);
Vladimir Marko415ac882014-09-30 18:09:14 +01001402 if (lvn != nullptr) {
1403 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1404 lvn->GetValueNumber(mir);
1405 }
Vladimir Markof585e542014-11-21 13:41:32 +00001406 bool change = temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko415ac882014-09-30 18:09:14 +01001407 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001408 }
Vladimir Marko95a05972014-05-30 10:01:32 +01001409 }
1410 }
Vladimir Marko415ac882014-09-30 18:09:14 +01001411 // GVN was successful, running the LVN would be useless.
1412 cu_->disable_opt |= (1u << kLocalValueNumbering);
Vladimir Marko95a05972014-05-30 10:01:32 +01001413 } else {
1414 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001415 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001416 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001417}
1418
1419bool MIRGraph::EliminateDeadCodeGate() {
Vladimir Markoad677272015-04-20 10:48:13 +01001420 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0 || temp_.gvn.gvn == nullptr) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001421 return false;
1422 }
1423 DCHECK(temp_scoped_alloc_ != nullptr);
1424 temp_.gvn.dce = new (temp_scoped_alloc_.get()) GvnDeadCodeElimination(temp_.gvn.gvn,
1425 temp_scoped_alloc_.get());
1426 return true;
1427}
1428
1429bool MIRGraph::EliminateDeadCode(BasicBlock* bb) {
1430 DCHECK(temp_scoped_alloc_ != nullptr);
1431 DCHECK(temp_.gvn.gvn != nullptr);
1432 if (bb->block_type != kDalvikByteCode) {
1433 return false;
1434 }
1435 DCHECK(temp_.gvn.dce != nullptr);
1436 temp_.gvn.dce->Apply(bb);
1437 return false; // No need to repeat.
1438}
1439
1440void MIRGraph::EliminateDeadCodeEnd() {
Vladimir Markoad677272015-04-20 10:48:13 +01001441 if (kIsDebugBuild) {
1442 // DCE can make some previously dead vregs alive again. Make sure the obsolete
1443 // live-in information is not used anymore.
1444 AllNodesIterator iter(this);
1445 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1446 if (bb->data_flow_info != nullptr) {
1447 bb->data_flow_info->live_in_v = nullptr;
1448 }
1449 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001450 }
Vladimir Markoad677272015-04-20 10:48:13 +01001451}
1452
1453void MIRGraph::GlobalValueNumberingCleanup() {
Vladimir Markof7255502015-04-25 17:00:45 +01001454 // If the GVN didn't run, these pointers should be null and everything is effectively no-op.
Vladimir Markoad677272015-04-20 10:48:13 +01001455 delete temp_.gvn.dce;
1456 temp_.gvn.dce = nullptr;
Vladimir Markof585e542014-11-21 13:41:32 +00001457 delete temp_.gvn.gvn;
1458 temp_.gvn.gvn = nullptr;
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001459 temp_.gvn.ifield_ids = nullptr;
1460 temp_.gvn.sfield_ids = nullptr;
Vladimir Marko95a05972014-05-30 10:01:32 +01001461 temp_scoped_alloc_.reset();
1462}
1463
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001464void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1465 uint32_t method_index = invoke->meta.method_lowering_info;
Vladimir Markof585e542014-11-21 13:41:32 +00001466 if (temp_.smi.processed_indexes->IsBitSet(method_index)) {
1467 iget_or_iput->meta.ifield_lowering_info = temp_.smi.lowering_infos[method_index];
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001468 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1469 return;
1470 }
1471
1472 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1473 MethodReference target = method_info.GetTargetMethod();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001474 ScopedObjectAccess soa(Thread::Current());
1475 StackHandleScope<1> hs(soa.Self());
1476 Handle<mirror::DexCache> dex_cache(
1477 hs.NewHandle(cu_->class_linker->FindDexCache(hs.Self(), *target.dex_file)));
1478 DexCompilationUnit inlined_unit(cu_,
1479 cu_->class_loader,
1480 cu_->class_linker,
1481 *target.dex_file,
1482 nullptr /* code_item not used */,
1483 0u /* class_def_idx not used */,
1484 target.dex_method_index,
1485 0u /* access_flags not used */,
1486 nullptr /* verified_method not used */,
1487 dex_cache);
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001488 DexMemAccessType type = IGetOrIPutMemAccessType(iget_or_iput->dalvikInsn.opcode);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001489 MirIFieldLoweringInfo inlined_field_info(field_idx, type, false);
Mathieu Chartier736b5602015-09-02 14:54:11 -07001490 MirIFieldLoweringInfo::Resolve(soa, cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001491 DCHECK(inlined_field_info.IsResolved());
1492
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001493 uint32_t field_info_index = ifield_lowering_infos_.size();
1494 ifield_lowering_infos_.push_back(inlined_field_info);
Vladimir Markof585e542014-11-21 13:41:32 +00001495 temp_.smi.processed_indexes->SetBit(method_index);
1496 temp_.smi.lowering_infos[method_index] = field_info_index;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001497 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1498}
1499
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001500bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001501 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001502 method_lowering_infos_.size() == 0u) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001503 return false;
1504 }
1505 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1506 // This isn't the Quick compiler.
1507 return false;
1508 }
1509 return true;
1510}
1511
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001512void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001513 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1514 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1515
1516 DCHECK(temp_scoped_alloc_.get() == nullptr);
1517 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001518 temp_.smi.num_indexes = method_lowering_infos_.size();
1519 temp_.smi.processed_indexes = new (temp_scoped_alloc_.get()) ArenaBitVector(
1520 temp_scoped_alloc_.get(), temp_.smi.num_indexes, false, kBitMapMisc);
1521 temp_.smi.processed_indexes->ClearAllBits();
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001522 temp_.smi.lowering_infos =
1523 temp_scoped_alloc_->AllocArray<uint16_t>(temp_.smi.num_indexes, kArenaAllocGrowableArray);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001524}
1525
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001526void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001527 if (bb->block_type != kDalvikByteCode) {
1528 return;
1529 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001530 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001531 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001532 continue;
1533 }
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001534 if (!(mir->dalvikInsn.FlagsOf() & Instruction::kInvoke)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001535 continue;
1536 }
1537 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
Vladimir Marko87b7c522015-04-08 10:01:01 +01001538 if (!method_info.FastPath() || !method_info.IsSpecial()) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001539 continue;
1540 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001541
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001542 InvokeType sharp_type = method_info.GetSharpType();
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001543 if ((sharp_type != kDirect) && (sharp_type != kStatic)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001544 continue;
1545 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001546
1547 if (sharp_type == kStatic) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001548 bool needs_clinit = !method_info.IsClassInitialized() &&
1549 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) == 0);
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001550 if (needs_clinit) {
1551 continue;
1552 }
1553 }
1554
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001555 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1556 MethodReference target = method_info.GetTargetMethod();
1557 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1558 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001559 if (cu_->verbose || cu_->print_pass) {
1560 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001561 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index,
1562 *target.dex_file)
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001563 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1564 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001565 }
1566 }
1567 }
1568}
1569
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001570void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Markof585e542014-11-21 13:41:32 +00001571 // Clean up temporaries.
1572 DCHECK(temp_.smi.lowering_infos != nullptr);
1573 temp_.smi.lowering_infos = nullptr;
1574 temp_.smi.num_indexes = 0u;
1575 DCHECK(temp_.smi.processed_indexes != nullptr);
1576 temp_.smi.processed_indexes = nullptr;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001577 DCHECK(temp_scoped_alloc_.get() != nullptr);
1578 temp_scoped_alloc_.reset();
1579}
1580
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001581void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001582 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001583 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001584 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001585 AllNodesIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001586 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
buzbee311ca162013-02-28 15:56:43 -08001587 CountChecks(bb);
1588 }
1589 if (stats->null_checks > 0) {
1590 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1591 float checks = static_cast<float>(stats->null_checks);
1592 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1593 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1594 << (eliminated/checks) * 100.0 << "%";
1595 }
1596 if (stats->range_checks > 0) {
1597 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1598 float checks = static_cast<float>(stats->range_checks);
1599 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1600 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1601 << (eliminated/checks) * 100.0 << "%";
1602 }
1603}
1604
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001605bool MIRGraph::BuildExtendedBBList(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001606 if (bb->visited) return false;
1607 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1608 || (bb->block_type == kExitBlock))) {
1609 // Ignore special blocks
1610 bb->visited = true;
1611 return false;
1612 }
1613 // Must be head of extended basic block.
1614 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001615 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001616 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001617 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001618 // Visit blocks strictly dominated by this head.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001619 while (bb != nullptr) {
buzbee311ca162013-02-28 15:56:43 -08001620 bb->visited = true;
1621 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001622 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001623 bb = NextDominatedBlock(bb);
1624 }
buzbee1da1e2f2013-11-15 13:37:01 -08001625 if (terminated_by_return || do_local_value_numbering) {
1626 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001627 bb = start_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001628 while (bb != nullptr) {
buzbee1da1e2f2013-11-15 13:37:01 -08001629 bb->use_lvn = do_local_value_numbering;
1630 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001631 bb = NextDominatedBlock(bb);
1632 }
1633 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001634 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001635}
1636
Vladimir Markoffda4992014-12-18 17:05:58 +00001637void MIRGraph::BasicBlockOptimizationStart() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001638 if ((cu_->disable_opt & (1 << kLocalValueNumbering)) == 0) {
1639 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001640 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001641 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001642 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001643 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
1644 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001645}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001646
Vladimir Markoffda4992014-12-18 17:05:58 +00001647void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001648 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1649 ClearAllVisitedFlags();
1650 PreOrderDfsIterator iter2(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001651 for (BasicBlock* bb = iter2.Next(); bb != nullptr; bb = iter2.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001652 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001653 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001654 // Perform extended basic block optimizations.
1655 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1656 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1657 }
1658 } else {
1659 PreOrderDfsIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001660 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001661 BasicBlockOpt(bb);
1662 }
buzbee311ca162013-02-28 15:56:43 -08001663 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001664}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001665
Vladimir Markoffda4992014-12-18 17:05:58 +00001666void MIRGraph::BasicBlockOptimizationEnd() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001667 // Clean up after LVN.
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001668 temp_.gvn.ifield_ids = nullptr;
1669 temp_.gvn.sfield_ids = nullptr;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001670 temp_scoped_alloc_.reset();
buzbee311ca162013-02-28 15:56:43 -08001671}
1672
Jeff Hao848f70a2014-01-15 13:49:50 -08001673void MIRGraph::StringChange() {
1674 AllNodesIterator iter(this);
1675 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1676 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1677 // Look for new instance opcodes, skip otherwise
1678 Instruction::Code opcode = mir->dalvikInsn.opcode;
1679 if (opcode == Instruction::NEW_INSTANCE) {
1680 uint32_t type_idx = mir->dalvikInsn.vB;
1681 if (cu_->compiler_driver->IsStringTypeIndex(type_idx, cu_->dex_file)) {
Jeff Haodde98272015-06-17 16:04:26 -07001682 // Change NEW_INSTANCE into CONST_4 of 0
Jeff Hao848f70a2014-01-15 13:49:50 -08001683 mir->dalvikInsn.opcode = Instruction::CONST_4;
1684 mir->dalvikInsn.vB = 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08001685 }
1686 } else if ((opcode == Instruction::INVOKE_DIRECT) ||
1687 (opcode == Instruction::INVOKE_DIRECT_RANGE)) {
1688 uint32_t method_idx = mir->dalvikInsn.vB;
1689 DexFileMethodInliner* inliner =
1690 cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(cu_->dex_file);
1691 if (inliner->IsStringInitMethodIndex(method_idx)) {
1692 bool is_range = (opcode == Instruction::INVOKE_DIRECT_RANGE);
1693 uint32_t orig_this_reg = is_range ? mir->dalvikInsn.vC : mir->dalvikInsn.arg[0];
1694 // Remove this pointer from string init and change to static call.
1695 mir->dalvikInsn.vA--;
1696 if (!is_range) {
1697 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC;
1698 for (uint32_t i = 0; i < mir->dalvikInsn.vA; i++) {
1699 mir->dalvikInsn.arg[i] = mir->dalvikInsn.arg[i + 1];
1700 }
1701 } else {
1702 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC_RANGE;
1703 mir->dalvikInsn.vC++;
1704 }
1705 // Insert a move-result instruction to the original this pointer reg.
1706 MIR* move_result_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1707 move_result_mir->dalvikInsn.opcode = Instruction::MOVE_RESULT_OBJECT;
1708 move_result_mir->dalvikInsn.vA = orig_this_reg;
1709 move_result_mir->offset = mir->offset;
1710 move_result_mir->m_unit_index = mir->m_unit_index;
1711 bb->InsertMIRAfter(mir, move_result_mir);
1712 // Add additional moves if this pointer was copied to other registers.
1713 const VerifiedMethod* verified_method =
1714 cu_->compiler_driver->GetVerifiedMethod(cu_->dex_file, cu_->method_idx);
1715 DCHECK(verified_method != nullptr);
1716 const SafeMap<uint32_t, std::set<uint32_t>>& string_init_map =
1717 verified_method->GetStringInitPcRegMap();
1718 auto map_it = string_init_map.find(mir->offset);
1719 if (map_it != string_init_map.end()) {
1720 const std::set<uint32_t>& reg_set = map_it->second;
1721 for (auto set_it = reg_set.begin(); set_it != reg_set.end(); ++set_it) {
1722 MIR* move_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1723 move_mir->dalvikInsn.opcode = Instruction::MOVE_OBJECT;
1724 move_mir->dalvikInsn.vA = *set_it;
1725 move_mir->dalvikInsn.vB = orig_this_reg;
1726 move_mir->offset = mir->offset;
1727 move_mir->m_unit_index = mir->m_unit_index;
1728 bb->InsertMIRAfter(move_result_mir, move_mir);
1729 }
1730 }
1731 }
1732 }
1733 }
1734 }
1735}
1736
1737
Vladimir Marko8b858e12014-11-27 14:52:37 +00001738bool MIRGraph::EliminateSuspendChecksGate() {
Vladimir Markod29e8482015-07-22 17:50:37 +01001739 if (kLeafOptimization || // Incompatible (could create loops without suspend checks).
1740 (cu_->disable_opt & (1 << kSuspendCheckElimination)) != 0 || // Disabled.
Vladimir Marko8b858e12014-11-27 14:52:37 +00001741 GetMaxNestedLoops() == 0u || // Nothing to do.
1742 GetMaxNestedLoops() >= 32u || // Only 32 bits in suspend_checks_in_loops_[.].
1743 // Exclude 32 as well to keep bit shifts well-defined.
1744 !HasInvokes()) { // No invokes to actually eliminate any suspend checks.
1745 return false;
1746 }
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001747 suspend_checks_in_loops_ = arena_->AllocArray<uint32_t>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Marko8b858e12014-11-27 14:52:37 +00001748 return true;
1749}
1750
1751bool MIRGraph::EliminateSuspendChecks(BasicBlock* bb) {
1752 if (bb->block_type != kDalvikByteCode) {
1753 return false;
1754 }
1755 DCHECK_EQ(GetTopologicalSortOrderLoopHeadStack()->size(), bb->nesting_depth);
1756 if (bb->nesting_depth == 0u) {
1757 // Out of loops.
1758 DCHECK_EQ(suspend_checks_in_loops_[bb->id], 0u); // The array was zero-initialized.
1759 return false;
1760 }
1761 uint32_t suspend_checks_in_loops = (1u << bb->nesting_depth) - 1u; // Start with all loop heads.
1762 bool found_invoke = false;
1763 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko87b7c522015-04-08 10:01:01 +01001764 if ((IsInstructionInvoke(mir->dalvikInsn.opcode) ||
1765 IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) &&
1766 !GetMethodLoweringInfo(mir).IsIntrinsic()) {
Vladimir Marko8b858e12014-11-27 14:52:37 +00001767 // Non-intrinsic invoke, rely on a suspend point in the invoked method.
1768 found_invoke = true;
1769 break;
1770 }
1771 }
1772 if (!found_invoke) {
1773 // Intersect suspend checks from predecessors.
1774 uint16_t bb_topo_idx = topological_order_indexes_[bb->id];
1775 uint32_t pred_mask_union = 0u;
1776 for (BasicBlockId pred_id : bb->predecessors) {
1777 uint16_t pred_topo_idx = topological_order_indexes_[pred_id];
1778 if (pred_topo_idx < bb_topo_idx) {
1779 // Determine the loop depth of the predecessors relative to this block.
1780 size_t pred_loop_depth = topological_order_loop_head_stack_.size();
1781 while (pred_loop_depth != 0u &&
1782 pred_topo_idx < topological_order_loop_head_stack_[pred_loop_depth - 1].first) {
1783 --pred_loop_depth;
1784 }
1785 DCHECK_LE(pred_loop_depth, GetBasicBlock(pred_id)->nesting_depth);
1786 uint32_t pred_mask = (1u << pred_loop_depth) - 1u;
1787 // Intersect pred_mask bits in suspend_checks_in_loops with
1788 // suspend_checks_in_loops_[pred_id].
1789 uint32_t pred_loops_without_checks = pred_mask & ~suspend_checks_in_loops_[pred_id];
1790 suspend_checks_in_loops = suspend_checks_in_loops & ~pred_loops_without_checks;
1791 pred_mask_union |= pred_mask;
1792 }
1793 }
Vladimir Marko67c8c942015-06-08 16:39:02 +01001794 // DCHECK_EQ() may not hold for unnatural loop heads, so use DCHECK_GE().
1795 DCHECK_GE(((1u << (IsLoopHead(bb->id) ? bb->nesting_depth - 1u: bb->nesting_depth)) - 1u),
Vladimir Marko8b858e12014-11-27 14:52:37 +00001796 pred_mask_union);
1797 suspend_checks_in_loops &= pred_mask_union;
1798 }
1799 suspend_checks_in_loops_[bb->id] = suspend_checks_in_loops;
1800 if (suspend_checks_in_loops == 0u) {
1801 return false;
1802 }
1803 // Apply MIR_IGNORE_SUSPEND_CHECK if appropriate.
1804 if (bb->taken != NullBasicBlockId) {
1805 DCHECK(bb->last_mir_insn != nullptr);
1806 DCHECK(IsInstructionIfCc(bb->last_mir_insn->dalvikInsn.opcode) ||
1807 IsInstructionIfCcZ(bb->last_mir_insn->dalvikInsn.opcode) ||
1808 IsInstructionGoto(bb->last_mir_insn->dalvikInsn.opcode) ||
1809 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) >= kMirOpFusedCmplFloat &&
1810 static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) <= kMirOpFusedCmpLong));
1811 if (!IsSuspendCheckEdge(bb, bb->taken) &&
1812 (bb->fall_through == NullBasicBlockId || !IsSuspendCheckEdge(bb, bb->fall_through))) {
1813 bb->last_mir_insn->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
1814 }
1815 } else if (bb->fall_through != NullBasicBlockId && IsSuspendCheckEdge(bb, bb->fall_through)) {
1816 // We've got a fall-through suspend edge. Add an artificial GOTO to force suspend check.
1817 MIR* mir = NewMIR();
1818 mir->dalvikInsn.opcode = Instruction::GOTO;
1819 mir->dalvikInsn.vA = 0; // Branch offset.
1820 mir->offset = GetBasicBlock(bb->fall_through)->start_offset;
1821 mir->m_unit_index = current_method_;
1822 mir->ssa_rep = reinterpret_cast<SSARepresentation*>(
1823 arena_->Alloc(sizeof(SSARepresentation), kArenaAllocDFInfo)); // Zero-initialized.
1824 bb->AppendMIR(mir);
1825 std::swap(bb->fall_through, bb->taken); // The fall-through has become taken.
1826 }
1827 return true;
1828}
1829
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001830bool MIRGraph::CanThrow(MIR* mir) const {
Ningsheng Jiana262f772014-11-25 16:48:07 +08001831 if ((mir->dalvikInsn.FlagsOf() & Instruction::kThrow) == 0) {
1832 return false;
1833 }
1834 const int opt_flags = mir->optimization_flags;
1835 uint64_t df_attributes = GetDataFlowAttributes(mir);
1836
Vladimir Marko315cc202014-12-18 17:01:02 +00001837 // First, check if the insn can still throw NPE.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001838 if (((df_attributes & DF_HAS_NULL_CHKS) != 0) && ((opt_flags & MIR_IGNORE_NULL_CHECK) == 0)) {
1839 return true;
1840 }
Vladimir Marko315cc202014-12-18 17:01:02 +00001841
1842 // Now process specific instructions.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001843 if ((df_attributes & DF_IFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001844 // The IGET/IPUT family. We have processed the IGET/IPUT null check above.
1845 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1846 // If not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001847 const MirIFieldLoweringInfo& field_info = GetIFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001848 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
1849 return !fast;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001850 } else if ((df_attributes & DF_SFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001851 // The SGET/SPUT family. Check for potentially throwing class initialization.
1852 // Also, if not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001853 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001854 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
Ningsheng Jiana262f772014-11-25 16:48:07 +08001855 bool is_class_initialized = field_info.IsClassInitialized() ||
1856 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0);
Vladimir Marko315cc202014-12-18 17:01:02 +00001857 return !(fast && is_class_initialized);
1858 } else if ((df_attributes & DF_HAS_RANGE_CHKS) != 0) {
1859 // Only AGET/APUT have range checks. We have processed the AGET/APUT null check above.
1860 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1861 // Non-throwing only if range check has been eliminated.
1862 return ((opt_flags & MIR_IGNORE_RANGE_CHECK) == 0);
Vladimir Marko22fe45d2015-03-18 11:33:58 +00001863 } else if (mir->dalvikInsn.opcode == Instruction::CHECK_CAST &&
1864 (opt_flags & MIR_IGNORE_CHECK_CAST) != 0) {
1865 return false;
Vladimir Marko315cc202014-12-18 17:01:02 +00001866 } else if (mir->dalvikInsn.opcode == Instruction::ARRAY_LENGTH ||
Vladimir Marko315cc202014-12-18 17:01:02 +00001867 static_cast<int>(mir->dalvikInsn.opcode) == kMirOpNullCheck) {
1868 // No more checks for these (null check was processed above).
1869 return false;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001870 }
1871 return true;
1872}
1873
1874bool MIRGraph::HasAntiDependency(MIR* first, MIR* second) {
1875 DCHECK(first->ssa_rep != nullptr);
1876 DCHECK(second->ssa_rep != nullptr);
1877 if ((second->ssa_rep->num_defs > 0) && (first->ssa_rep->num_uses > 0)) {
1878 int vreg0 = SRegToVReg(second->ssa_rep->defs[0]);
1879 int vreg1 = (second->ssa_rep->num_defs == 2) ?
1880 SRegToVReg(second->ssa_rep->defs[1]) : INVALID_VREG;
1881 for (int i = 0; i < first->ssa_rep->num_uses; i++) {
1882 int32_t use = SRegToVReg(first->ssa_rep->uses[i]);
1883 if (use == vreg0 || use == vreg1) {
1884 return true;
1885 }
1886 }
1887 }
1888 return false;
1889}
1890
1891void MIRGraph::CombineMultiplyAdd(MIR* mul_mir, MIR* add_mir, bool mul_is_first_addend,
1892 bool is_wide, bool is_sub) {
1893 if (is_wide) {
1894 if (is_sub) {
1895 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubLong);
1896 } else {
1897 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddLong);
1898 }
1899 } else {
1900 if (is_sub) {
1901 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubInt);
1902 } else {
1903 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddInt);
1904 }
1905 }
1906 add_mir->ssa_rep->num_uses = is_wide ? 6 : 3;
1907 int32_t addend0 = INVALID_SREG;
1908 int32_t addend1 = INVALID_SREG;
1909 if (is_wide) {
1910 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[2] : add_mir->ssa_rep->uses[0];
1911 addend1 = mul_is_first_addend ? add_mir->ssa_rep->uses[3] : add_mir->ssa_rep->uses[1];
1912 } else {
1913 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[1] : add_mir->ssa_rep->uses[0];
1914 }
1915
1916 AllocateSSAUseData(add_mir, add_mir->ssa_rep->num_uses);
1917 add_mir->ssa_rep->uses[0] = mul_mir->ssa_rep->uses[0];
1918 add_mir->ssa_rep->uses[1] = mul_mir->ssa_rep->uses[1];
1919 // Clear the original multiply product ssa use count, as it is not used anymore.
1920 raw_use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1921 use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1922 if (is_wide) {
1923 DCHECK_EQ(add_mir->ssa_rep->num_uses, 6);
1924 add_mir->ssa_rep->uses[2] = mul_mir->ssa_rep->uses[2];
1925 add_mir->ssa_rep->uses[3] = mul_mir->ssa_rep->uses[3];
1926 add_mir->ssa_rep->uses[4] = addend0;
1927 add_mir->ssa_rep->uses[5] = addend1;
1928 raw_use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1929 use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1930 } else {
1931 DCHECK_EQ(add_mir->ssa_rep->num_uses, 3);
1932 add_mir->ssa_rep->uses[2] = addend0;
1933 }
1934 // Copy in the decoded instruction information.
1935 add_mir->dalvikInsn.vB = SRegToVReg(add_mir->ssa_rep->uses[0]);
1936 if (is_wide) {
1937 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[2]);
1938 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[4]);
1939 } else {
1940 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[1]);
1941 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[2]);
1942 }
1943 // Original multiply MIR is set to Nop.
1944 mul_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1945}
1946
1947void MIRGraph::MultiplyAddOpt(BasicBlock* bb) {
1948 if (bb->block_type == kDead) {
1949 return;
1950 }
1951 ScopedArenaAllocator allocator(&cu_->arena_stack);
1952 ScopedArenaSafeMap<uint32_t, MIR*> ssa_mul_map(std::less<uint32_t>(), allocator.Adapter());
1953 ScopedArenaSafeMap<uint32_t, MIR*>::iterator map_it;
1954 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1955 Instruction::Code opcode = mir->dalvikInsn.opcode;
1956 bool is_sub = true;
1957 bool is_candidate_multiply = false;
1958 switch (opcode) {
1959 case Instruction::MUL_INT:
1960 case Instruction::MUL_INT_2ADDR:
1961 is_candidate_multiply = true;
1962 break;
1963 case Instruction::MUL_LONG:
1964 case Instruction::MUL_LONG_2ADDR:
1965 if (cu_->target64) {
1966 is_candidate_multiply = true;
1967 }
1968 break;
1969 case Instruction::ADD_INT:
1970 case Instruction::ADD_INT_2ADDR:
1971 is_sub = false;
1972 FALLTHROUGH_INTENDED;
1973 case Instruction::SUB_INT:
1974 case Instruction::SUB_INT_2ADDR:
1975 if (((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end()) && !is_sub) {
1976 // a*b+c
1977 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1978 false /* is_wide */, false /* is_sub */);
1979 ssa_mul_map.erase(mir->ssa_rep->uses[0]);
1980 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[1])) != ssa_mul_map.end()) {
1981 // c+a*b or c-a*b
1982 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1983 false /* is_wide */, is_sub);
1984 ssa_mul_map.erase(map_it);
1985 }
1986 break;
1987 case Instruction::ADD_LONG:
1988 case Instruction::ADD_LONG_2ADDR:
1989 is_sub = false;
1990 FALLTHROUGH_INTENDED;
1991 case Instruction::SUB_LONG:
1992 case Instruction::SUB_LONG_2ADDR:
1993 if (!cu_->target64) {
1994 break;
1995 }
1996 if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end() && !is_sub) {
1997 // a*b+c
1998 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1999 true /* is_wide */, false /* is_sub */);
2000 ssa_mul_map.erase(map_it);
2001 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[2])) != ssa_mul_map.end()) {
2002 // c+a*b or c-a*b
2003 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
2004 true /* is_wide */, is_sub);
2005 ssa_mul_map.erase(map_it);
2006 }
2007 break;
2008 default:
2009 if (!ssa_mul_map.empty() && CanThrow(mir)) {
2010 // Should not combine multiply and add MIRs across potential exception.
2011 ssa_mul_map.clear();
2012 }
2013 break;
2014 }
2015
2016 // Exclude the case when an MIR writes a vreg which is previous candidate multiply MIR's uses.
2017 // It is because that current RA may allocate the same physical register to them. For this
2018 // kind of cases, the multiplier has been updated, we should not use updated value to the
2019 // multiply-add insn.
2020 if (ssa_mul_map.size() > 0) {
2021 for (auto it = ssa_mul_map.begin(); it != ssa_mul_map.end();) {
2022 MIR* mul = it->second;
2023 if (HasAntiDependency(mul, mir)) {
2024 it = ssa_mul_map.erase(it);
2025 } else {
2026 ++it;
2027 }
2028 }
2029 }
2030
2031 if (is_candidate_multiply &&
2032 (GetRawUseCount(mir->ssa_rep->defs[0]) == 1) && (mir->next != nullptr)) {
2033 ssa_mul_map.Put(mir->ssa_rep->defs[0], mir);
2034 }
2035 }
2036}
2037
buzbee311ca162013-02-28 15:56:43 -08002038} // namespace art