blob: d4685400916c3dc03f303a63f5196a068086362b [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;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010076
77 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000078
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010079 void SimplifySystemArrayCopy(HInvoke* invoke);
80 void SimplifyStringEquals(HInvoke* invoke);
81
Calin Juravleacf735c2015-02-12 15:25:22 +000082 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010083 bool simplification_occurred_ = false;
84 int simplifications_at_current_position_ = 0;
85 // We ensure we do not loop infinitely. The value is a finger in the air guess
86 // that should allow enough simplification.
87 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000088};
89
Nicolas Geoffray3c049742014-09-24 18:10:46 +010090void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000091 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010092 visitor.Run();
93}
94
95void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010096 // Iterate in reverse post order to open up more simplifications to users
97 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010098 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
99 // The simplification of an instruction to another instruction may yield
100 // possibilities for other simplifications. So although we perform a reverse
101 // post order visit, we sometimes need to revisit an instruction index.
102 simplification_occurred_ = false;
103 VisitBasicBlock(it.Current());
104 if (simplification_occurred_ &&
105 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
106 // New simplifications may be applicable to the instruction at the
107 // current index, so don't advance the iterator.
108 continue;
109 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100110 simplifications_at_current_position_ = 0;
111 it.Advance();
112 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100113}
114
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000115namespace {
116
117bool AreAllBitsSet(HConstant* constant) {
118 return Int64FromConstant(constant) == -1;
119}
120
121} // namespace
122
Alexandre Rames188d4312015-04-09 18:30:21 +0100123// Returns true if the code was simplified to use only one negation operation
124// after the binary operation instead of one on each of the inputs.
125bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
126 DCHECK(binop->IsAdd() || binop->IsSub());
127 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
128 HNeg* left_neg = binop->GetLeft()->AsNeg();
129 HNeg* right_neg = binop->GetRight()->AsNeg();
130 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
131 !right_neg->HasOnlyOneNonEnvironmentUse()) {
132 return false;
133 }
134 // Replace code looking like
135 // NEG tmp1, a
136 // NEG tmp2, b
137 // ADD dst, tmp1, tmp2
138 // with
139 // ADD tmp, a, b
140 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600141 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
142 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
143 // while the later yields `-0.0`.
144 if (!Primitive::IsIntegralType(binop->GetType())) {
145 return false;
146 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100147 binop->ReplaceInput(left_neg->GetInput(), 0);
148 binop->ReplaceInput(right_neg->GetInput(), 1);
149 left_neg->GetBlock()->RemoveInstruction(left_neg);
150 right_neg->GetBlock()->RemoveInstruction(right_neg);
151 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
152 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
153 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
154 RecordSimplification();
155 return true;
156}
157
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000158void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
159 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
160 HConstant* input_cst = instruction->GetConstantRight();
161 HInstruction* input_other = instruction->GetLeastConstantLeft();
162
Mark Mendellba56d062015-05-05 21:34:03 -0400163 if (input_cst != nullptr) {
164 if (input_cst->IsZero()) {
165 // Replace code looking like
166 // SHL dst, src, 0
167 // with
168 // src
169 instruction->ReplaceWith(input_other);
170 instruction->GetBlock()->RemoveInstruction(instruction);
171 } else if (instruction->IsShl() && input_cst->IsOne()) {
172 // Replace Shl looking like
173 // SHL dst, src, 1
174 // with
175 // ADD dst, src, src
176 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
177 input_other,
178 input_other);
179 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
180 RecordSimplification();
181 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000182 }
183}
184
Calin Juravle10e244f2015-01-26 18:54:32 +0000185void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
186 HInstruction* obj = null_check->InputAt(0);
187 if (!obj->CanBeNull()) {
188 null_check->ReplaceWith(obj);
189 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000190 if (stats_ != nullptr) {
191 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
192 }
193 }
194}
195
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100196bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
197 if (!input->CanBeNull()) {
198 return true;
199 }
200
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100201 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
202 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100203 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100204 return true;
205 }
206 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100207
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100208 return false;
209}
210
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100211// Returns whether doing a type test between the class of `object` against `klass` has
212// a statically known outcome. The result of the test is stored in `outcome`.
213static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000214 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
215 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
216 ScopedObjectAccess soa(Thread::Current());
217 if (!obj_rti.IsValid()) {
218 // We run the simplifier before the reference type propagation so type info might not be
219 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100220 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000221 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100222
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100223 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100224 if (!class_rti.IsValid()) {
225 // Happens when the loaded class is unresolved.
226 return false;
227 }
228 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000229 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100230 *outcome = true;
231 return true;
232 } else if (obj_rti.IsExact()) {
233 // The test failed at compile time so will also fail at runtime.
234 *outcome = false;
235 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100236 } else if (!class_rti.IsInterface()
237 && !obj_rti.IsInterface()
238 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100239 // Different type hierarchy. The test will fail.
240 *outcome = false;
241 return true;
242 }
243 return false;
244}
245
246void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
247 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100248 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
249 if (load_class->NeedsAccessCheck()) {
250 // If we need to perform an access check we cannot remove the instruction.
251 return;
252 }
253
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100254 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100255 check_cast->ClearMustDoNullCheck();
256 }
257
258 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000259 check_cast->GetBlock()->RemoveInstruction(check_cast);
260 if (stats_ != nullptr) {
261 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
262 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100263 return;
264 }
265
266 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700267 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100268 if (outcome) {
269 check_cast->GetBlock()->RemoveInstruction(check_cast);
270 if (stats_ != nullptr) {
271 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
272 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700273 if (!load_class->HasUses()) {
274 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
275 // However, here we know that it cannot because the checkcast was successfull, hence
276 // the class was already loaded.
277 load_class->GetBlock()->RemoveInstruction(load_class);
278 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100279 } else {
280 // Don't do anything for exceptional cases for now. Ideally we should remove
281 // all instructions and blocks this instruction dominates.
282 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000283 }
284}
285
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100286void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100287 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100288 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
289 if (load_class->NeedsAccessCheck()) {
290 // If we need to perform an access check we cannot remove the instruction.
291 return;
292 }
293
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100294 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100295 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100296 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100297 instruction->ClearMustDoNullCheck();
298 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100299
300 HGraph* graph = GetGraph();
301 if (object->IsNullConstant()) {
302 instruction->ReplaceWith(graph->GetIntConstant(0));
303 instruction->GetBlock()->RemoveInstruction(instruction);
304 RecordSimplification();
305 return;
306 }
307
308 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700309 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100310 if (outcome && can_be_null) {
311 // Type test will succeed, we just need a null test.
312 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
313 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
314 instruction->ReplaceWith(test);
315 } else {
316 // We've statically determined the result of the instanceof.
317 instruction->ReplaceWith(graph->GetIntConstant(outcome));
318 }
319 RecordSimplification();
320 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700321 if (outcome && !load_class->HasUses()) {
322 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
323 // However, here we know that it cannot because the instanceof check was successfull, hence
324 // the class was already loaded.
325 load_class->GetBlock()->RemoveInstruction(load_class);
326 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100327 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100328}
329
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100330void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
331 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100332 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100333 instruction->ClearValueCanBeNull();
334 }
335}
336
337void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
338 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100339 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100340 instruction->ClearValueCanBeNull();
341 }
342}
343
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000344void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100345 HBasicBlock* block = check->GetBlock();
346 // Currently always keep the suspend check at entry.
347 if (block->IsEntryBlock()) return;
348
349 // Currently always keep suspend checks at loop entry.
350 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
351 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
352 return;
353 }
354
355 // Remove the suspend check that was added at build time for the baseline
356 // compiler.
357 block->RemoveInstruction(check);
358}
359
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000360void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100361 HInstruction* input_const = equal->GetConstantRight();
362 if (input_const != nullptr) {
363 HInstruction* input_value = equal->GetLeastConstantLeft();
364 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
365 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100366 // We are comparing the boolean to a constant which is of type int and can
367 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100368 if (input_const->AsIntConstant()->IsOne()) {
369 // Replace (bool_value == true) with bool_value
370 equal->ReplaceWith(input_value);
371 block->RemoveInstruction(equal);
372 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100373 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100374 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100375 block->ReplaceAndRemoveInstructionWith(
376 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
377 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()) {
401 // Replace (bool_value != true) with !bool_value
402 block->ReplaceAndRemoveInstructionWith(
403 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
404 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100405 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100406 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100407 not_equal->ReplaceWith(input_value);
408 block->RemoveInstruction(not_equal);
409 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100410 } else {
411 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
412 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
413 block->RemoveInstruction(not_equal);
414 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100415 }
Mark Mendellc4701932015-04-10 13:18:51 -0400416 } else {
417 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100418 }
Mark Mendellc4701932015-04-10 13:18:51 -0400419 } else {
420 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100421 }
422}
423
424void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
425 HInstruction* parent = bool_not->InputAt(0);
426 if (parent->IsBooleanNot()) {
427 HInstruction* value = parent->InputAt(0);
428 // Replace (!(!bool_value)) with bool_value
429 bool_not->ReplaceWith(value);
430 bool_not->GetBlock()->RemoveInstruction(bool_not);
431 // It is possible that `parent` is dead at this point but we leave
432 // its removal to DCE for simplicity.
433 RecordSimplification();
434 }
435}
436
Mingyao Yang0304e182015-01-30 16:41:29 -0800437void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
438 HInstruction* input = instruction->InputAt(0);
439 // If the array is a NewArray with constant size, replace the array length
440 // with the constant instruction. This helps the bounds check elimination phase.
441 if (input->IsNewArray()) {
442 input = input->InputAt(0);
443 if (input->IsIntConstant()) {
444 instruction->ReplaceWith(input);
445 }
446 }
447}
448
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000449void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000450 HInstruction* value = instruction->GetValue();
451 if (value->GetType() != Primitive::kPrimNot) return;
452
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100453 if (CanEnsureNotNullAt(value, instruction)) {
454 instruction->ClearValueCanBeNull();
455 }
456
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000457 if (value->IsArrayGet()) {
458 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
459 // If the code is just swapping elements in the array, no need for a type check.
460 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100461 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000462 }
463 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100464
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100465 if (value->IsNullConstant()) {
466 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100467 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100468 }
469
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100470 ScopedObjectAccess soa(Thread::Current());
471 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
472 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
473 if (!array_rti.IsValid()) {
474 return;
475 }
476
477 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
478 instruction->ClearNeedsTypeCheck();
479 return;
480 }
481
482 if (array_rti.IsObjectArray()) {
483 if (array_rti.IsExact()) {
484 instruction->ClearNeedsTypeCheck();
485 return;
486 }
487 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100488 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000489}
490
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000491void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
492 if (instruction->GetResultType() == instruction->GetInputType()) {
493 // Remove the instruction if it's converting to the same type.
494 instruction->ReplaceWith(instruction->GetInput());
495 instruction->GetBlock()->RemoveInstruction(instruction);
496 }
497}
498
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000499void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
500 HConstant* input_cst = instruction->GetConstantRight();
501 HInstruction* input_other = instruction->GetLeastConstantLeft();
502 if ((input_cst != nullptr) && input_cst->IsZero()) {
503 // Replace code looking like
504 // ADD dst, src, 0
505 // with
506 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600507 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
508 // `x` is `-0.0`, the former expression yields `0.0`, while the later
509 // yields `-0.0`.
510 if (Primitive::IsIntegralType(instruction->GetType())) {
511 instruction->ReplaceWith(input_other);
512 instruction->GetBlock()->RemoveInstruction(instruction);
513 return;
514 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100515 }
516
517 HInstruction* left = instruction->GetLeft();
518 HInstruction* right = instruction->GetRight();
519 bool left_is_neg = left->IsNeg();
520 bool right_is_neg = right->IsNeg();
521
522 if (left_is_neg && right_is_neg) {
523 if (TryMoveNegOnInputsAfterBinop(instruction)) {
524 return;
525 }
526 }
527
528 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
529 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
530 // Replace code looking like
531 // NEG tmp, b
532 // ADD dst, a, tmp
533 // with
534 // SUB dst, a, b
535 // We do not perform the optimization if the input negation has environment
536 // uses or multiple non-environment uses as it could lead to worse code. In
537 // particular, we do not want the live range of `b` to be extended if we are
538 // not sure the initial 'NEG' instruction can be removed.
539 HInstruction* other = left_is_neg ? right : left;
540 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
541 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
542 RecordSimplification();
543 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000544 }
545}
546
547void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
548 HConstant* input_cst = instruction->GetConstantRight();
549 HInstruction* input_other = instruction->GetLeastConstantLeft();
550
Vladimir Marko452c1b62015-09-25 14:44:17 +0100551 if (input_cst != nullptr) {
552 int64_t value = Int64FromConstant(input_cst);
553 if (value == -1) {
554 // Replace code looking like
555 // AND dst, src, 0xFFF...FF
556 // with
557 // src
558 instruction->ReplaceWith(input_other);
559 instruction->GetBlock()->RemoveInstruction(instruction);
560 RecordSimplification();
561 return;
562 }
563 // Eliminate And from UShr+And if the And-mask contains all the bits that
564 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
565 // precisely clears the shifted-in sign bits.
566 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
567 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
568 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
569 size_t num_tail_bits_set = CTZ(value + 1);
570 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
571 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
572 instruction->ReplaceWith(input_other);
573 instruction->GetBlock()->RemoveInstruction(instruction);
574 RecordSimplification();
575 return;
576 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
577 input_other->HasOnlyOneNonEnvironmentUse()) {
578 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
579 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
580 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
581 input_other->InputAt(0),
582 input_other->InputAt(1),
583 input_other->GetDexPc());
584 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
585 input_other->GetBlock()->RemoveInstruction(input_other);
586 RecordSimplification();
587 return;
588 }
589 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000590 }
591
592 // We assume that GVN has run before, so we only perform a pointer comparison.
593 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100594 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000595 if (instruction->GetLeft() == instruction->GetRight()) {
596 // Replace code looking like
597 // AND dst, src, src
598 // with
599 // src
600 instruction->ReplaceWith(instruction->GetLeft());
601 instruction->GetBlock()->RemoveInstruction(instruction);
602 }
603}
604
Mark Mendellc4701932015-04-10 13:18:51 -0400605void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
606 VisitCondition(condition);
607}
608
609void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
610 VisitCondition(condition);
611}
612
613void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
614 VisitCondition(condition);
615}
616
617void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
618 VisitCondition(condition);
619}
620
Aart Bike9f37602015-10-09 11:15:55 -0700621// TODO: unsigned comparisons too?
622
Mark Mendellc4701932015-04-10 13:18:51 -0400623void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
624 // Try to fold an HCompare into this HCondition.
625
Roland Levillain7f63c522015-07-13 15:54:55 +0000626 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
627 // TODO: Implement it for MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400628 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Roland Levillain7f63c522015-07-13 15:54:55 +0000629 if (instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400630 return;
631 }
632
633 HInstruction* left = condition->GetLeft();
634 HInstruction* right = condition->GetRight();
635 // We can only replace an HCondition which compares a Compare to 0.
636 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
637 // condition with a long, float or double comparison as input.
638 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
639 // Conversion is not possible.
640 return;
641 }
642
643 // Is the Compare only used for this purpose?
644 if (!left->GetUses().HasOnlyOneUse()) {
645 // Someone else also wants the result of the compare.
646 return;
647 }
648
649 if (!left->GetEnvUses().IsEmpty()) {
650 // There is a reference to the compare result in an environment. Do we really need it?
651 if (GetGraph()->IsDebuggable()) {
652 return;
653 }
654
655 // We have to ensure that there are no deopt points in the sequence.
656 if (left->HasAnyEnvironmentUseBefore(condition)) {
657 return;
658 }
659 }
660
661 // Clean up any environment uses from the HCompare, if any.
662 left->RemoveEnvironmentUsers();
663
664 // We have decided to fold the HCompare into the HCondition. Transfer the information.
665 condition->SetBias(left->AsCompare()->GetBias());
666
667 // Replace the operands of the HCondition.
668 condition->ReplaceInput(left->InputAt(0), 0);
669 condition->ReplaceInput(left->InputAt(1), 1);
670
671 // Remove the HCompare.
672 left->GetBlock()->RemoveInstruction(left);
673
674 RecordSimplification();
675}
676
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000677void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
678 HConstant* input_cst = instruction->GetConstantRight();
679 HInstruction* input_other = instruction->GetLeastConstantLeft();
680 Primitive::Type type = instruction->GetType();
681
682 if ((input_cst != nullptr) && input_cst->IsOne()) {
683 // Replace code looking like
684 // DIV dst, src, 1
685 // with
686 // src
687 instruction->ReplaceWith(input_other);
688 instruction->GetBlock()->RemoveInstruction(instruction);
689 return;
690 }
691
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000692 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000693 // Replace code looking like
694 // DIV dst, src, -1
695 // with
696 // NEG dst, src
697 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000698 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100699 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000700 return;
701 }
702
703 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
704 // Try replacing code looking like
705 // DIV dst, src, constant
706 // with
707 // MUL dst, src, 1 / constant
708 HConstant* reciprocal = nullptr;
709 if (type == Primitive::Primitive::kPrimDouble) {
710 double value = input_cst->AsDoubleConstant()->GetValue();
711 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
712 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
713 }
714 } else {
715 DCHECK_EQ(type, Primitive::kPrimFloat);
716 float value = input_cst->AsFloatConstant()->GetValue();
717 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
718 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
719 }
720 }
721
722 if (reciprocal != nullptr) {
723 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
724 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
725 RecordSimplification();
726 return;
727 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000728 }
729}
730
731void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
732 HConstant* input_cst = instruction->GetConstantRight();
733 HInstruction* input_other = instruction->GetLeastConstantLeft();
734 Primitive::Type type = instruction->GetType();
735 HBasicBlock* block = instruction->GetBlock();
736 ArenaAllocator* allocator = GetGraph()->GetArena();
737
738 if (input_cst == nullptr) {
739 return;
740 }
741
742 if (input_cst->IsOne()) {
743 // Replace code looking like
744 // MUL dst, src, 1
745 // with
746 // src
747 instruction->ReplaceWith(input_other);
748 instruction->GetBlock()->RemoveInstruction(instruction);
749 return;
750 }
751
752 if (input_cst->IsMinusOne() &&
753 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
754 // Replace code looking like
755 // MUL dst, src, -1
756 // with
757 // NEG dst, src
758 HNeg* neg = new (allocator) HNeg(type, input_other);
759 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100760 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000761 return;
762 }
763
764 if (Primitive::IsFloatingPointType(type) &&
765 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
766 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
767 // Replace code looking like
768 // FP_MUL dst, src, 2.0
769 // with
770 // FP_ADD dst, src, src
771 // The 'int' and 'long' cases are handled below.
772 block->ReplaceAndRemoveInstructionWith(instruction,
773 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100774 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000775 return;
776 }
777
778 if (Primitive::IsIntOrLongType(type)) {
779 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600780 // Even though constant propagation also takes care of the zero case, other
781 // optimizations can lead to having a zero multiplication.
782 if (factor == 0) {
783 // Replace code looking like
784 // MUL dst, src, 0
785 // with
786 // 0
787 instruction->ReplaceWith(input_cst);
788 instruction->GetBlock()->RemoveInstruction(instruction);
789 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000790 // Replace code looking like
791 // MUL dst, src, pow_of_2
792 // with
793 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000794 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000795 HShl* shl = new(allocator) HShl(type, input_other, shift);
796 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100797 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000798 }
799 }
800}
801
Alexandre Rames188d4312015-04-09 18:30:21 +0100802void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
803 HInstruction* input = instruction->GetInput();
804 if (input->IsNeg()) {
805 // Replace code looking like
806 // NEG tmp, src
807 // NEG dst, tmp
808 // with
809 // src
810 HNeg* previous_neg = input->AsNeg();
811 instruction->ReplaceWith(previous_neg->GetInput());
812 instruction->GetBlock()->RemoveInstruction(instruction);
813 // We perform the optimization even if the input negation has environment
814 // uses since it allows removing the current instruction. But we only delete
815 // the input negation only if it is does not have any uses left.
816 if (!previous_neg->HasUses()) {
817 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
818 }
819 RecordSimplification();
820 return;
821 }
822
Serguei Katkov339dfc22015-04-20 12:29:32 +0600823 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
824 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100825 // Replace code looking like
826 // SUB tmp, a, b
827 // NEG dst, tmp
828 // with
829 // SUB dst, b, a
830 // We do not perform the optimization if the input subtraction has
831 // environment uses or multiple non-environment uses as it could lead to
832 // worse code. In particular, we do not want the live ranges of `a` and `b`
833 // to be extended if we are not sure the initial 'SUB' instruction can be
834 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600835 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100836 HSub* sub = input->AsSub();
837 HSub* new_sub =
838 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
839 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
840 if (!sub->HasUses()) {
841 sub->GetBlock()->RemoveInstruction(sub);
842 }
843 RecordSimplification();
844 }
845}
846
847void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
848 HInstruction* input = instruction->GetInput();
849 if (input->IsNot()) {
850 // Replace code looking like
851 // NOT tmp, src
852 // NOT dst, tmp
853 // with
854 // src
855 // We perform the optimization even if the input negation has environment
856 // uses since it allows removing the current instruction. But we only delete
857 // the input negation only if it is does not have any uses left.
858 HNot* previous_not = input->AsNot();
859 instruction->ReplaceWith(previous_not->GetInput());
860 instruction->GetBlock()->RemoveInstruction(instruction);
861 if (!previous_not->HasUses()) {
862 previous_not->GetBlock()->RemoveInstruction(previous_not);
863 }
864 RecordSimplification();
865 }
866}
867
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000868void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
869 HConstant* input_cst = instruction->GetConstantRight();
870 HInstruction* input_other = instruction->GetLeastConstantLeft();
871
872 if ((input_cst != nullptr) && input_cst->IsZero()) {
873 // Replace code looking like
874 // OR dst, src, 0
875 // with
876 // src
877 instruction->ReplaceWith(input_other);
878 instruction->GetBlock()->RemoveInstruction(instruction);
879 return;
880 }
881
882 // We assume that GVN has run before, so we only perform a pointer comparison.
883 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100884 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000885 if (instruction->GetLeft() == instruction->GetRight()) {
886 // Replace code looking like
887 // OR dst, src, src
888 // with
889 // src
890 instruction->ReplaceWith(instruction->GetLeft());
891 instruction->GetBlock()->RemoveInstruction(instruction);
892 }
893}
894
895void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
896 VisitShift(instruction);
897}
898
899void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
900 VisitShift(instruction);
901}
902
903void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
904 HConstant* input_cst = instruction->GetConstantRight();
905 HInstruction* input_other = instruction->GetLeastConstantLeft();
906
Serguei Katkov115b53f2015-08-05 17:03:30 +0600907 Primitive::Type type = instruction->GetType();
908 if (Primitive::IsFloatingPointType(type)) {
909 return;
910 }
911
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000912 if ((input_cst != nullptr) && input_cst->IsZero()) {
913 // Replace code looking like
914 // SUB dst, src, 0
915 // with
916 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600917 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
918 // `x` is `-0.0`, the former expression yields `0.0`, while the later
919 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000920 instruction->ReplaceWith(input_other);
921 instruction->GetBlock()->RemoveInstruction(instruction);
922 return;
923 }
924
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000925 HBasicBlock* block = instruction->GetBlock();
926 ArenaAllocator* allocator = GetGraph()->GetArena();
927
Alexandre Rames188d4312015-04-09 18:30:21 +0100928 HInstruction* left = instruction->GetLeft();
929 HInstruction* right = instruction->GetRight();
930 if (left->IsConstant()) {
931 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000932 // Replace code looking like
933 // SUB dst, 0, src
934 // with
935 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100936 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000937 // `x` is `0.0`, the former expression yields `0.0`, while the later
938 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100939 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000940 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100941 RecordSimplification();
942 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000943 }
944 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100945
946 if (left->IsNeg() && right->IsNeg()) {
947 if (TryMoveNegOnInputsAfterBinop(instruction)) {
948 return;
949 }
950 }
951
952 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
953 // Replace code looking like
954 // NEG tmp, b
955 // SUB dst, a, tmp
956 // with
957 // ADD dst, a, b
958 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
959 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
960 RecordSimplification();
961 right->GetBlock()->RemoveInstruction(right);
962 return;
963 }
964
965 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
966 // Replace code looking like
967 // NEG tmp, a
968 // SUB dst, tmp, b
969 // with
970 // ADD tmp, a, b
971 // NEG dst, tmp
972 // The second version is not intrinsically better, but enables more
973 // transformations.
974 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
975 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
976 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
977 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
978 instruction->ReplaceWith(neg);
979 instruction->GetBlock()->RemoveInstruction(instruction);
980 RecordSimplification();
981 left->GetBlock()->RemoveInstruction(left);
982 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000983}
984
985void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
986 VisitShift(instruction);
987}
988
989void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
990 HConstant* input_cst = instruction->GetConstantRight();
991 HInstruction* input_other = instruction->GetLeastConstantLeft();
992
993 if ((input_cst != nullptr) && input_cst->IsZero()) {
994 // Replace code looking like
995 // XOR dst, src, 0
996 // with
997 // src
998 instruction->ReplaceWith(input_other);
999 instruction->GetBlock()->RemoveInstruction(instruction);
1000 return;
1001 }
1002
1003 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1004 // Replace code looking like
1005 // XOR dst, src, 0xFFF...FF
1006 // with
1007 // NOT dst, src
1008 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1009 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001010 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001011 return;
1012 }
1013}
1014
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +01001015void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
1016 HInstruction* actual_string = nullptr;
1017
1018 // Find the string we need to replace this instruction with. The actual string is
1019 // the return value of a StringFactory call.
1020 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1021 HInstruction* use = it.Current()->GetUser();
1022 if (use->IsInvokeStaticOrDirect()
1023 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
1024 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
1025 actual_string = use;
1026 break;
1027 }
1028 }
1029
1030 // Check that there is no other instruction that thinks it is the factory for that string.
1031 if (kIsDebugBuild) {
1032 CHECK(actual_string != nullptr);
1033 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1034 HInstruction* use = it.Current()->GetUser();
1035 if (use->IsInvokeStaticOrDirect()) {
1036 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
1037 }
1038 }
1039 }
1040
1041 // We need to remove any environment uses of the fake string that are not dominated by
1042 // `actual_string` to null.
1043 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
1044 HEnvironment* environment = it.Current()->GetUser();
1045 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
1046 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
1047 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
1048 }
1049 }
1050
1051 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
1052 // `instruction`.
1053 instruction->ReplaceWith(actual_string);
1054 instruction->GetBlock()->RemoveInstruction(instruction);
1055}
1056
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001057void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1058 HInstruction* argument = instruction->InputAt(1);
1059 HInstruction* receiver = instruction->InputAt(0);
1060 if (receiver == argument) {
1061 // Because String.equals is an instance call, the receiver is
1062 // a null check if we don't know it's null. The argument however, will
1063 // be the actual object. So we cannot end up in a situation where both
1064 // are equal but could be null.
1065 DCHECK(CanEnsureNotNullAt(argument, instruction));
1066 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1067 instruction->GetBlock()->RemoveInstruction(instruction);
1068 } else {
1069 StringEqualsOptimizations optimizations(instruction);
1070 if (CanEnsureNotNullAt(argument, instruction)) {
1071 optimizations.SetArgumentNotNull();
1072 }
1073 ScopedObjectAccess soa(Thread::Current());
1074 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1075 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1076 optimizations.SetArgumentIsString();
1077 }
1078 }
1079}
1080
1081static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1082 if (potential_length->IsArrayLength()) {
1083 return potential_length->InputAt(0) == potential_array;
1084 }
1085
1086 if (potential_array->IsNewArray()) {
1087 return potential_array->InputAt(0) == potential_length;
1088 }
1089
1090 return false;
1091}
1092
1093void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1094 HInstruction* source = instruction->InputAt(0);
1095 HInstruction* destination = instruction->InputAt(2);
1096 HInstruction* count = instruction->InputAt(4);
1097 SystemArrayCopyOptimizations optimizations(instruction);
1098 if (CanEnsureNotNullAt(source, instruction)) {
1099 optimizations.SetSourceIsNotNull();
1100 }
1101 if (CanEnsureNotNullAt(destination, instruction)) {
1102 optimizations.SetDestinationIsNotNull();
1103 }
1104 if (destination == source) {
1105 optimizations.SetDestinationIsSource();
1106 }
1107
1108 if (IsArrayLengthOf(count, source)) {
1109 optimizations.SetCountIsSourceLength();
1110 }
1111
1112 if (IsArrayLengthOf(count, destination)) {
1113 optimizations.SetCountIsDestinationLength();
1114 }
1115
1116 {
1117 ScopedObjectAccess soa(Thread::Current());
1118 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1119 if (destination_rti.IsValid()) {
1120 if (destination_rti.IsObjectArray()) {
1121 if (destination_rti.IsExact()) {
1122 optimizations.SetDoesNotNeedTypeCheck();
1123 }
1124 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001125 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001126 if (destination_rti.IsPrimitiveArrayClass()) {
1127 optimizations.SetDestinationIsPrimitiveArray();
1128 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1129 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001130 }
1131 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001132 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1133 if (source_rti.IsValid()) {
1134 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1135 optimizations.SetDoesNotNeedTypeCheck();
1136 }
1137 if (source_rti.IsPrimitiveArrayClass()) {
1138 optimizations.SetSourceIsPrimitiveArray();
1139 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1140 optimizations.SetSourceIsNonPrimitiveArray();
1141 }
1142 }
1143 }
1144}
1145
1146void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1147 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1148 SimplifyStringEquals(instruction);
1149 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1150 SimplifySystemArrayCopy(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001151 }
1152}
1153
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001154} // namespace art