blob: 2f3df7fc687716c38efa5df0fbb1aaf8179d19e1 [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
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
37 if (stats_) {
38 stats_->RecordStat(kInstructionSimplifications);
39 }
40 }
41
42 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000043 void VisitShift(HBinaryOperation* shift);
44
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000045 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
46 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010047 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
48 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010049 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
50 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000051 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000052 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000053 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080054 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000055 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000056 void VisitAdd(HAdd* instruction) OVERRIDE;
57 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040058 void VisitCondition(HCondition* instruction) OVERRIDE;
59 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
60 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
61 void VisitLessThan(HLessThan* condition) OVERRIDE;
62 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000063 void VisitDiv(HDiv* instruction) OVERRIDE;
64 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010065 void VisitNeg(HNeg* instruction) OVERRIDE;
66 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000067 void VisitOr(HOr* instruction) OVERRIDE;
68 void VisitShl(HShl* instruction) OVERRIDE;
69 void VisitShr(HShr* instruction) OVERRIDE;
70 void VisitSub(HSub* instruction) OVERRIDE;
71 void VisitUShr(HUShr* instruction) OVERRIDE;
72 void VisitXor(HXor* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010073 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +010074 void VisitFakeString(HFakeString* fake_string) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010075 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070076 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010077
78 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000079
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010080 void SimplifySystemArrayCopy(HInvoke* invoke);
81 void SimplifyStringEquals(HInvoke* invoke);
82
Calin Juravleacf735c2015-02-12 15:25:22 +000083 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010084 bool simplification_occurred_ = false;
85 int simplifications_at_current_position_ = 0;
86 // We ensure we do not loop infinitely. The value is a finger in the air guess
87 // that should allow enough simplification.
88 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000089};
90
Nicolas Geoffray3c049742014-09-24 18:10:46 +010091void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000092 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010093 visitor.Run();
94}
95
96void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010097 // Iterate in reverse post order to open up more simplifications to users
98 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010099 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
100 // The simplification of an instruction to another instruction may yield
101 // possibilities for other simplifications. So although we perform a reverse
102 // post order visit, we sometimes need to revisit an instruction index.
103 simplification_occurred_ = false;
104 VisitBasicBlock(it.Current());
105 if (simplification_occurred_ &&
106 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
107 // New simplifications may be applicable to the instruction at the
108 // current index, so don't advance the iterator.
109 continue;
110 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100111 simplifications_at_current_position_ = 0;
112 it.Advance();
113 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100114}
115
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000116namespace {
117
118bool AreAllBitsSet(HConstant* constant) {
119 return Int64FromConstant(constant) == -1;
120}
121
122} // namespace
123
Alexandre Rames188d4312015-04-09 18:30:21 +0100124// Returns true if the code was simplified to use only one negation operation
125// after the binary operation instead of one on each of the inputs.
126bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
127 DCHECK(binop->IsAdd() || binop->IsSub());
128 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
129 HNeg* left_neg = binop->GetLeft()->AsNeg();
130 HNeg* right_neg = binop->GetRight()->AsNeg();
131 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
132 !right_neg->HasOnlyOneNonEnvironmentUse()) {
133 return false;
134 }
135 // Replace code looking like
136 // NEG tmp1, a
137 // NEG tmp2, b
138 // ADD dst, tmp1, tmp2
139 // with
140 // ADD tmp, a, b
141 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600142 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
143 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
144 // while the later yields `-0.0`.
145 if (!Primitive::IsIntegralType(binop->GetType())) {
146 return false;
147 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100148 binop->ReplaceInput(left_neg->GetInput(), 0);
149 binop->ReplaceInput(right_neg->GetInput(), 1);
150 left_neg->GetBlock()->RemoveInstruction(left_neg);
151 right_neg->GetBlock()->RemoveInstruction(right_neg);
152 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
153 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
154 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
155 RecordSimplification();
156 return true;
157}
158
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000159void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
160 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
161 HConstant* input_cst = instruction->GetConstantRight();
162 HInstruction* input_other = instruction->GetLeastConstantLeft();
163
Mark Mendellba56d062015-05-05 21:34:03 -0400164 if (input_cst != nullptr) {
165 if (input_cst->IsZero()) {
166 // Replace code looking like
167 // SHL dst, src, 0
168 // with
169 // src
170 instruction->ReplaceWith(input_other);
171 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400172 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000173 }
174}
175
Calin Juravle10e244f2015-01-26 18:54:32 +0000176void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
177 HInstruction* obj = null_check->InputAt(0);
178 if (!obj->CanBeNull()) {
179 null_check->ReplaceWith(obj);
180 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000181 if (stats_ != nullptr) {
182 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
183 }
184 }
185}
186
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100187bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
188 if (!input->CanBeNull()) {
189 return true;
190 }
191
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100192 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
193 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100194 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100195 return true;
196 }
197 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100198
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100199 return false;
200}
201
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100202// Returns whether doing a type test between the class of `object` against `klass` has
203// a statically known outcome. The result of the test is stored in `outcome`.
204static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000205 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
206 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
207 ScopedObjectAccess soa(Thread::Current());
208 if (!obj_rti.IsValid()) {
209 // We run the simplifier before the reference type propagation so type info might not be
210 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100211 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000212 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100213
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100214 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100215 if (!class_rti.IsValid()) {
216 // Happens when the loaded class is unresolved.
217 return false;
218 }
219 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000220 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100221 *outcome = true;
222 return true;
223 } else if (obj_rti.IsExact()) {
224 // The test failed at compile time so will also fail at runtime.
225 *outcome = false;
226 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100227 } else if (!class_rti.IsInterface()
228 && !obj_rti.IsInterface()
229 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100230 // Different type hierarchy. The test will fail.
231 *outcome = false;
232 return true;
233 }
234 return false;
235}
236
237void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
238 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100239 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
240 if (load_class->NeedsAccessCheck()) {
241 // If we need to perform an access check we cannot remove the instruction.
242 return;
243 }
244
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100245 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100246 check_cast->ClearMustDoNullCheck();
247 }
248
249 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000250 check_cast->GetBlock()->RemoveInstruction(check_cast);
251 if (stats_ != nullptr) {
252 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
253 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100254 return;
255 }
256
257 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700258 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100259 if (outcome) {
260 check_cast->GetBlock()->RemoveInstruction(check_cast);
261 if (stats_ != nullptr) {
262 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
263 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700264 if (!load_class->HasUses()) {
265 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
266 // However, here we know that it cannot because the checkcast was successfull, hence
267 // the class was already loaded.
268 load_class->GetBlock()->RemoveInstruction(load_class);
269 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100270 } else {
271 // Don't do anything for exceptional cases for now. Ideally we should remove
272 // all instructions and blocks this instruction dominates.
273 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000274 }
275}
276
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100277void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100278 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100279 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
280 if (load_class->NeedsAccessCheck()) {
281 // If we need to perform an access check we cannot remove the instruction.
282 return;
283 }
284
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100285 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100286 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100287 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100288 instruction->ClearMustDoNullCheck();
289 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100290
291 HGraph* graph = GetGraph();
292 if (object->IsNullConstant()) {
293 instruction->ReplaceWith(graph->GetIntConstant(0));
294 instruction->GetBlock()->RemoveInstruction(instruction);
295 RecordSimplification();
296 return;
297 }
298
299 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700300 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100301 if (outcome && can_be_null) {
302 // Type test will succeed, we just need a null test.
303 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
304 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
305 instruction->ReplaceWith(test);
306 } else {
307 // We've statically determined the result of the instanceof.
308 instruction->ReplaceWith(graph->GetIntConstant(outcome));
309 }
310 RecordSimplification();
311 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700312 if (outcome && !load_class->HasUses()) {
313 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
314 // However, here we know that it cannot because the instanceof check was successfull, hence
315 // the class was already loaded.
316 load_class->GetBlock()->RemoveInstruction(load_class);
317 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100318 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100319}
320
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100321void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
322 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100323 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100324 instruction->ClearValueCanBeNull();
325 }
326}
327
328void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
329 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100330 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100331 instruction->ClearValueCanBeNull();
332 }
333}
334
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000335void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100336 HBasicBlock* block = check->GetBlock();
337 // Currently always keep the suspend check at entry.
338 if (block->IsEntryBlock()) return;
339
340 // Currently always keep suspend checks at loop entry.
341 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
342 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
343 return;
344 }
345
346 // Remove the suspend check that was added at build time for the baseline
347 // compiler.
348 block->RemoveInstruction(check);
349}
350
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000351void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100352 HInstruction* input_const = equal->GetConstantRight();
353 if (input_const != nullptr) {
354 HInstruction* input_value = equal->GetLeastConstantLeft();
355 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
356 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100357 // We are comparing the boolean to a constant which is of type int and can
358 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100359 if (input_const->AsIntConstant()->IsOne()) {
360 // Replace (bool_value == true) with bool_value
361 equal->ReplaceWith(input_value);
362 block->RemoveInstruction(equal);
363 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100364 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500365 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
366 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100367 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100368 } else {
369 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
370 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
371 block->RemoveInstruction(equal);
372 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100373 }
Mark Mendellc4701932015-04-10 13:18:51 -0400374 } else {
375 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100376 }
Mark Mendellc4701932015-04-10 13:18:51 -0400377 } else {
378 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100379 }
380}
381
David Brazdil0d13fee2015-04-17 14:52:19 +0100382void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
383 HInstruction* input_const = not_equal->GetConstantRight();
384 if (input_const != nullptr) {
385 HInstruction* input_value = not_equal->GetLeastConstantLeft();
386 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
387 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100388 // We are comparing the boolean to a constant which is of type int and can
389 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100390 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500391 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
392 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100393 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100394 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100395 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100396 not_equal->ReplaceWith(input_value);
397 block->RemoveInstruction(not_equal);
398 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100399 } else {
400 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
401 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
402 block->RemoveInstruction(not_equal);
403 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100404 }
Mark Mendellc4701932015-04-10 13:18:51 -0400405 } else {
406 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100407 }
Mark Mendellc4701932015-04-10 13:18:51 -0400408 } else {
409 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100410 }
411}
412
413void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
414 HInstruction* parent = bool_not->InputAt(0);
415 if (parent->IsBooleanNot()) {
416 HInstruction* value = parent->InputAt(0);
417 // Replace (!(!bool_value)) with bool_value
418 bool_not->ReplaceWith(value);
419 bool_not->GetBlock()->RemoveInstruction(bool_not);
420 // It is possible that `parent` is dead at this point but we leave
421 // its removal to DCE for simplicity.
422 RecordSimplification();
423 }
424}
425
Mingyao Yang0304e182015-01-30 16:41:29 -0800426void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
427 HInstruction* input = instruction->InputAt(0);
428 // If the array is a NewArray with constant size, replace the array length
429 // with the constant instruction. This helps the bounds check elimination phase.
430 if (input->IsNewArray()) {
431 input = input->InputAt(0);
432 if (input->IsIntConstant()) {
433 instruction->ReplaceWith(input);
434 }
435 }
436}
437
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000438void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000439 HInstruction* value = instruction->GetValue();
440 if (value->GetType() != Primitive::kPrimNot) return;
441
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100442 if (CanEnsureNotNullAt(value, instruction)) {
443 instruction->ClearValueCanBeNull();
444 }
445
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000446 if (value->IsArrayGet()) {
447 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
448 // If the code is just swapping elements in the array, no need for a type check.
449 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100450 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000451 }
452 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100453
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100454 if (value->IsNullConstant()) {
455 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100456 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100457 }
458
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100459 ScopedObjectAccess soa(Thread::Current());
460 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
461 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
462 if (!array_rti.IsValid()) {
463 return;
464 }
465
466 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
467 instruction->ClearNeedsTypeCheck();
468 return;
469 }
470
471 if (array_rti.IsObjectArray()) {
472 if (array_rti.IsExact()) {
473 instruction->ClearNeedsTypeCheck();
474 return;
475 }
476 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100477 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000478}
479
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000480void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
481 if (instruction->GetResultType() == instruction->GetInputType()) {
482 // Remove the instruction if it's converting to the same type.
483 instruction->ReplaceWith(instruction->GetInput());
484 instruction->GetBlock()->RemoveInstruction(instruction);
485 }
486}
487
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000488void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
489 HConstant* input_cst = instruction->GetConstantRight();
490 HInstruction* input_other = instruction->GetLeastConstantLeft();
491 if ((input_cst != nullptr) && input_cst->IsZero()) {
492 // Replace code looking like
493 // ADD dst, src, 0
494 // with
495 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600496 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
497 // `x` is `-0.0`, the former expression yields `0.0`, while the later
498 // yields `-0.0`.
499 if (Primitive::IsIntegralType(instruction->GetType())) {
500 instruction->ReplaceWith(input_other);
501 instruction->GetBlock()->RemoveInstruction(instruction);
502 return;
503 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100504 }
505
506 HInstruction* left = instruction->GetLeft();
507 HInstruction* right = instruction->GetRight();
508 bool left_is_neg = left->IsNeg();
509 bool right_is_neg = right->IsNeg();
510
511 if (left_is_neg && right_is_neg) {
512 if (TryMoveNegOnInputsAfterBinop(instruction)) {
513 return;
514 }
515 }
516
517 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
518 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
519 // Replace code looking like
520 // NEG tmp, b
521 // ADD dst, a, tmp
522 // with
523 // SUB dst, a, b
524 // We do not perform the optimization if the input negation has environment
525 // uses or multiple non-environment uses as it could lead to worse code. In
526 // particular, we do not want the live range of `b` to be extended if we are
527 // not sure the initial 'NEG' instruction can be removed.
528 HInstruction* other = left_is_neg ? right : left;
529 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
530 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
531 RecordSimplification();
532 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000533 }
534}
535
536void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
537 HConstant* input_cst = instruction->GetConstantRight();
538 HInstruction* input_other = instruction->GetLeastConstantLeft();
539
Vladimir Marko452c1b62015-09-25 14:44:17 +0100540 if (input_cst != nullptr) {
541 int64_t value = Int64FromConstant(input_cst);
542 if (value == -1) {
543 // Replace code looking like
544 // AND dst, src, 0xFFF...FF
545 // with
546 // src
547 instruction->ReplaceWith(input_other);
548 instruction->GetBlock()->RemoveInstruction(instruction);
549 RecordSimplification();
550 return;
551 }
552 // Eliminate And from UShr+And if the And-mask contains all the bits that
553 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
554 // precisely clears the shifted-in sign bits.
555 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
556 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
557 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
558 size_t num_tail_bits_set = CTZ(value + 1);
559 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
560 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
561 instruction->ReplaceWith(input_other);
562 instruction->GetBlock()->RemoveInstruction(instruction);
563 RecordSimplification();
564 return;
565 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
566 input_other->HasOnlyOneNonEnvironmentUse()) {
567 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
568 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
569 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
570 input_other->InputAt(0),
571 input_other->InputAt(1),
572 input_other->GetDexPc());
573 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
574 input_other->GetBlock()->RemoveInstruction(input_other);
575 RecordSimplification();
576 return;
577 }
578 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000579 }
580
581 // We assume that GVN has run before, so we only perform a pointer comparison.
582 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100583 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000584 if (instruction->GetLeft() == instruction->GetRight()) {
585 // Replace code looking like
586 // AND dst, src, src
587 // with
588 // src
589 instruction->ReplaceWith(instruction->GetLeft());
590 instruction->GetBlock()->RemoveInstruction(instruction);
591 }
592}
593
Mark Mendellc4701932015-04-10 13:18:51 -0400594void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
595 VisitCondition(condition);
596}
597
598void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
599 VisitCondition(condition);
600}
601
602void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
603 VisitCondition(condition);
604}
605
606void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
607 VisitCondition(condition);
608}
609
Aart Bike9f37602015-10-09 11:15:55 -0700610// TODO: unsigned comparisons too?
611
Mark Mendellc4701932015-04-10 13:18:51 -0400612void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
613 // Try to fold an HCompare into this HCondition.
614
Roland Levillain7f63c522015-07-13 15:54:55 +0000615 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200616 // TODO: Implement it for MIPS and MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400617 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200618 if (instruction_set == kMips || instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400619 return;
620 }
621
622 HInstruction* left = condition->GetLeft();
623 HInstruction* right = condition->GetRight();
624 // We can only replace an HCondition which compares a Compare to 0.
625 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
626 // condition with a long, float or double comparison as input.
627 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
628 // Conversion is not possible.
629 return;
630 }
631
632 // Is the Compare only used for this purpose?
633 if (!left->GetUses().HasOnlyOneUse()) {
634 // Someone else also wants the result of the compare.
635 return;
636 }
637
638 if (!left->GetEnvUses().IsEmpty()) {
639 // There is a reference to the compare result in an environment. Do we really need it?
640 if (GetGraph()->IsDebuggable()) {
641 return;
642 }
643
644 // We have to ensure that there are no deopt points in the sequence.
645 if (left->HasAnyEnvironmentUseBefore(condition)) {
646 return;
647 }
648 }
649
650 // Clean up any environment uses from the HCompare, if any.
651 left->RemoveEnvironmentUsers();
652
653 // We have decided to fold the HCompare into the HCondition. Transfer the information.
654 condition->SetBias(left->AsCompare()->GetBias());
655
656 // Replace the operands of the HCondition.
657 condition->ReplaceInput(left->InputAt(0), 0);
658 condition->ReplaceInput(left->InputAt(1), 1);
659
660 // Remove the HCompare.
661 left->GetBlock()->RemoveInstruction(left);
662
663 RecordSimplification();
664}
665
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000666void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
667 HConstant* input_cst = instruction->GetConstantRight();
668 HInstruction* input_other = instruction->GetLeastConstantLeft();
669 Primitive::Type type = instruction->GetType();
670
671 if ((input_cst != nullptr) && input_cst->IsOne()) {
672 // Replace code looking like
673 // DIV dst, src, 1
674 // with
675 // src
676 instruction->ReplaceWith(input_other);
677 instruction->GetBlock()->RemoveInstruction(instruction);
678 return;
679 }
680
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000681 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000682 // Replace code looking like
683 // DIV dst, src, -1
684 // with
685 // NEG dst, src
686 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000687 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100688 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000689 return;
690 }
691
692 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
693 // Try replacing code looking like
694 // DIV dst, src, constant
695 // with
696 // MUL dst, src, 1 / constant
697 HConstant* reciprocal = nullptr;
698 if (type == Primitive::Primitive::kPrimDouble) {
699 double value = input_cst->AsDoubleConstant()->GetValue();
700 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
701 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
702 }
703 } else {
704 DCHECK_EQ(type, Primitive::kPrimFloat);
705 float value = input_cst->AsFloatConstant()->GetValue();
706 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
707 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
708 }
709 }
710
711 if (reciprocal != nullptr) {
712 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
713 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
714 RecordSimplification();
715 return;
716 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000717 }
718}
719
720void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
721 HConstant* input_cst = instruction->GetConstantRight();
722 HInstruction* input_other = instruction->GetLeastConstantLeft();
723 Primitive::Type type = instruction->GetType();
724 HBasicBlock* block = instruction->GetBlock();
725 ArenaAllocator* allocator = GetGraph()->GetArena();
726
727 if (input_cst == nullptr) {
728 return;
729 }
730
731 if (input_cst->IsOne()) {
732 // Replace code looking like
733 // MUL dst, src, 1
734 // with
735 // src
736 instruction->ReplaceWith(input_other);
737 instruction->GetBlock()->RemoveInstruction(instruction);
738 return;
739 }
740
741 if (input_cst->IsMinusOne() &&
742 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
743 // Replace code looking like
744 // MUL dst, src, -1
745 // with
746 // NEG dst, src
747 HNeg* neg = new (allocator) HNeg(type, input_other);
748 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100749 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000750 return;
751 }
752
753 if (Primitive::IsFloatingPointType(type) &&
754 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
755 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
756 // Replace code looking like
757 // FP_MUL dst, src, 2.0
758 // with
759 // FP_ADD dst, src, src
760 // The 'int' and 'long' cases are handled below.
761 block->ReplaceAndRemoveInstructionWith(instruction,
762 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100763 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000764 return;
765 }
766
767 if (Primitive::IsIntOrLongType(type)) {
768 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600769 // Even though constant propagation also takes care of the zero case, other
770 // optimizations can lead to having a zero multiplication.
771 if (factor == 0) {
772 // Replace code looking like
773 // MUL dst, src, 0
774 // with
775 // 0
776 instruction->ReplaceWith(input_cst);
777 instruction->GetBlock()->RemoveInstruction(instruction);
778 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000779 // Replace code looking like
780 // MUL dst, src, pow_of_2
781 // with
782 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000783 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000784 HShl* shl = new(allocator) HShl(type, input_other, shift);
785 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100786 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +0000787 } else if (IsPowerOfTwo(factor - 1)) {
788 // Transform code looking like
789 // MUL dst, src, (2^n + 1)
790 // into
791 // SHL tmp, src, n
792 // ADD dst, src, tmp
793 HShl* shl = new (allocator) HShl(type,
794 input_other,
795 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
796 HAdd* add = new (allocator) HAdd(type, input_other, shl);
797
798 block->InsertInstructionBefore(shl, instruction);
799 block->ReplaceAndRemoveInstructionWith(instruction, add);
800 RecordSimplification();
801 } else if (IsPowerOfTwo(factor + 1)) {
802 // Transform code looking like
803 // MUL dst, src, (2^n - 1)
804 // into
805 // SHL tmp, src, n
806 // SUB dst, tmp, src
807 HShl* shl = new (allocator) HShl(type,
808 input_other,
809 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
810 HSub* sub = new (allocator) HSub(type, shl, input_other);
811
812 block->InsertInstructionBefore(shl, instruction);
813 block->ReplaceAndRemoveInstructionWith(instruction, sub);
814 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000815 }
816 }
817}
818
Alexandre Rames188d4312015-04-09 18:30:21 +0100819void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
820 HInstruction* input = instruction->GetInput();
821 if (input->IsNeg()) {
822 // Replace code looking like
823 // NEG tmp, src
824 // NEG dst, tmp
825 // with
826 // src
827 HNeg* previous_neg = input->AsNeg();
828 instruction->ReplaceWith(previous_neg->GetInput());
829 instruction->GetBlock()->RemoveInstruction(instruction);
830 // We perform the optimization even if the input negation has environment
831 // uses since it allows removing the current instruction. But we only delete
832 // the input negation only if it is does not have any uses left.
833 if (!previous_neg->HasUses()) {
834 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
835 }
836 RecordSimplification();
837 return;
838 }
839
Serguei Katkov339dfc22015-04-20 12:29:32 +0600840 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
841 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100842 // Replace code looking like
843 // SUB tmp, a, b
844 // NEG dst, tmp
845 // with
846 // SUB dst, b, a
847 // We do not perform the optimization if the input subtraction has
848 // environment uses or multiple non-environment uses as it could lead to
849 // worse code. In particular, we do not want the live ranges of `a` and `b`
850 // to be extended if we are not sure the initial 'SUB' instruction can be
851 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600852 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100853 HSub* sub = input->AsSub();
854 HSub* new_sub =
855 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
856 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
857 if (!sub->HasUses()) {
858 sub->GetBlock()->RemoveInstruction(sub);
859 }
860 RecordSimplification();
861 }
862}
863
864void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
865 HInstruction* input = instruction->GetInput();
866 if (input->IsNot()) {
867 // Replace code looking like
868 // NOT tmp, src
869 // NOT dst, tmp
870 // with
871 // src
872 // We perform the optimization even if the input negation has environment
873 // uses since it allows removing the current instruction. But we only delete
874 // the input negation only if it is does not have any uses left.
875 HNot* previous_not = input->AsNot();
876 instruction->ReplaceWith(previous_not->GetInput());
877 instruction->GetBlock()->RemoveInstruction(instruction);
878 if (!previous_not->HasUses()) {
879 previous_not->GetBlock()->RemoveInstruction(previous_not);
880 }
881 RecordSimplification();
882 }
883}
884
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000885void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
886 HConstant* input_cst = instruction->GetConstantRight();
887 HInstruction* input_other = instruction->GetLeastConstantLeft();
888
889 if ((input_cst != nullptr) && input_cst->IsZero()) {
890 // Replace code looking like
891 // OR dst, src, 0
892 // with
893 // src
894 instruction->ReplaceWith(input_other);
895 instruction->GetBlock()->RemoveInstruction(instruction);
896 return;
897 }
898
899 // We assume that GVN has run before, so we only perform a pointer comparison.
900 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100901 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000902 if (instruction->GetLeft() == instruction->GetRight()) {
903 // Replace code looking like
904 // OR dst, src, src
905 // with
906 // src
907 instruction->ReplaceWith(instruction->GetLeft());
908 instruction->GetBlock()->RemoveInstruction(instruction);
909 }
910}
911
912void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
913 VisitShift(instruction);
914}
915
916void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
917 VisitShift(instruction);
918}
919
920void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
921 HConstant* input_cst = instruction->GetConstantRight();
922 HInstruction* input_other = instruction->GetLeastConstantLeft();
923
Serguei Katkov115b53f2015-08-05 17:03:30 +0600924 Primitive::Type type = instruction->GetType();
925 if (Primitive::IsFloatingPointType(type)) {
926 return;
927 }
928
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000929 if ((input_cst != nullptr) && input_cst->IsZero()) {
930 // Replace code looking like
931 // SUB dst, src, 0
932 // with
933 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600934 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
935 // `x` is `-0.0`, the former expression yields `0.0`, while the later
936 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000937 instruction->ReplaceWith(input_other);
938 instruction->GetBlock()->RemoveInstruction(instruction);
939 return;
940 }
941
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000942 HBasicBlock* block = instruction->GetBlock();
943 ArenaAllocator* allocator = GetGraph()->GetArena();
944
Alexandre Rames188d4312015-04-09 18:30:21 +0100945 HInstruction* left = instruction->GetLeft();
946 HInstruction* right = instruction->GetRight();
947 if (left->IsConstant()) {
948 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000949 // Replace code looking like
950 // SUB dst, 0, src
951 // with
952 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100953 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000954 // `x` is `0.0`, the former expression yields `0.0`, while the later
955 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100956 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000957 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100958 RecordSimplification();
959 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000960 }
961 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100962
963 if (left->IsNeg() && right->IsNeg()) {
964 if (TryMoveNegOnInputsAfterBinop(instruction)) {
965 return;
966 }
967 }
968
969 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
970 // Replace code looking like
971 // NEG tmp, b
972 // SUB dst, a, tmp
973 // with
974 // ADD dst, a, b
975 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
976 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
977 RecordSimplification();
978 right->GetBlock()->RemoveInstruction(right);
979 return;
980 }
981
982 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
983 // Replace code looking like
984 // NEG tmp, a
985 // SUB dst, tmp, b
986 // with
987 // ADD tmp, a, b
988 // NEG dst, tmp
989 // The second version is not intrinsically better, but enables more
990 // transformations.
991 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
992 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
993 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
994 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
995 instruction->ReplaceWith(neg);
996 instruction->GetBlock()->RemoveInstruction(instruction);
997 RecordSimplification();
998 left->GetBlock()->RemoveInstruction(left);
999 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001000}
1001
1002void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1003 VisitShift(instruction);
1004}
1005
1006void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1007 HConstant* input_cst = instruction->GetConstantRight();
1008 HInstruction* input_other = instruction->GetLeastConstantLeft();
1009
1010 if ((input_cst != nullptr) && input_cst->IsZero()) {
1011 // Replace code looking like
1012 // XOR dst, src, 0
1013 // with
1014 // src
1015 instruction->ReplaceWith(input_other);
1016 instruction->GetBlock()->RemoveInstruction(instruction);
1017 return;
1018 }
1019
1020 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1021 // Replace code looking like
1022 // XOR dst, src, 0xFFF...FF
1023 // with
1024 // NOT dst, src
1025 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1026 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001027 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001028 return;
1029 }
1030}
1031
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +01001032void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
1033 HInstruction* actual_string = nullptr;
1034
1035 // Find the string we need to replace this instruction with. The actual string is
1036 // the return value of a StringFactory call.
1037 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1038 HInstruction* use = it.Current()->GetUser();
1039 if (use->IsInvokeStaticOrDirect()
1040 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
1041 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
1042 actual_string = use;
1043 break;
1044 }
1045 }
1046
1047 // Check that there is no other instruction that thinks it is the factory for that string.
1048 if (kIsDebugBuild) {
1049 CHECK(actual_string != nullptr);
1050 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1051 HInstruction* use = it.Current()->GetUser();
1052 if (use->IsInvokeStaticOrDirect()) {
1053 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
1054 }
1055 }
1056 }
1057
1058 // We need to remove any environment uses of the fake string that are not dominated by
1059 // `actual_string` to null.
1060 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
1061 HEnvironment* environment = it.Current()->GetUser();
1062 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
1063 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
1064 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
1065 }
1066 }
1067
1068 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
1069 // `instruction`.
1070 instruction->ReplaceWith(actual_string);
1071 instruction->GetBlock()->RemoveInstruction(instruction);
1072}
1073
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001074void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1075 HInstruction* argument = instruction->InputAt(1);
1076 HInstruction* receiver = instruction->InputAt(0);
1077 if (receiver == argument) {
1078 // Because String.equals is an instance call, the receiver is
1079 // a null check if we don't know it's null. The argument however, will
1080 // be the actual object. So we cannot end up in a situation where both
1081 // are equal but could be null.
1082 DCHECK(CanEnsureNotNullAt(argument, instruction));
1083 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1084 instruction->GetBlock()->RemoveInstruction(instruction);
1085 } else {
1086 StringEqualsOptimizations optimizations(instruction);
1087 if (CanEnsureNotNullAt(argument, instruction)) {
1088 optimizations.SetArgumentNotNull();
1089 }
1090 ScopedObjectAccess soa(Thread::Current());
1091 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1092 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1093 optimizations.SetArgumentIsString();
1094 }
1095 }
1096}
1097
1098static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1099 if (potential_length->IsArrayLength()) {
1100 return potential_length->InputAt(0) == potential_array;
1101 }
1102
1103 if (potential_array->IsNewArray()) {
1104 return potential_array->InputAt(0) == potential_length;
1105 }
1106
1107 return false;
1108}
1109
1110void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1111 HInstruction* source = instruction->InputAt(0);
1112 HInstruction* destination = instruction->InputAt(2);
1113 HInstruction* count = instruction->InputAt(4);
1114 SystemArrayCopyOptimizations optimizations(instruction);
1115 if (CanEnsureNotNullAt(source, instruction)) {
1116 optimizations.SetSourceIsNotNull();
1117 }
1118 if (CanEnsureNotNullAt(destination, instruction)) {
1119 optimizations.SetDestinationIsNotNull();
1120 }
1121 if (destination == source) {
1122 optimizations.SetDestinationIsSource();
1123 }
1124
1125 if (IsArrayLengthOf(count, source)) {
1126 optimizations.SetCountIsSourceLength();
1127 }
1128
1129 if (IsArrayLengthOf(count, destination)) {
1130 optimizations.SetCountIsDestinationLength();
1131 }
1132
1133 {
1134 ScopedObjectAccess soa(Thread::Current());
1135 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1136 if (destination_rti.IsValid()) {
1137 if (destination_rti.IsObjectArray()) {
1138 if (destination_rti.IsExact()) {
1139 optimizations.SetDoesNotNeedTypeCheck();
1140 }
1141 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001142 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001143 if (destination_rti.IsPrimitiveArrayClass()) {
1144 optimizations.SetDestinationIsPrimitiveArray();
1145 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1146 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001147 }
1148 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001149 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1150 if (source_rti.IsValid()) {
1151 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1152 optimizations.SetDoesNotNeedTypeCheck();
1153 }
1154 if (source_rti.IsPrimitiveArrayClass()) {
1155 optimizations.SetSourceIsPrimitiveArray();
1156 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1157 optimizations.SetSourceIsNonPrimitiveArray();
1158 }
1159 }
1160 }
1161}
1162
1163void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1164 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1165 SimplifyStringEquals(instruction);
1166 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1167 SimplifySystemArrayCopy(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001168 }
1169}
1170
Aart Bikbb245d12015-10-19 11:05:03 -07001171void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1172 HInstruction* cond = deoptimize->InputAt(0);
1173 if (cond->IsConstant()) {
1174 if (cond->AsIntConstant()->IsZero()) {
1175 // Never deopt: instruction can be removed.
1176 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1177 } else {
1178 // Always deopt.
1179 }
1180 }
1181}
1182
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001183} // namespace art