blob: d3911456fb221477e4a8920103df96fa2d0197a2 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 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
17#include "instruction_simplifier.h"
18
Calin Juravleacf735c2015-02-12 15:25:22 +000019#include "mirror/class-inl.h"
20#include "scoped_thread_state_change.h"
21
Nicolas Geoffray3c049742014-09-24 18:10:46 +010022namespace art {
23
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000024class InstructionSimplifierVisitor : public HGraphVisitor {
25 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000026 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Alexandre Rames188d4312015-04-09 18:30:21 +010027 : HGraphVisitor(graph),
28 stats_(stats) {}
29
30 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031
32 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010033 void RecordSimplification() {
34 simplification_occurred_ = true;
35 simplifications_at_current_position_++;
36 if (stats_) {
37 stats_->RecordStat(kInstructionSimplifications);
38 }
39 }
40
41 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000042 void VisitShift(HBinaryOperation* shift);
43
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000044 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
45 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010046 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
47 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010048 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
49 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000050 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000051 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000052 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080053 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000054 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000055 void VisitAdd(HAdd* instruction) OVERRIDE;
56 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040057 void VisitCondition(HCondition* instruction) OVERRIDE;
58 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
59 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
60 void VisitLessThan(HLessThan* condition) OVERRIDE;
61 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000062 void VisitDiv(HDiv* instruction) OVERRIDE;
63 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010064 void VisitNeg(HNeg* instruction) OVERRIDE;
65 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000066 void VisitOr(HOr* instruction) OVERRIDE;
67 void VisitShl(HShl* instruction) OVERRIDE;
68 void VisitShr(HShr* instruction) OVERRIDE;
69 void VisitSub(HSub* instruction) OVERRIDE;
70 void VisitUShr(HUShr* instruction) OVERRIDE;
71 void VisitXor(HXor* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010072 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +010073 void VisitFakeString(HFakeString* fake_string) OVERRIDE;
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +010074 bool IsDominatedByInputNullCheck(HInstruction* instr);
Calin Juravleacf735c2015-02-12 15:25:22 +000075
76 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010077 bool simplification_occurred_ = false;
78 int simplifications_at_current_position_ = 0;
79 // We ensure we do not loop infinitely. The value is a finger in the air guess
80 // that should allow enough simplification.
81 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000082};
83
Nicolas Geoffray3c049742014-09-24 18:10:46 +010084void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000085 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010086 visitor.Run();
87}
88
89void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010090 // Iterate in reverse post order to open up more simplifications to users
91 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010092 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
93 // The simplification of an instruction to another instruction may yield
94 // possibilities for other simplifications. So although we perform a reverse
95 // post order visit, we sometimes need to revisit an instruction index.
96 simplification_occurred_ = false;
97 VisitBasicBlock(it.Current());
98 if (simplification_occurred_ &&
99 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
100 // New simplifications may be applicable to the instruction at the
101 // current index, so don't advance the iterator.
102 continue;
103 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100104 simplifications_at_current_position_ = 0;
105 it.Advance();
106 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100107}
108
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000109namespace {
110
111bool AreAllBitsSet(HConstant* constant) {
112 return Int64FromConstant(constant) == -1;
113}
114
115} // namespace
116
Alexandre Rames188d4312015-04-09 18:30:21 +0100117// Returns true if the code was simplified to use only one negation operation
118// after the binary operation instead of one on each of the inputs.
119bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
120 DCHECK(binop->IsAdd() || binop->IsSub());
121 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
122 HNeg* left_neg = binop->GetLeft()->AsNeg();
123 HNeg* right_neg = binop->GetRight()->AsNeg();
124 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
125 !right_neg->HasOnlyOneNonEnvironmentUse()) {
126 return false;
127 }
128 // Replace code looking like
129 // NEG tmp1, a
130 // NEG tmp2, b
131 // ADD dst, tmp1, tmp2
132 // with
133 // ADD tmp, a, b
134 // NEG dst, tmp
135 binop->ReplaceInput(left_neg->GetInput(), 0);
136 binop->ReplaceInput(right_neg->GetInput(), 1);
137 left_neg->GetBlock()->RemoveInstruction(left_neg);
138 right_neg->GetBlock()->RemoveInstruction(right_neg);
139 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
140 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
141 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
142 RecordSimplification();
143 return true;
144}
145
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000146void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
147 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
148 HConstant* input_cst = instruction->GetConstantRight();
149 HInstruction* input_other = instruction->GetLeastConstantLeft();
150
Mark Mendellba56d062015-05-05 21:34:03 -0400151 if (input_cst != nullptr) {
152 if (input_cst->IsZero()) {
153 // Replace code looking like
154 // SHL dst, src, 0
155 // with
156 // src
157 instruction->ReplaceWith(input_other);
158 instruction->GetBlock()->RemoveInstruction(instruction);
159 } else if (instruction->IsShl() && input_cst->IsOne()) {
160 // Replace Shl looking like
161 // SHL dst, src, 1
162 // with
163 // ADD dst, src, src
164 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
165 input_other,
166 input_other);
167 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
168 RecordSimplification();
169 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000170 }
171}
172
Calin Juravle10e244f2015-01-26 18:54:32 +0000173void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
174 HInstruction* obj = null_check->InputAt(0);
175 if (!obj->CanBeNull()) {
176 null_check->ReplaceWith(obj);
177 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000178 if (stats_ != nullptr) {
179 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
180 }
181 }
182}
183
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100184bool InstructionSimplifierVisitor::IsDominatedByInputNullCheck(HInstruction* instr) {
185 HInstruction* input = instr->InputAt(0);
186 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
187 HInstruction* use = it.Current()->GetUser();
188 if (use->IsNullCheck() && use->StrictlyDominates(instr)) {
189 return true;
190 }
191 }
192 return false;
193}
194
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100195// Returns whether doing a type test between the class of `object` against `klass` has
196// a statically known outcome. The result of the test is stored in `outcome`.
197static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000198 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
199 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
200 ScopedObjectAccess soa(Thread::Current());
201 if (!obj_rti.IsValid()) {
202 // We run the simplifier before the reference type propagation so type info might not be
203 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100204 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000205 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100206
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100207 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle2e768302015-07-28 14:41:11 +0000208 DCHECK(class_rti.IsValid() && class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000209 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100210 *outcome = true;
211 return true;
212 } else if (obj_rti.IsExact()) {
213 // The test failed at compile time so will also fail at runtime.
214 *outcome = false;
215 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100216 } else if (!class_rti.IsInterface()
217 && !obj_rti.IsInterface()
218 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100219 // Different type hierarchy. The test will fail.
220 *outcome = false;
221 return true;
222 }
223 return false;
224}
225
226void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
227 HInstruction* object = check_cast->InputAt(0);
228 if (!object->CanBeNull() || IsDominatedByInputNullCheck(check_cast)) {
229 check_cast->ClearMustDoNullCheck();
230 }
231
232 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000233 check_cast->GetBlock()->RemoveInstruction(check_cast);
234 if (stats_ != nullptr) {
235 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
236 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100237 return;
238 }
239
240 bool outcome;
241 if (TypeCheckHasKnownOutcome(check_cast->InputAt(1)->AsLoadClass(), object, &outcome)) {
242 if (outcome) {
243 check_cast->GetBlock()->RemoveInstruction(check_cast);
244 if (stats_ != nullptr) {
245 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
246 }
247 } else {
248 // Don't do anything for exceptional cases for now. Ideally we should remove
249 // all instructions and blocks this instruction dominates.
250 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000251 }
252}
253
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100254void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100255 HInstruction* object = instruction->InputAt(0);
256 bool can_be_null = true;
257 if (!object->CanBeNull() || IsDominatedByInputNullCheck(instruction)) {
258 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100259 instruction->ClearMustDoNullCheck();
260 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100261
262 HGraph* graph = GetGraph();
263 if (object->IsNullConstant()) {
264 instruction->ReplaceWith(graph->GetIntConstant(0));
265 instruction->GetBlock()->RemoveInstruction(instruction);
266 RecordSimplification();
267 return;
268 }
269
270 bool outcome;
271 if (TypeCheckHasKnownOutcome(instruction->InputAt(1)->AsLoadClass(), object, &outcome)) {
272 if (outcome && can_be_null) {
273 // Type test will succeed, we just need a null test.
274 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
275 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
276 instruction->ReplaceWith(test);
277 } else {
278 // We've statically determined the result of the instanceof.
279 instruction->ReplaceWith(graph->GetIntConstant(outcome));
280 }
281 RecordSimplification();
282 instruction->GetBlock()->RemoveInstruction(instruction);
283 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100284}
285
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100286void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
287 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
288 && !instruction->GetValue()->CanBeNull()) {
289 instruction->ClearValueCanBeNull();
290 }
291}
292
293void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
294 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
295 && !instruction->GetValue()->CanBeNull()) {
296 instruction->ClearValueCanBeNull();
297 }
298}
299
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000300void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100301 HBasicBlock* block = check->GetBlock();
302 // Currently always keep the suspend check at entry.
303 if (block->IsEntryBlock()) return;
304
305 // Currently always keep suspend checks at loop entry.
306 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
307 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
308 return;
309 }
310
311 // Remove the suspend check that was added at build time for the baseline
312 // compiler.
313 block->RemoveInstruction(check);
314}
315
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000316void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100317 HInstruction* input_const = equal->GetConstantRight();
318 if (input_const != nullptr) {
319 HInstruction* input_value = equal->GetLeastConstantLeft();
320 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
321 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100322 // We are comparing the boolean to a constant which is of type int and can
323 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100324 if (input_const->AsIntConstant()->IsOne()) {
325 // Replace (bool_value == true) with bool_value
326 equal->ReplaceWith(input_value);
327 block->RemoveInstruction(equal);
328 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100329 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100330 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100331 block->ReplaceAndRemoveInstructionWith(
332 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
333 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100334 } else {
335 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
336 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
337 block->RemoveInstruction(equal);
338 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100339 }
Mark Mendellc4701932015-04-10 13:18:51 -0400340 } else {
341 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100342 }
Mark Mendellc4701932015-04-10 13:18:51 -0400343 } else {
344 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100345 }
346}
347
David Brazdil0d13fee2015-04-17 14:52:19 +0100348void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
349 HInstruction* input_const = not_equal->GetConstantRight();
350 if (input_const != nullptr) {
351 HInstruction* input_value = not_equal->GetLeastConstantLeft();
352 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
353 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100354 // We are comparing the boolean to a constant which is of type int and can
355 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100356 if (input_const->AsIntConstant()->IsOne()) {
357 // Replace (bool_value != true) with !bool_value
358 block->ReplaceAndRemoveInstructionWith(
359 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
360 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100361 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100362 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100363 not_equal->ReplaceWith(input_value);
364 block->RemoveInstruction(not_equal);
365 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100366 } else {
367 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
368 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
369 block->RemoveInstruction(not_equal);
370 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100371 }
Mark Mendellc4701932015-04-10 13:18:51 -0400372 } else {
373 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100374 }
Mark Mendellc4701932015-04-10 13:18:51 -0400375 } else {
376 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100377 }
378}
379
380void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
381 HInstruction* parent = bool_not->InputAt(0);
382 if (parent->IsBooleanNot()) {
383 HInstruction* value = parent->InputAt(0);
384 // Replace (!(!bool_value)) with bool_value
385 bool_not->ReplaceWith(value);
386 bool_not->GetBlock()->RemoveInstruction(bool_not);
387 // It is possible that `parent` is dead at this point but we leave
388 // its removal to DCE for simplicity.
389 RecordSimplification();
390 }
391}
392
Mingyao Yang0304e182015-01-30 16:41:29 -0800393void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
394 HInstruction* input = instruction->InputAt(0);
395 // If the array is a NewArray with constant size, replace the array length
396 // with the constant instruction. This helps the bounds check elimination phase.
397 if (input->IsNewArray()) {
398 input = input->InputAt(0);
399 if (input->IsIntConstant()) {
400 instruction->ReplaceWith(input);
401 }
402 }
403}
404
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000405void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000406 HInstruction* value = instruction->GetValue();
407 if (value->GetType() != Primitive::kPrimNot) return;
408
409 if (value->IsArrayGet()) {
410 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
411 // If the code is just swapping elements in the array, no need for a type check.
412 instruction->ClearNeedsTypeCheck();
413 }
414 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100415
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100416 if (value->IsNullConstant()) {
417 instruction->ClearNeedsTypeCheck();
418 }
419
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100420 if (!value->CanBeNull()) {
421 instruction->ClearValueCanBeNull();
422 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000423}
424
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000425void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
426 if (instruction->GetResultType() == instruction->GetInputType()) {
427 // Remove the instruction if it's converting to the same type.
428 instruction->ReplaceWith(instruction->GetInput());
429 instruction->GetBlock()->RemoveInstruction(instruction);
430 }
431}
432
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000433void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
434 HConstant* input_cst = instruction->GetConstantRight();
435 HInstruction* input_other = instruction->GetLeastConstantLeft();
436 if ((input_cst != nullptr) && input_cst->IsZero()) {
437 // Replace code looking like
438 // ADD dst, src, 0
439 // with
440 // src
441 instruction->ReplaceWith(input_other);
442 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames188d4312015-04-09 18:30:21 +0100443 return;
444 }
445
446 HInstruction* left = instruction->GetLeft();
447 HInstruction* right = instruction->GetRight();
448 bool left_is_neg = left->IsNeg();
449 bool right_is_neg = right->IsNeg();
450
451 if (left_is_neg && right_is_neg) {
452 if (TryMoveNegOnInputsAfterBinop(instruction)) {
453 return;
454 }
455 }
456
457 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
458 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
459 // Replace code looking like
460 // NEG tmp, b
461 // ADD dst, a, tmp
462 // with
463 // SUB dst, a, b
464 // We do not perform the optimization if the input negation has environment
465 // uses or multiple non-environment uses as it could lead to worse code. In
466 // particular, we do not want the live range of `b` to be extended if we are
467 // not sure the initial 'NEG' instruction can be removed.
468 HInstruction* other = left_is_neg ? right : left;
469 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
470 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
471 RecordSimplification();
472 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000473 }
474}
475
476void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
477 HConstant* input_cst = instruction->GetConstantRight();
478 HInstruction* input_other = instruction->GetLeastConstantLeft();
479
480 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
481 // Replace code looking like
482 // AND dst, src, 0xFFF...FF
483 // with
484 // src
485 instruction->ReplaceWith(input_other);
486 instruction->GetBlock()->RemoveInstruction(instruction);
487 return;
488 }
489
490 // We assume that GVN has run before, so we only perform a pointer comparison.
491 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100492 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000493 if (instruction->GetLeft() == instruction->GetRight()) {
494 // Replace code looking like
495 // AND dst, src, src
496 // with
497 // src
498 instruction->ReplaceWith(instruction->GetLeft());
499 instruction->GetBlock()->RemoveInstruction(instruction);
500 }
501}
502
Mark Mendellc4701932015-04-10 13:18:51 -0400503void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
504 VisitCondition(condition);
505}
506
507void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
508 VisitCondition(condition);
509}
510
511void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
512 VisitCondition(condition);
513}
514
515void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
516 VisitCondition(condition);
517}
518
519void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
520 // Try to fold an HCompare into this HCondition.
521
Roland Levillain7f63c522015-07-13 15:54:55 +0000522 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
523 // TODO: Implement it for MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400524 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Roland Levillain7f63c522015-07-13 15:54:55 +0000525 if (instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400526 return;
527 }
528
529 HInstruction* left = condition->GetLeft();
530 HInstruction* right = condition->GetRight();
531 // We can only replace an HCondition which compares a Compare to 0.
532 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
533 // condition with a long, float or double comparison as input.
534 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
535 // Conversion is not possible.
536 return;
537 }
538
539 // Is the Compare only used for this purpose?
540 if (!left->GetUses().HasOnlyOneUse()) {
541 // Someone else also wants the result of the compare.
542 return;
543 }
544
545 if (!left->GetEnvUses().IsEmpty()) {
546 // There is a reference to the compare result in an environment. Do we really need it?
547 if (GetGraph()->IsDebuggable()) {
548 return;
549 }
550
551 // We have to ensure that there are no deopt points in the sequence.
552 if (left->HasAnyEnvironmentUseBefore(condition)) {
553 return;
554 }
555 }
556
557 // Clean up any environment uses from the HCompare, if any.
558 left->RemoveEnvironmentUsers();
559
560 // We have decided to fold the HCompare into the HCondition. Transfer the information.
561 condition->SetBias(left->AsCompare()->GetBias());
562
563 // Replace the operands of the HCondition.
564 condition->ReplaceInput(left->InputAt(0), 0);
565 condition->ReplaceInput(left->InputAt(1), 1);
566
567 // Remove the HCompare.
568 left->GetBlock()->RemoveInstruction(left);
569
570 RecordSimplification();
571}
572
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000573void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
574 HConstant* input_cst = instruction->GetConstantRight();
575 HInstruction* input_other = instruction->GetLeastConstantLeft();
576 Primitive::Type type = instruction->GetType();
577
578 if ((input_cst != nullptr) && input_cst->IsOne()) {
579 // Replace code looking like
580 // DIV dst, src, 1
581 // with
582 // src
583 instruction->ReplaceWith(input_other);
584 instruction->GetBlock()->RemoveInstruction(instruction);
585 return;
586 }
587
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000588 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000589 // Replace code looking like
590 // DIV dst, src, -1
591 // with
592 // NEG dst, src
593 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000594 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100595 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000596 return;
597 }
598
599 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
600 // Try replacing code looking like
601 // DIV dst, src, constant
602 // with
603 // MUL dst, src, 1 / constant
604 HConstant* reciprocal = nullptr;
605 if (type == Primitive::Primitive::kPrimDouble) {
606 double value = input_cst->AsDoubleConstant()->GetValue();
607 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
608 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
609 }
610 } else {
611 DCHECK_EQ(type, Primitive::kPrimFloat);
612 float value = input_cst->AsFloatConstant()->GetValue();
613 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
614 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
615 }
616 }
617
618 if (reciprocal != nullptr) {
619 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
620 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
621 RecordSimplification();
622 return;
623 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000624 }
625}
626
627void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
628 HConstant* input_cst = instruction->GetConstantRight();
629 HInstruction* input_other = instruction->GetLeastConstantLeft();
630 Primitive::Type type = instruction->GetType();
631 HBasicBlock* block = instruction->GetBlock();
632 ArenaAllocator* allocator = GetGraph()->GetArena();
633
634 if (input_cst == nullptr) {
635 return;
636 }
637
638 if (input_cst->IsOne()) {
639 // Replace code looking like
640 // MUL dst, src, 1
641 // with
642 // src
643 instruction->ReplaceWith(input_other);
644 instruction->GetBlock()->RemoveInstruction(instruction);
645 return;
646 }
647
648 if (input_cst->IsMinusOne() &&
649 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
650 // Replace code looking like
651 // MUL dst, src, -1
652 // with
653 // NEG dst, src
654 HNeg* neg = new (allocator) HNeg(type, input_other);
655 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100656 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000657 return;
658 }
659
660 if (Primitive::IsFloatingPointType(type) &&
661 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
662 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
663 // Replace code looking like
664 // FP_MUL dst, src, 2.0
665 // with
666 // FP_ADD dst, src, src
667 // The 'int' and 'long' cases are handled below.
668 block->ReplaceAndRemoveInstructionWith(instruction,
669 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100670 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000671 return;
672 }
673
674 if (Primitive::IsIntOrLongType(type)) {
675 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600676 // Even though constant propagation also takes care of the zero case, other
677 // optimizations can lead to having a zero multiplication.
678 if (factor == 0) {
679 // Replace code looking like
680 // MUL dst, src, 0
681 // with
682 // 0
683 instruction->ReplaceWith(input_cst);
684 instruction->GetBlock()->RemoveInstruction(instruction);
685 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000686 // Replace code looking like
687 // MUL dst, src, pow_of_2
688 // with
689 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000690 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000691 HShl* shl = new(allocator) HShl(type, input_other, shift);
692 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100693 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000694 }
695 }
696}
697
Alexandre Rames188d4312015-04-09 18:30:21 +0100698void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
699 HInstruction* input = instruction->GetInput();
700 if (input->IsNeg()) {
701 // Replace code looking like
702 // NEG tmp, src
703 // NEG dst, tmp
704 // with
705 // src
706 HNeg* previous_neg = input->AsNeg();
707 instruction->ReplaceWith(previous_neg->GetInput());
708 instruction->GetBlock()->RemoveInstruction(instruction);
709 // We perform the optimization even if the input negation has environment
710 // uses since it allows removing the current instruction. But we only delete
711 // the input negation only if it is does not have any uses left.
712 if (!previous_neg->HasUses()) {
713 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
714 }
715 RecordSimplification();
716 return;
717 }
718
Serguei Katkov339dfc22015-04-20 12:29:32 +0600719 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
720 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100721 // Replace code looking like
722 // SUB tmp, a, b
723 // NEG dst, tmp
724 // with
725 // SUB dst, b, a
726 // We do not perform the optimization if the input subtraction has
727 // environment uses or multiple non-environment uses as it could lead to
728 // worse code. In particular, we do not want the live ranges of `a` and `b`
729 // to be extended if we are not sure the initial 'SUB' instruction can be
730 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600731 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100732 HSub* sub = input->AsSub();
733 HSub* new_sub =
734 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
735 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
736 if (!sub->HasUses()) {
737 sub->GetBlock()->RemoveInstruction(sub);
738 }
739 RecordSimplification();
740 }
741}
742
743void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
744 HInstruction* input = instruction->GetInput();
745 if (input->IsNot()) {
746 // Replace code looking like
747 // NOT tmp, src
748 // NOT dst, tmp
749 // with
750 // src
751 // We perform the optimization even if the input negation has environment
752 // uses since it allows removing the current instruction. But we only delete
753 // the input negation only if it is does not have any uses left.
754 HNot* previous_not = input->AsNot();
755 instruction->ReplaceWith(previous_not->GetInput());
756 instruction->GetBlock()->RemoveInstruction(instruction);
757 if (!previous_not->HasUses()) {
758 previous_not->GetBlock()->RemoveInstruction(previous_not);
759 }
760 RecordSimplification();
761 }
762}
763
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000764void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
765 HConstant* input_cst = instruction->GetConstantRight();
766 HInstruction* input_other = instruction->GetLeastConstantLeft();
767
768 if ((input_cst != nullptr) && input_cst->IsZero()) {
769 // Replace code looking like
770 // OR dst, src, 0
771 // with
772 // src
773 instruction->ReplaceWith(input_other);
774 instruction->GetBlock()->RemoveInstruction(instruction);
775 return;
776 }
777
778 // We assume that GVN has run before, so we only perform a pointer comparison.
779 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100780 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000781 if (instruction->GetLeft() == instruction->GetRight()) {
782 // Replace code looking like
783 // OR dst, src, src
784 // with
785 // src
786 instruction->ReplaceWith(instruction->GetLeft());
787 instruction->GetBlock()->RemoveInstruction(instruction);
788 }
789}
790
791void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
792 VisitShift(instruction);
793}
794
795void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
796 VisitShift(instruction);
797}
798
799void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
800 HConstant* input_cst = instruction->GetConstantRight();
801 HInstruction* input_other = instruction->GetLeastConstantLeft();
802
803 if ((input_cst != nullptr) && input_cst->IsZero()) {
804 // Replace code looking like
805 // SUB dst, src, 0
806 // with
807 // src
808 instruction->ReplaceWith(input_other);
809 instruction->GetBlock()->RemoveInstruction(instruction);
810 return;
811 }
812
813 Primitive::Type type = instruction->GetType();
814 if (!Primitive::IsIntegralType(type)) {
815 return;
816 }
817
818 HBasicBlock* block = instruction->GetBlock();
819 ArenaAllocator* allocator = GetGraph()->GetArena();
820
Alexandre Rames188d4312015-04-09 18:30:21 +0100821 HInstruction* left = instruction->GetLeft();
822 HInstruction* right = instruction->GetRight();
823 if (left->IsConstant()) {
824 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000825 // Replace code looking like
826 // SUB dst, 0, src
827 // with
828 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100829 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000830 // `x` is `0.0`, the former expression yields `0.0`, while the later
831 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100832 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000833 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100834 RecordSimplification();
835 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000836 }
837 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100838
839 if (left->IsNeg() && right->IsNeg()) {
840 if (TryMoveNegOnInputsAfterBinop(instruction)) {
841 return;
842 }
843 }
844
845 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
846 // Replace code looking like
847 // NEG tmp, b
848 // SUB dst, a, tmp
849 // with
850 // ADD dst, a, b
851 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
852 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
853 RecordSimplification();
854 right->GetBlock()->RemoveInstruction(right);
855 return;
856 }
857
858 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
859 // Replace code looking like
860 // NEG tmp, a
861 // SUB dst, tmp, b
862 // with
863 // ADD tmp, a, b
864 // NEG dst, tmp
865 // The second version is not intrinsically better, but enables more
866 // transformations.
867 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
868 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
869 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
870 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
871 instruction->ReplaceWith(neg);
872 instruction->GetBlock()->RemoveInstruction(instruction);
873 RecordSimplification();
874 left->GetBlock()->RemoveInstruction(left);
875 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000876}
877
878void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
879 VisitShift(instruction);
880}
881
882void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
883 HConstant* input_cst = instruction->GetConstantRight();
884 HInstruction* input_other = instruction->GetLeastConstantLeft();
885
886 if ((input_cst != nullptr) && input_cst->IsZero()) {
887 // Replace code looking like
888 // XOR dst, src, 0
889 // with
890 // src
891 instruction->ReplaceWith(input_other);
892 instruction->GetBlock()->RemoveInstruction(instruction);
893 return;
894 }
895
896 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
897 // Replace code looking like
898 // XOR dst, src, 0xFFF...FF
899 // with
900 // NOT dst, src
901 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
902 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +0100903 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000904 return;
905 }
906}
907
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +0100908void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
909 HInstruction* actual_string = nullptr;
910
911 // Find the string we need to replace this instruction with. The actual string is
912 // the return value of a StringFactory call.
913 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
914 HInstruction* use = it.Current()->GetUser();
915 if (use->IsInvokeStaticOrDirect()
916 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
917 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
918 actual_string = use;
919 break;
920 }
921 }
922
923 // Check that there is no other instruction that thinks it is the factory for that string.
924 if (kIsDebugBuild) {
925 CHECK(actual_string != nullptr);
926 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
927 HInstruction* use = it.Current()->GetUser();
928 if (use->IsInvokeStaticOrDirect()) {
929 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
930 }
931 }
932 }
933
934 // We need to remove any environment uses of the fake string that are not dominated by
935 // `actual_string` to null.
936 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
937 HEnvironment* environment = it.Current()->GetUser();
938 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
939 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
940 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
941 }
942 }
943
944 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
945 // `instruction`.
946 instruction->ReplaceWith(actual_string);
947 instruction->GetBlock()->RemoveInstruction(instruction);
948}
949
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100950} // namespace art