blob: d82b5d20330cf9cdc0ca1d8d73e57800ef28e6cf [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);
172 } else if (instruction->IsShl() && input_cst->IsOne()) {
173 // Replace Shl looking like
174 // SHL dst, src, 1
175 // with
176 // ADD dst, src, src
177 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
178 input_other,
179 input_other);
180 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
181 RecordSimplification();
182 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000183 }
184}
185
Calin Juravle10e244f2015-01-26 18:54:32 +0000186void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
187 HInstruction* obj = null_check->InputAt(0);
188 if (!obj->CanBeNull()) {
189 null_check->ReplaceWith(obj);
190 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000191 if (stats_ != nullptr) {
192 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
193 }
194 }
195}
196
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100197bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
198 if (!input->CanBeNull()) {
199 return true;
200 }
201
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100202 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
203 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100204 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100205 return true;
206 }
207 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100208
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100209 return false;
210}
211
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100212// Returns whether doing a type test between the class of `object` against `klass` has
213// a statically known outcome. The result of the test is stored in `outcome`.
214static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000215 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
216 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
217 ScopedObjectAccess soa(Thread::Current());
218 if (!obj_rti.IsValid()) {
219 // We run the simplifier before the reference type propagation so type info might not be
220 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100221 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000222 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100223
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100224 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100225 if (!class_rti.IsValid()) {
226 // Happens when the loaded class is unresolved.
227 return false;
228 }
229 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000230 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100231 *outcome = true;
232 return true;
233 } else if (obj_rti.IsExact()) {
234 // The test failed at compile time so will also fail at runtime.
235 *outcome = false;
236 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100237 } else if (!class_rti.IsInterface()
238 && !obj_rti.IsInterface()
239 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100240 // Different type hierarchy. The test will fail.
241 *outcome = false;
242 return true;
243 }
244 return false;
245}
246
247void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
248 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100249 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
250 if (load_class->NeedsAccessCheck()) {
251 // If we need to perform an access check we cannot remove the instruction.
252 return;
253 }
254
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100255 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100256 check_cast->ClearMustDoNullCheck();
257 }
258
259 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000260 check_cast->GetBlock()->RemoveInstruction(check_cast);
261 if (stats_ != nullptr) {
262 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
263 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100264 return;
265 }
266
267 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700268 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100269 if (outcome) {
270 check_cast->GetBlock()->RemoveInstruction(check_cast);
271 if (stats_ != nullptr) {
272 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
273 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700274 if (!load_class->HasUses()) {
275 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
276 // However, here we know that it cannot because the checkcast was successfull, hence
277 // the class was already loaded.
278 load_class->GetBlock()->RemoveInstruction(load_class);
279 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100280 } else {
281 // Don't do anything for exceptional cases for now. Ideally we should remove
282 // all instructions and blocks this instruction dominates.
283 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000284 }
285}
286
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100287void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100288 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100289 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
290 if (load_class->NeedsAccessCheck()) {
291 // If we need to perform an access check we cannot remove the instruction.
292 return;
293 }
294
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100295 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100296 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100297 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100298 instruction->ClearMustDoNullCheck();
299 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100300
301 HGraph* graph = GetGraph();
302 if (object->IsNullConstant()) {
303 instruction->ReplaceWith(graph->GetIntConstant(0));
304 instruction->GetBlock()->RemoveInstruction(instruction);
305 RecordSimplification();
306 return;
307 }
308
309 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700310 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100311 if (outcome && can_be_null) {
312 // Type test will succeed, we just need a null test.
313 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
314 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
315 instruction->ReplaceWith(test);
316 } else {
317 // We've statically determined the result of the instanceof.
318 instruction->ReplaceWith(graph->GetIntConstant(outcome));
319 }
320 RecordSimplification();
321 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700322 if (outcome && !load_class->HasUses()) {
323 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
324 // However, here we know that it cannot because the instanceof check was successfull, hence
325 // the class was already loaded.
326 load_class->GetBlock()->RemoveInstruction(load_class);
327 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100328 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100329}
330
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100331void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
332 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100333 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100334 instruction->ClearValueCanBeNull();
335 }
336}
337
338void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
339 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100340 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100341 instruction->ClearValueCanBeNull();
342 }
343}
344
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000345void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100346 HBasicBlock* block = check->GetBlock();
347 // Currently always keep the suspend check at entry.
348 if (block->IsEntryBlock()) return;
349
350 // Currently always keep suspend checks at loop entry.
351 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
352 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
353 return;
354 }
355
356 // Remove the suspend check that was added at build time for the baseline
357 // compiler.
358 block->RemoveInstruction(check);
359}
360
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000361void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100362 HInstruction* input_const = equal->GetConstantRight();
363 if (input_const != nullptr) {
364 HInstruction* input_value = equal->GetLeastConstantLeft();
365 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
366 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100367 // We are comparing the boolean to a constant which is of type int and can
368 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100369 if (input_const->AsIntConstant()->IsOne()) {
370 // Replace (bool_value == true) with bool_value
371 equal->ReplaceWith(input_value);
372 block->RemoveInstruction(equal);
373 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100374 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500375 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
376 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100377 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100378 } else {
379 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
380 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
381 block->RemoveInstruction(equal);
382 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100383 }
Mark Mendellc4701932015-04-10 13:18:51 -0400384 } else {
385 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100386 }
Mark Mendellc4701932015-04-10 13:18:51 -0400387 } else {
388 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100389 }
390}
391
David Brazdil0d13fee2015-04-17 14:52:19 +0100392void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
393 HInstruction* input_const = not_equal->GetConstantRight();
394 if (input_const != nullptr) {
395 HInstruction* input_value = not_equal->GetLeastConstantLeft();
396 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
397 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100398 // We are comparing the boolean to a constant which is of type int and can
399 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100400 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500401 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
402 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100403 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100404 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100405 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100406 not_equal->ReplaceWith(input_value);
407 block->RemoveInstruction(not_equal);
408 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100409 } else {
410 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
411 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
412 block->RemoveInstruction(not_equal);
413 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100414 }
Mark Mendellc4701932015-04-10 13:18:51 -0400415 } else {
416 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100417 }
Mark Mendellc4701932015-04-10 13:18:51 -0400418 } else {
419 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100420 }
421}
422
423void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
424 HInstruction* parent = bool_not->InputAt(0);
425 if (parent->IsBooleanNot()) {
426 HInstruction* value = parent->InputAt(0);
427 // Replace (!(!bool_value)) with bool_value
428 bool_not->ReplaceWith(value);
429 bool_not->GetBlock()->RemoveInstruction(bool_not);
430 // It is possible that `parent` is dead at this point but we leave
431 // its removal to DCE for simplicity.
432 RecordSimplification();
433 }
434}
435
Mingyao Yang0304e182015-01-30 16:41:29 -0800436void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
437 HInstruction* input = instruction->InputAt(0);
438 // If the array is a NewArray with constant size, replace the array length
439 // with the constant instruction. This helps the bounds check elimination phase.
440 if (input->IsNewArray()) {
441 input = input->InputAt(0);
442 if (input->IsIntConstant()) {
443 instruction->ReplaceWith(input);
444 }
445 }
446}
447
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000448void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000449 HInstruction* value = instruction->GetValue();
450 if (value->GetType() != Primitive::kPrimNot) return;
451
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100452 if (CanEnsureNotNullAt(value, instruction)) {
453 instruction->ClearValueCanBeNull();
454 }
455
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000456 if (value->IsArrayGet()) {
457 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
458 // If the code is just swapping elements in the array, no need for a type check.
459 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100460 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000461 }
462 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100463
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100464 if (value->IsNullConstant()) {
465 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100466 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100467 }
468
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100469 ScopedObjectAccess soa(Thread::Current());
470 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
471 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
472 if (!array_rti.IsValid()) {
473 return;
474 }
475
476 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
477 instruction->ClearNeedsTypeCheck();
478 return;
479 }
480
481 if (array_rti.IsObjectArray()) {
482 if (array_rti.IsExact()) {
483 instruction->ClearNeedsTypeCheck();
484 return;
485 }
486 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100487 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000488}
489
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000490void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
491 if (instruction->GetResultType() == instruction->GetInputType()) {
492 // Remove the instruction if it's converting to the same type.
493 instruction->ReplaceWith(instruction->GetInput());
494 instruction->GetBlock()->RemoveInstruction(instruction);
495 }
496}
497
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000498void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
499 HConstant* input_cst = instruction->GetConstantRight();
500 HInstruction* input_other = instruction->GetLeastConstantLeft();
501 if ((input_cst != nullptr) && input_cst->IsZero()) {
502 // Replace code looking like
503 // ADD dst, src, 0
504 // with
505 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600506 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
507 // `x` is `-0.0`, the former expression yields `0.0`, while the later
508 // yields `-0.0`.
509 if (Primitive::IsIntegralType(instruction->GetType())) {
510 instruction->ReplaceWith(input_other);
511 instruction->GetBlock()->RemoveInstruction(instruction);
512 return;
513 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100514 }
515
516 HInstruction* left = instruction->GetLeft();
517 HInstruction* right = instruction->GetRight();
518 bool left_is_neg = left->IsNeg();
519 bool right_is_neg = right->IsNeg();
520
521 if (left_is_neg && right_is_neg) {
522 if (TryMoveNegOnInputsAfterBinop(instruction)) {
523 return;
524 }
525 }
526
527 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
528 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
529 // Replace code looking like
530 // NEG tmp, b
531 // ADD dst, a, tmp
532 // with
533 // SUB dst, a, b
534 // We do not perform the optimization if the input negation has environment
535 // uses or multiple non-environment uses as it could lead to worse code. In
536 // particular, we do not want the live range of `b` to be extended if we are
537 // not sure the initial 'NEG' instruction can be removed.
538 HInstruction* other = left_is_neg ? right : left;
539 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
540 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
541 RecordSimplification();
542 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000543 }
544}
545
546void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
547 HConstant* input_cst = instruction->GetConstantRight();
548 HInstruction* input_other = instruction->GetLeastConstantLeft();
549
Vladimir Marko452c1b62015-09-25 14:44:17 +0100550 if (input_cst != nullptr) {
551 int64_t value = Int64FromConstant(input_cst);
552 if (value == -1) {
553 // Replace code looking like
554 // AND dst, src, 0xFFF...FF
555 // with
556 // src
557 instruction->ReplaceWith(input_other);
558 instruction->GetBlock()->RemoveInstruction(instruction);
559 RecordSimplification();
560 return;
561 }
562 // Eliminate And from UShr+And if the And-mask contains all the bits that
563 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
564 // precisely clears the shifted-in sign bits.
565 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
566 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
567 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
568 size_t num_tail_bits_set = CTZ(value + 1);
569 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
570 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
571 instruction->ReplaceWith(input_other);
572 instruction->GetBlock()->RemoveInstruction(instruction);
573 RecordSimplification();
574 return;
575 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
576 input_other->HasOnlyOneNonEnvironmentUse()) {
577 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
578 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
579 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
580 input_other->InputAt(0),
581 input_other->InputAt(1),
582 input_other->GetDexPc());
583 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
584 input_other->GetBlock()->RemoveInstruction(input_other);
585 RecordSimplification();
586 return;
587 }
588 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000589 }
590
591 // We assume that GVN has run before, so we only perform a pointer comparison.
592 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100593 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000594 if (instruction->GetLeft() == instruction->GetRight()) {
595 // Replace code looking like
596 // AND dst, src, src
597 // with
598 // src
599 instruction->ReplaceWith(instruction->GetLeft());
600 instruction->GetBlock()->RemoveInstruction(instruction);
601 }
602}
603
Mark Mendellc4701932015-04-10 13:18:51 -0400604void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
605 VisitCondition(condition);
606}
607
608void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
609 VisitCondition(condition);
610}
611
612void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
613 VisitCondition(condition);
614}
615
616void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
617 VisitCondition(condition);
618}
619
Aart Bike9f37602015-10-09 11:15:55 -0700620// TODO: unsigned comparisons too?
621
Mark Mendellc4701932015-04-10 13:18:51 -0400622void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
623 // Try to fold an HCompare into this HCondition.
624
Roland Levillain7f63c522015-07-13 15:54:55 +0000625 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200626 // TODO: Implement it for MIPS and MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400627 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200628 if (instruction_set == kMips || instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400629 return;
630 }
631
632 HInstruction* left = condition->GetLeft();
633 HInstruction* right = condition->GetRight();
634 // We can only replace an HCondition which compares a Compare to 0.
635 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
636 // condition with a long, float or double comparison as input.
637 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
638 // Conversion is not possible.
639 return;
640 }
641
642 // Is the Compare only used for this purpose?
643 if (!left->GetUses().HasOnlyOneUse()) {
644 // Someone else also wants the result of the compare.
645 return;
646 }
647
648 if (!left->GetEnvUses().IsEmpty()) {
649 // There is a reference to the compare result in an environment. Do we really need it?
650 if (GetGraph()->IsDebuggable()) {
651 return;
652 }
653
654 // We have to ensure that there are no deopt points in the sequence.
655 if (left->HasAnyEnvironmentUseBefore(condition)) {
656 return;
657 }
658 }
659
660 // Clean up any environment uses from the HCompare, if any.
661 left->RemoveEnvironmentUsers();
662
663 // We have decided to fold the HCompare into the HCondition. Transfer the information.
664 condition->SetBias(left->AsCompare()->GetBias());
665
666 // Replace the operands of the HCondition.
667 condition->ReplaceInput(left->InputAt(0), 0);
668 condition->ReplaceInput(left->InputAt(1), 1);
669
670 // Remove the HCompare.
671 left->GetBlock()->RemoveInstruction(left);
672
673 RecordSimplification();
674}
675
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000676void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
677 HConstant* input_cst = instruction->GetConstantRight();
678 HInstruction* input_other = instruction->GetLeastConstantLeft();
679 Primitive::Type type = instruction->GetType();
680
681 if ((input_cst != nullptr) && input_cst->IsOne()) {
682 // Replace code looking like
683 // DIV dst, src, 1
684 // with
685 // src
686 instruction->ReplaceWith(input_other);
687 instruction->GetBlock()->RemoveInstruction(instruction);
688 return;
689 }
690
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000691 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000692 // Replace code looking like
693 // DIV dst, src, -1
694 // with
695 // NEG dst, src
696 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000697 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100698 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000699 return;
700 }
701
702 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
703 // Try replacing code looking like
704 // DIV dst, src, constant
705 // with
706 // MUL dst, src, 1 / constant
707 HConstant* reciprocal = nullptr;
708 if (type == Primitive::Primitive::kPrimDouble) {
709 double value = input_cst->AsDoubleConstant()->GetValue();
710 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
711 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
712 }
713 } else {
714 DCHECK_EQ(type, Primitive::kPrimFloat);
715 float value = input_cst->AsFloatConstant()->GetValue();
716 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
717 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
718 }
719 }
720
721 if (reciprocal != nullptr) {
722 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
723 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
724 RecordSimplification();
725 return;
726 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000727 }
728}
729
730void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
731 HConstant* input_cst = instruction->GetConstantRight();
732 HInstruction* input_other = instruction->GetLeastConstantLeft();
733 Primitive::Type type = instruction->GetType();
734 HBasicBlock* block = instruction->GetBlock();
735 ArenaAllocator* allocator = GetGraph()->GetArena();
736
737 if (input_cst == nullptr) {
738 return;
739 }
740
741 if (input_cst->IsOne()) {
742 // Replace code looking like
743 // MUL dst, src, 1
744 // with
745 // src
746 instruction->ReplaceWith(input_other);
747 instruction->GetBlock()->RemoveInstruction(instruction);
748 return;
749 }
750
751 if (input_cst->IsMinusOne() &&
752 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
753 // Replace code looking like
754 // MUL dst, src, -1
755 // with
756 // NEG dst, src
757 HNeg* neg = new (allocator) HNeg(type, input_other);
758 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100759 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000760 return;
761 }
762
763 if (Primitive::IsFloatingPointType(type) &&
764 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
765 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
766 // Replace code looking like
767 // FP_MUL dst, src, 2.0
768 // with
769 // FP_ADD dst, src, src
770 // The 'int' and 'long' cases are handled below.
771 block->ReplaceAndRemoveInstructionWith(instruction,
772 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100773 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000774 return;
775 }
776
777 if (Primitive::IsIntOrLongType(type)) {
778 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600779 // Even though constant propagation also takes care of the zero case, other
780 // optimizations can lead to having a zero multiplication.
781 if (factor == 0) {
782 // Replace code looking like
783 // MUL dst, src, 0
784 // with
785 // 0
786 instruction->ReplaceWith(input_cst);
787 instruction->GetBlock()->RemoveInstruction(instruction);
788 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000789 // Replace code looking like
790 // MUL dst, src, pow_of_2
791 // with
792 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000793 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000794 HShl* shl = new(allocator) HShl(type, input_other, shift);
795 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100796 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +0000797 } else if (IsPowerOfTwo(factor - 1)) {
798 // Transform code looking like
799 // MUL dst, src, (2^n + 1)
800 // into
801 // SHL tmp, src, n
802 // ADD dst, src, tmp
803 HShl* shl = new (allocator) HShl(type,
804 input_other,
805 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
806 HAdd* add = new (allocator) HAdd(type, input_other, shl);
807
808 block->InsertInstructionBefore(shl, instruction);
809 block->ReplaceAndRemoveInstructionWith(instruction, add);
810 RecordSimplification();
811 } else if (IsPowerOfTwo(factor + 1)) {
812 // Transform code looking like
813 // MUL dst, src, (2^n - 1)
814 // into
815 // SHL tmp, src, n
816 // SUB dst, tmp, src
817 HShl* shl = new (allocator) HShl(type,
818 input_other,
819 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
820 HSub* sub = new (allocator) HSub(type, shl, input_other);
821
822 block->InsertInstructionBefore(shl, instruction);
823 block->ReplaceAndRemoveInstructionWith(instruction, sub);
824 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000825 }
826 }
827}
828
Alexandre Rames188d4312015-04-09 18:30:21 +0100829void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
830 HInstruction* input = instruction->GetInput();
831 if (input->IsNeg()) {
832 // Replace code looking like
833 // NEG tmp, src
834 // NEG dst, tmp
835 // with
836 // src
837 HNeg* previous_neg = input->AsNeg();
838 instruction->ReplaceWith(previous_neg->GetInput());
839 instruction->GetBlock()->RemoveInstruction(instruction);
840 // We perform the optimization even if the input negation has environment
841 // uses since it allows removing the current instruction. But we only delete
842 // the input negation only if it is does not have any uses left.
843 if (!previous_neg->HasUses()) {
844 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
845 }
846 RecordSimplification();
847 return;
848 }
849
Serguei Katkov339dfc22015-04-20 12:29:32 +0600850 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
851 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100852 // Replace code looking like
853 // SUB tmp, a, b
854 // NEG dst, tmp
855 // with
856 // SUB dst, b, a
857 // We do not perform the optimization if the input subtraction has
858 // environment uses or multiple non-environment uses as it could lead to
859 // worse code. In particular, we do not want the live ranges of `a` and `b`
860 // to be extended if we are not sure the initial 'SUB' instruction can be
861 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600862 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100863 HSub* sub = input->AsSub();
864 HSub* new_sub =
865 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
866 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
867 if (!sub->HasUses()) {
868 sub->GetBlock()->RemoveInstruction(sub);
869 }
870 RecordSimplification();
871 }
872}
873
874void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
875 HInstruction* input = instruction->GetInput();
876 if (input->IsNot()) {
877 // Replace code looking like
878 // NOT tmp, src
879 // NOT dst, tmp
880 // with
881 // src
882 // We perform the optimization even if the input negation has environment
883 // uses since it allows removing the current instruction. But we only delete
884 // the input negation only if it is does not have any uses left.
885 HNot* previous_not = input->AsNot();
886 instruction->ReplaceWith(previous_not->GetInput());
887 instruction->GetBlock()->RemoveInstruction(instruction);
888 if (!previous_not->HasUses()) {
889 previous_not->GetBlock()->RemoveInstruction(previous_not);
890 }
891 RecordSimplification();
892 }
893}
894
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000895void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
896 HConstant* input_cst = instruction->GetConstantRight();
897 HInstruction* input_other = instruction->GetLeastConstantLeft();
898
899 if ((input_cst != nullptr) && input_cst->IsZero()) {
900 // Replace code looking like
901 // OR dst, src, 0
902 // with
903 // src
904 instruction->ReplaceWith(input_other);
905 instruction->GetBlock()->RemoveInstruction(instruction);
906 return;
907 }
908
909 // We assume that GVN has run before, so we only perform a pointer comparison.
910 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100911 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000912 if (instruction->GetLeft() == instruction->GetRight()) {
913 // Replace code looking like
914 // OR dst, src, src
915 // with
916 // src
917 instruction->ReplaceWith(instruction->GetLeft());
918 instruction->GetBlock()->RemoveInstruction(instruction);
919 }
920}
921
922void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
923 VisitShift(instruction);
924}
925
926void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
927 VisitShift(instruction);
928}
929
930void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
931 HConstant* input_cst = instruction->GetConstantRight();
932 HInstruction* input_other = instruction->GetLeastConstantLeft();
933
Serguei Katkov115b53f2015-08-05 17:03:30 +0600934 Primitive::Type type = instruction->GetType();
935 if (Primitive::IsFloatingPointType(type)) {
936 return;
937 }
938
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000939 if ((input_cst != nullptr) && input_cst->IsZero()) {
940 // Replace code looking like
941 // SUB dst, src, 0
942 // with
943 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600944 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
945 // `x` is `-0.0`, the former expression yields `0.0`, while the later
946 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000947 instruction->ReplaceWith(input_other);
948 instruction->GetBlock()->RemoveInstruction(instruction);
949 return;
950 }
951
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000952 HBasicBlock* block = instruction->GetBlock();
953 ArenaAllocator* allocator = GetGraph()->GetArena();
954
Alexandre Rames188d4312015-04-09 18:30:21 +0100955 HInstruction* left = instruction->GetLeft();
956 HInstruction* right = instruction->GetRight();
957 if (left->IsConstant()) {
958 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000959 // Replace code looking like
960 // SUB dst, 0, src
961 // with
962 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100963 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000964 // `x` is `0.0`, the former expression yields `0.0`, while the later
965 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100966 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000967 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100968 RecordSimplification();
969 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000970 }
971 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100972
973 if (left->IsNeg() && right->IsNeg()) {
974 if (TryMoveNegOnInputsAfterBinop(instruction)) {
975 return;
976 }
977 }
978
979 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
980 // Replace code looking like
981 // NEG tmp, b
982 // SUB dst, a, tmp
983 // with
984 // ADD dst, a, b
985 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
986 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
987 RecordSimplification();
988 right->GetBlock()->RemoveInstruction(right);
989 return;
990 }
991
992 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
993 // Replace code looking like
994 // NEG tmp, a
995 // SUB dst, tmp, b
996 // with
997 // ADD tmp, a, b
998 // NEG dst, tmp
999 // The second version is not intrinsically better, but enables more
1000 // transformations.
1001 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1002 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1003 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1004 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1005 instruction->ReplaceWith(neg);
1006 instruction->GetBlock()->RemoveInstruction(instruction);
1007 RecordSimplification();
1008 left->GetBlock()->RemoveInstruction(left);
1009 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001010}
1011
1012void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1013 VisitShift(instruction);
1014}
1015
1016void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1017 HConstant* input_cst = instruction->GetConstantRight();
1018 HInstruction* input_other = instruction->GetLeastConstantLeft();
1019
1020 if ((input_cst != nullptr) && input_cst->IsZero()) {
1021 // Replace code looking like
1022 // XOR dst, src, 0
1023 // with
1024 // src
1025 instruction->ReplaceWith(input_other);
1026 instruction->GetBlock()->RemoveInstruction(instruction);
1027 return;
1028 }
1029
1030 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1031 // Replace code looking like
1032 // XOR dst, src, 0xFFF...FF
1033 // with
1034 // NOT dst, src
1035 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1036 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001037 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001038 return;
1039 }
1040}
1041
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +01001042void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
1043 HInstruction* actual_string = nullptr;
1044
1045 // Find the string we need to replace this instruction with. The actual string is
1046 // the return value of a StringFactory call.
1047 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1048 HInstruction* use = it.Current()->GetUser();
1049 if (use->IsInvokeStaticOrDirect()
1050 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
1051 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
1052 actual_string = use;
1053 break;
1054 }
1055 }
1056
1057 // Check that there is no other instruction that thinks it is the factory for that string.
1058 if (kIsDebugBuild) {
1059 CHECK(actual_string != nullptr);
1060 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1061 HInstruction* use = it.Current()->GetUser();
1062 if (use->IsInvokeStaticOrDirect()) {
1063 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
1064 }
1065 }
1066 }
1067
1068 // We need to remove any environment uses of the fake string that are not dominated by
1069 // `actual_string` to null.
1070 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
1071 HEnvironment* environment = it.Current()->GetUser();
1072 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
1073 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
1074 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
1075 }
1076 }
1077
1078 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
1079 // `instruction`.
1080 instruction->ReplaceWith(actual_string);
1081 instruction->GetBlock()->RemoveInstruction(instruction);
1082}
1083
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001084void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1085 HInstruction* argument = instruction->InputAt(1);
1086 HInstruction* receiver = instruction->InputAt(0);
1087 if (receiver == argument) {
1088 // Because String.equals is an instance call, the receiver is
1089 // a null check if we don't know it's null. The argument however, will
1090 // be the actual object. So we cannot end up in a situation where both
1091 // are equal but could be null.
1092 DCHECK(CanEnsureNotNullAt(argument, instruction));
1093 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1094 instruction->GetBlock()->RemoveInstruction(instruction);
1095 } else {
1096 StringEqualsOptimizations optimizations(instruction);
1097 if (CanEnsureNotNullAt(argument, instruction)) {
1098 optimizations.SetArgumentNotNull();
1099 }
1100 ScopedObjectAccess soa(Thread::Current());
1101 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1102 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1103 optimizations.SetArgumentIsString();
1104 }
1105 }
1106}
1107
1108static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1109 if (potential_length->IsArrayLength()) {
1110 return potential_length->InputAt(0) == potential_array;
1111 }
1112
1113 if (potential_array->IsNewArray()) {
1114 return potential_array->InputAt(0) == potential_length;
1115 }
1116
1117 return false;
1118}
1119
1120void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1121 HInstruction* source = instruction->InputAt(0);
1122 HInstruction* destination = instruction->InputAt(2);
1123 HInstruction* count = instruction->InputAt(4);
1124 SystemArrayCopyOptimizations optimizations(instruction);
1125 if (CanEnsureNotNullAt(source, instruction)) {
1126 optimizations.SetSourceIsNotNull();
1127 }
1128 if (CanEnsureNotNullAt(destination, instruction)) {
1129 optimizations.SetDestinationIsNotNull();
1130 }
1131 if (destination == source) {
1132 optimizations.SetDestinationIsSource();
1133 }
1134
1135 if (IsArrayLengthOf(count, source)) {
1136 optimizations.SetCountIsSourceLength();
1137 }
1138
1139 if (IsArrayLengthOf(count, destination)) {
1140 optimizations.SetCountIsDestinationLength();
1141 }
1142
1143 {
1144 ScopedObjectAccess soa(Thread::Current());
1145 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1146 if (destination_rti.IsValid()) {
1147 if (destination_rti.IsObjectArray()) {
1148 if (destination_rti.IsExact()) {
1149 optimizations.SetDoesNotNeedTypeCheck();
1150 }
1151 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001152 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001153 if (destination_rti.IsPrimitiveArrayClass()) {
1154 optimizations.SetDestinationIsPrimitiveArray();
1155 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1156 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001157 }
1158 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001159 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1160 if (source_rti.IsValid()) {
1161 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1162 optimizations.SetDoesNotNeedTypeCheck();
1163 }
1164 if (source_rti.IsPrimitiveArrayClass()) {
1165 optimizations.SetSourceIsPrimitiveArray();
1166 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1167 optimizations.SetSourceIsNonPrimitiveArray();
1168 }
1169 }
1170 }
1171}
1172
1173void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1174 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1175 SimplifyStringEquals(instruction);
1176 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1177 SimplifySystemArrayCopy(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001178 }
1179}
1180
Aart Bikbb245d12015-10-19 11:05:03 -07001181void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1182 HInstruction* cond = deoptimize->InputAt(0);
1183 if (cond->IsConstant()) {
1184 if (cond->AsIntConstant()->IsZero()) {
1185 // Never deopt: instruction can be removed.
1186 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1187 } else {
1188 // Always deopt.
1189 }
1190 }
1191}
1192
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001193} // namespace art