blob: b97dc1a5119f9007c248ae65ea66a23894133f8a [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()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100375 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100376 block->ReplaceAndRemoveInstructionWith(
377 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
378 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100379 } else {
380 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
381 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
382 block->RemoveInstruction(equal);
383 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100384 }
Mark Mendellc4701932015-04-10 13:18:51 -0400385 } else {
386 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100387 }
Mark Mendellc4701932015-04-10 13:18:51 -0400388 } else {
389 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100390 }
391}
392
David Brazdil0d13fee2015-04-17 14:52:19 +0100393void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
394 HInstruction* input_const = not_equal->GetConstantRight();
395 if (input_const != nullptr) {
396 HInstruction* input_value = not_equal->GetLeastConstantLeft();
397 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
398 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100399 // We are comparing the boolean to a constant which is of type int and can
400 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100401 if (input_const->AsIntConstant()->IsOne()) {
402 // Replace (bool_value != true) with !bool_value
403 block->ReplaceAndRemoveInstructionWith(
404 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
405 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100406 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100407 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100408 not_equal->ReplaceWith(input_value);
409 block->RemoveInstruction(not_equal);
410 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100411 } else {
412 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
413 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
414 block->RemoveInstruction(not_equal);
415 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100416 }
Mark Mendellc4701932015-04-10 13:18:51 -0400417 } else {
418 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100419 }
Mark Mendellc4701932015-04-10 13:18:51 -0400420 } else {
421 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100422 }
423}
424
425void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
426 HInstruction* parent = bool_not->InputAt(0);
427 if (parent->IsBooleanNot()) {
428 HInstruction* value = parent->InputAt(0);
429 // Replace (!(!bool_value)) with bool_value
430 bool_not->ReplaceWith(value);
431 bool_not->GetBlock()->RemoveInstruction(bool_not);
432 // It is possible that `parent` is dead at this point but we leave
433 // its removal to DCE for simplicity.
434 RecordSimplification();
435 }
436}
437
Mingyao Yang0304e182015-01-30 16:41:29 -0800438void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
439 HInstruction* input = instruction->InputAt(0);
440 // If the array is a NewArray with constant size, replace the array length
441 // with the constant instruction. This helps the bounds check elimination phase.
442 if (input->IsNewArray()) {
443 input = input->InputAt(0);
444 if (input->IsIntConstant()) {
445 instruction->ReplaceWith(input);
446 }
447 }
448}
449
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000450void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000451 HInstruction* value = instruction->GetValue();
452 if (value->GetType() != Primitive::kPrimNot) return;
453
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100454 if (CanEnsureNotNullAt(value, instruction)) {
455 instruction->ClearValueCanBeNull();
456 }
457
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000458 if (value->IsArrayGet()) {
459 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
460 // If the code is just swapping elements in the array, no need for a type check.
461 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100462 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000463 }
464 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100465
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100466 if (value->IsNullConstant()) {
467 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100468 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100469 }
470
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100471 ScopedObjectAccess soa(Thread::Current());
472 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
473 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
474 if (!array_rti.IsValid()) {
475 return;
476 }
477
478 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
479 instruction->ClearNeedsTypeCheck();
480 return;
481 }
482
483 if (array_rti.IsObjectArray()) {
484 if (array_rti.IsExact()) {
485 instruction->ClearNeedsTypeCheck();
486 return;
487 }
488 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100489 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000490}
491
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000492void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
493 if (instruction->GetResultType() == instruction->GetInputType()) {
494 // Remove the instruction if it's converting to the same type.
495 instruction->ReplaceWith(instruction->GetInput());
496 instruction->GetBlock()->RemoveInstruction(instruction);
497 }
498}
499
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000500void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
501 HConstant* input_cst = instruction->GetConstantRight();
502 HInstruction* input_other = instruction->GetLeastConstantLeft();
503 if ((input_cst != nullptr) && input_cst->IsZero()) {
504 // Replace code looking like
505 // ADD dst, src, 0
506 // with
507 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600508 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
509 // `x` is `-0.0`, the former expression yields `0.0`, while the later
510 // yields `-0.0`.
511 if (Primitive::IsIntegralType(instruction->GetType())) {
512 instruction->ReplaceWith(input_other);
513 instruction->GetBlock()->RemoveInstruction(instruction);
514 return;
515 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100516 }
517
518 HInstruction* left = instruction->GetLeft();
519 HInstruction* right = instruction->GetRight();
520 bool left_is_neg = left->IsNeg();
521 bool right_is_neg = right->IsNeg();
522
523 if (left_is_neg && right_is_neg) {
524 if (TryMoveNegOnInputsAfterBinop(instruction)) {
525 return;
526 }
527 }
528
529 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
530 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
531 // Replace code looking like
532 // NEG tmp, b
533 // ADD dst, a, tmp
534 // with
535 // SUB dst, a, b
536 // We do not perform the optimization if the input negation has environment
537 // uses or multiple non-environment uses as it could lead to worse code. In
538 // particular, we do not want the live range of `b` to be extended if we are
539 // not sure the initial 'NEG' instruction can be removed.
540 HInstruction* other = left_is_neg ? right : left;
541 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
542 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
543 RecordSimplification();
544 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000545 }
546}
547
548void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
549 HConstant* input_cst = instruction->GetConstantRight();
550 HInstruction* input_other = instruction->GetLeastConstantLeft();
551
Vladimir Marko452c1b62015-09-25 14:44:17 +0100552 if (input_cst != nullptr) {
553 int64_t value = Int64FromConstant(input_cst);
554 if (value == -1) {
555 // Replace code looking like
556 // AND dst, src, 0xFFF...FF
557 // with
558 // src
559 instruction->ReplaceWith(input_other);
560 instruction->GetBlock()->RemoveInstruction(instruction);
561 RecordSimplification();
562 return;
563 }
564 // Eliminate And from UShr+And if the And-mask contains all the bits that
565 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
566 // precisely clears the shifted-in sign bits.
567 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
568 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
569 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
570 size_t num_tail_bits_set = CTZ(value + 1);
571 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
572 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
573 instruction->ReplaceWith(input_other);
574 instruction->GetBlock()->RemoveInstruction(instruction);
575 RecordSimplification();
576 return;
577 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
578 input_other->HasOnlyOneNonEnvironmentUse()) {
579 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
580 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
581 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
582 input_other->InputAt(0),
583 input_other->InputAt(1),
584 input_other->GetDexPc());
585 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
586 input_other->GetBlock()->RemoveInstruction(input_other);
587 RecordSimplification();
588 return;
589 }
590 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000591 }
592
593 // We assume that GVN has run before, so we only perform a pointer comparison.
594 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100595 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000596 if (instruction->GetLeft() == instruction->GetRight()) {
597 // Replace code looking like
598 // AND dst, src, src
599 // with
600 // src
601 instruction->ReplaceWith(instruction->GetLeft());
602 instruction->GetBlock()->RemoveInstruction(instruction);
603 }
604}
605
Mark Mendellc4701932015-04-10 13:18:51 -0400606void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
607 VisitCondition(condition);
608}
609
610void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
611 VisitCondition(condition);
612}
613
614void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
615 VisitCondition(condition);
616}
617
618void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
619 VisitCondition(condition);
620}
621
Aart Bike9f37602015-10-09 11:15:55 -0700622// TODO: unsigned comparisons too?
623
Mark Mendellc4701932015-04-10 13:18:51 -0400624void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
625 // Try to fold an HCompare into this HCondition.
626
Roland Levillain7f63c522015-07-13 15:54:55 +0000627 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200628 // TODO: Implement it for MIPS and MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400629 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200630 if (instruction_set == kMips || instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400631 return;
632 }
633
634 HInstruction* left = condition->GetLeft();
635 HInstruction* right = condition->GetRight();
636 // We can only replace an HCondition which compares a Compare to 0.
637 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
638 // condition with a long, float or double comparison as input.
639 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
640 // Conversion is not possible.
641 return;
642 }
643
644 // Is the Compare only used for this purpose?
645 if (!left->GetUses().HasOnlyOneUse()) {
646 // Someone else also wants the result of the compare.
647 return;
648 }
649
650 if (!left->GetEnvUses().IsEmpty()) {
651 // There is a reference to the compare result in an environment. Do we really need it?
652 if (GetGraph()->IsDebuggable()) {
653 return;
654 }
655
656 // We have to ensure that there are no deopt points in the sequence.
657 if (left->HasAnyEnvironmentUseBefore(condition)) {
658 return;
659 }
660 }
661
662 // Clean up any environment uses from the HCompare, if any.
663 left->RemoveEnvironmentUsers();
664
665 // We have decided to fold the HCompare into the HCondition. Transfer the information.
666 condition->SetBias(left->AsCompare()->GetBias());
667
668 // Replace the operands of the HCondition.
669 condition->ReplaceInput(left->InputAt(0), 0);
670 condition->ReplaceInput(left->InputAt(1), 1);
671
672 // Remove the HCompare.
673 left->GetBlock()->RemoveInstruction(left);
674
675 RecordSimplification();
676}
677
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000678void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
679 HConstant* input_cst = instruction->GetConstantRight();
680 HInstruction* input_other = instruction->GetLeastConstantLeft();
681 Primitive::Type type = instruction->GetType();
682
683 if ((input_cst != nullptr) && input_cst->IsOne()) {
684 // Replace code looking like
685 // DIV dst, src, 1
686 // with
687 // src
688 instruction->ReplaceWith(input_other);
689 instruction->GetBlock()->RemoveInstruction(instruction);
690 return;
691 }
692
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000693 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000694 // Replace code looking like
695 // DIV dst, src, -1
696 // with
697 // NEG dst, src
698 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000699 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100700 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000701 return;
702 }
703
704 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
705 // Try replacing code looking like
706 // DIV dst, src, constant
707 // with
708 // MUL dst, src, 1 / constant
709 HConstant* reciprocal = nullptr;
710 if (type == Primitive::Primitive::kPrimDouble) {
711 double value = input_cst->AsDoubleConstant()->GetValue();
712 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
713 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
714 }
715 } else {
716 DCHECK_EQ(type, Primitive::kPrimFloat);
717 float value = input_cst->AsFloatConstant()->GetValue();
718 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
719 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
720 }
721 }
722
723 if (reciprocal != nullptr) {
724 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
725 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
726 RecordSimplification();
727 return;
728 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000729 }
730}
731
732void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
733 HConstant* input_cst = instruction->GetConstantRight();
734 HInstruction* input_other = instruction->GetLeastConstantLeft();
735 Primitive::Type type = instruction->GetType();
736 HBasicBlock* block = instruction->GetBlock();
737 ArenaAllocator* allocator = GetGraph()->GetArena();
738
739 if (input_cst == nullptr) {
740 return;
741 }
742
743 if (input_cst->IsOne()) {
744 // Replace code looking like
745 // MUL dst, src, 1
746 // with
747 // src
748 instruction->ReplaceWith(input_other);
749 instruction->GetBlock()->RemoveInstruction(instruction);
750 return;
751 }
752
753 if (input_cst->IsMinusOne() &&
754 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
755 // Replace code looking like
756 // MUL dst, src, -1
757 // with
758 // NEG dst, src
759 HNeg* neg = new (allocator) HNeg(type, input_other);
760 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100761 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000762 return;
763 }
764
765 if (Primitive::IsFloatingPointType(type) &&
766 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
767 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
768 // Replace code looking like
769 // FP_MUL dst, src, 2.0
770 // with
771 // FP_ADD dst, src, src
772 // The 'int' and 'long' cases are handled below.
773 block->ReplaceAndRemoveInstructionWith(instruction,
774 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100775 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000776 return;
777 }
778
779 if (Primitive::IsIntOrLongType(type)) {
780 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600781 // Even though constant propagation also takes care of the zero case, other
782 // optimizations can lead to having a zero multiplication.
783 if (factor == 0) {
784 // Replace code looking like
785 // MUL dst, src, 0
786 // with
787 // 0
788 instruction->ReplaceWith(input_cst);
789 instruction->GetBlock()->RemoveInstruction(instruction);
790 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000791 // Replace code looking like
792 // MUL dst, src, pow_of_2
793 // with
794 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000795 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000796 HShl* shl = new(allocator) HShl(type, input_other, shift);
797 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100798 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000799 }
800 }
801}
802
Alexandre Rames188d4312015-04-09 18:30:21 +0100803void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
804 HInstruction* input = instruction->GetInput();
805 if (input->IsNeg()) {
806 // Replace code looking like
807 // NEG tmp, src
808 // NEG dst, tmp
809 // with
810 // src
811 HNeg* previous_neg = input->AsNeg();
812 instruction->ReplaceWith(previous_neg->GetInput());
813 instruction->GetBlock()->RemoveInstruction(instruction);
814 // We perform the optimization even if the input negation has environment
815 // uses since it allows removing the current instruction. But we only delete
816 // the input negation only if it is does not have any uses left.
817 if (!previous_neg->HasUses()) {
818 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
819 }
820 RecordSimplification();
821 return;
822 }
823
Serguei Katkov339dfc22015-04-20 12:29:32 +0600824 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
825 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100826 // Replace code looking like
827 // SUB tmp, a, b
828 // NEG dst, tmp
829 // with
830 // SUB dst, b, a
831 // We do not perform the optimization if the input subtraction has
832 // environment uses or multiple non-environment uses as it could lead to
833 // worse code. In particular, we do not want the live ranges of `a` and `b`
834 // to be extended if we are not sure the initial 'SUB' instruction can be
835 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600836 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100837 HSub* sub = input->AsSub();
838 HSub* new_sub =
839 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
840 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
841 if (!sub->HasUses()) {
842 sub->GetBlock()->RemoveInstruction(sub);
843 }
844 RecordSimplification();
845 }
846}
847
848void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
849 HInstruction* input = instruction->GetInput();
850 if (input->IsNot()) {
851 // Replace code looking like
852 // NOT tmp, src
853 // NOT dst, tmp
854 // with
855 // src
856 // We perform the optimization even if the input negation has environment
857 // uses since it allows removing the current instruction. But we only delete
858 // the input negation only if it is does not have any uses left.
859 HNot* previous_not = input->AsNot();
860 instruction->ReplaceWith(previous_not->GetInput());
861 instruction->GetBlock()->RemoveInstruction(instruction);
862 if (!previous_not->HasUses()) {
863 previous_not->GetBlock()->RemoveInstruction(previous_not);
864 }
865 RecordSimplification();
866 }
867}
868
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000869void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
870 HConstant* input_cst = instruction->GetConstantRight();
871 HInstruction* input_other = instruction->GetLeastConstantLeft();
872
873 if ((input_cst != nullptr) && input_cst->IsZero()) {
874 // Replace code looking like
875 // OR dst, src, 0
876 // with
877 // src
878 instruction->ReplaceWith(input_other);
879 instruction->GetBlock()->RemoveInstruction(instruction);
880 return;
881 }
882
883 // We assume that GVN has run before, so we only perform a pointer comparison.
884 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100885 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000886 if (instruction->GetLeft() == instruction->GetRight()) {
887 // Replace code looking like
888 // OR dst, src, src
889 // with
890 // src
891 instruction->ReplaceWith(instruction->GetLeft());
892 instruction->GetBlock()->RemoveInstruction(instruction);
893 }
894}
895
896void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
897 VisitShift(instruction);
898}
899
900void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
901 VisitShift(instruction);
902}
903
904void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
905 HConstant* input_cst = instruction->GetConstantRight();
906 HInstruction* input_other = instruction->GetLeastConstantLeft();
907
Serguei Katkov115b53f2015-08-05 17:03:30 +0600908 Primitive::Type type = instruction->GetType();
909 if (Primitive::IsFloatingPointType(type)) {
910 return;
911 }
912
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000913 if ((input_cst != nullptr) && input_cst->IsZero()) {
914 // Replace code looking like
915 // SUB dst, src, 0
916 // with
917 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600918 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
919 // `x` is `-0.0`, the former expression yields `0.0`, while the later
920 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000921 instruction->ReplaceWith(input_other);
922 instruction->GetBlock()->RemoveInstruction(instruction);
923 return;
924 }
925
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000926 HBasicBlock* block = instruction->GetBlock();
927 ArenaAllocator* allocator = GetGraph()->GetArena();
928
Alexandre Rames188d4312015-04-09 18:30:21 +0100929 HInstruction* left = instruction->GetLeft();
930 HInstruction* right = instruction->GetRight();
931 if (left->IsConstant()) {
932 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000933 // Replace code looking like
934 // SUB dst, 0, src
935 // with
936 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100937 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000938 // `x` is `0.0`, the former expression yields `0.0`, while the later
939 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100940 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000941 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100942 RecordSimplification();
943 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000944 }
945 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100946
947 if (left->IsNeg() && right->IsNeg()) {
948 if (TryMoveNegOnInputsAfterBinop(instruction)) {
949 return;
950 }
951 }
952
953 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
954 // Replace code looking like
955 // NEG tmp, b
956 // SUB dst, a, tmp
957 // with
958 // ADD dst, a, b
959 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
960 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
961 RecordSimplification();
962 right->GetBlock()->RemoveInstruction(right);
963 return;
964 }
965
966 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
967 // Replace code looking like
968 // NEG tmp, a
969 // SUB dst, tmp, b
970 // with
971 // ADD tmp, a, b
972 // NEG dst, tmp
973 // The second version is not intrinsically better, but enables more
974 // transformations.
975 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
976 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
977 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
978 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
979 instruction->ReplaceWith(neg);
980 instruction->GetBlock()->RemoveInstruction(instruction);
981 RecordSimplification();
982 left->GetBlock()->RemoveInstruction(left);
983 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000984}
985
986void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
987 VisitShift(instruction);
988}
989
990void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
991 HConstant* input_cst = instruction->GetConstantRight();
992 HInstruction* input_other = instruction->GetLeastConstantLeft();
993
994 if ((input_cst != nullptr) && input_cst->IsZero()) {
995 // Replace code looking like
996 // XOR dst, src, 0
997 // with
998 // src
999 instruction->ReplaceWith(input_other);
1000 instruction->GetBlock()->RemoveInstruction(instruction);
1001 return;
1002 }
1003
1004 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1005 // Replace code looking like
1006 // XOR dst, src, 0xFFF...FF
1007 // with
1008 // NOT dst, src
1009 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1010 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001011 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001012 return;
1013 }
1014}
1015
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +01001016void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
1017 HInstruction* actual_string = nullptr;
1018
1019 // Find the string we need to replace this instruction with. The actual string is
1020 // the return value of a StringFactory call.
1021 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1022 HInstruction* use = it.Current()->GetUser();
1023 if (use->IsInvokeStaticOrDirect()
1024 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
1025 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
1026 actual_string = use;
1027 break;
1028 }
1029 }
1030
1031 // Check that there is no other instruction that thinks it is the factory for that string.
1032 if (kIsDebugBuild) {
1033 CHECK(actual_string != nullptr);
1034 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1035 HInstruction* use = it.Current()->GetUser();
1036 if (use->IsInvokeStaticOrDirect()) {
1037 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
1038 }
1039 }
1040 }
1041
1042 // We need to remove any environment uses of the fake string that are not dominated by
1043 // `actual_string` to null.
1044 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
1045 HEnvironment* environment = it.Current()->GetUser();
1046 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
1047 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
1048 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
1049 }
1050 }
1051
1052 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
1053 // `instruction`.
1054 instruction->ReplaceWith(actual_string);
1055 instruction->GetBlock()->RemoveInstruction(instruction);
1056}
1057
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001058void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1059 HInstruction* argument = instruction->InputAt(1);
1060 HInstruction* receiver = instruction->InputAt(0);
1061 if (receiver == argument) {
1062 // Because String.equals is an instance call, the receiver is
1063 // a null check if we don't know it's null. The argument however, will
1064 // be the actual object. So we cannot end up in a situation where both
1065 // are equal but could be null.
1066 DCHECK(CanEnsureNotNullAt(argument, instruction));
1067 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1068 instruction->GetBlock()->RemoveInstruction(instruction);
1069 } else {
1070 StringEqualsOptimizations optimizations(instruction);
1071 if (CanEnsureNotNullAt(argument, instruction)) {
1072 optimizations.SetArgumentNotNull();
1073 }
1074 ScopedObjectAccess soa(Thread::Current());
1075 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1076 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1077 optimizations.SetArgumentIsString();
1078 }
1079 }
1080}
1081
1082static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1083 if (potential_length->IsArrayLength()) {
1084 return potential_length->InputAt(0) == potential_array;
1085 }
1086
1087 if (potential_array->IsNewArray()) {
1088 return potential_array->InputAt(0) == potential_length;
1089 }
1090
1091 return false;
1092}
1093
1094void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1095 HInstruction* source = instruction->InputAt(0);
1096 HInstruction* destination = instruction->InputAt(2);
1097 HInstruction* count = instruction->InputAt(4);
1098 SystemArrayCopyOptimizations optimizations(instruction);
1099 if (CanEnsureNotNullAt(source, instruction)) {
1100 optimizations.SetSourceIsNotNull();
1101 }
1102 if (CanEnsureNotNullAt(destination, instruction)) {
1103 optimizations.SetDestinationIsNotNull();
1104 }
1105 if (destination == source) {
1106 optimizations.SetDestinationIsSource();
1107 }
1108
1109 if (IsArrayLengthOf(count, source)) {
1110 optimizations.SetCountIsSourceLength();
1111 }
1112
1113 if (IsArrayLengthOf(count, destination)) {
1114 optimizations.SetCountIsDestinationLength();
1115 }
1116
1117 {
1118 ScopedObjectAccess soa(Thread::Current());
1119 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1120 if (destination_rti.IsValid()) {
1121 if (destination_rti.IsObjectArray()) {
1122 if (destination_rti.IsExact()) {
1123 optimizations.SetDoesNotNeedTypeCheck();
1124 }
1125 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001126 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001127 if (destination_rti.IsPrimitiveArrayClass()) {
1128 optimizations.SetDestinationIsPrimitiveArray();
1129 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1130 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001131 }
1132 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001133 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1134 if (source_rti.IsValid()) {
1135 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1136 optimizations.SetDoesNotNeedTypeCheck();
1137 }
1138 if (source_rti.IsPrimitiveArrayClass()) {
1139 optimizations.SetSourceIsPrimitiveArray();
1140 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1141 optimizations.SetSourceIsNonPrimitiveArray();
1142 }
1143 }
1144 }
1145}
1146
1147void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1148 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1149 SimplifyStringEquals(instruction);
1150 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1151 SimplifySystemArrayCopy(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001152 }
1153}
1154
Aart Bikbb245d12015-10-19 11:05:03 -07001155void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1156 HInstruction* cond = deoptimize->InputAt(0);
1157 if (cond->IsConstant()) {
1158 if (cond->AsIntConstant()->IsZero()) {
1159 // Never deopt: instruction can be removed.
1160 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1161 } else {
1162 // Always deopt.
1163 }
1164 }
1165}
1166
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001167} // namespace art