blob: 98f800984643b3c0051783d80493d028b78fd348 [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
Scott Wakeling40a04bf2015-12-11 09:50:36 +000042 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
43 bool TryReplaceWithRotate(HBinaryOperation* instruction);
44 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
45 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
46 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47
Alexandre Rames188d4312015-04-09 18:30:21 +010048 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000049 // `op` should be either HOr or HAnd.
50 // De Morgan's laws:
51 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
52 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000053 void VisitShift(HBinaryOperation* shift);
54
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000055 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
56 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010057 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
58 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010059 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
60 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000061 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000062 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000063 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080064 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000065 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000066 void VisitAdd(HAdd* instruction) OVERRIDE;
67 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040068 void VisitCondition(HCondition* instruction) OVERRIDE;
69 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
70 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
71 void VisitLessThan(HLessThan* condition) OVERRIDE;
72 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000073 void VisitDiv(HDiv* instruction) OVERRIDE;
74 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010075 void VisitNeg(HNeg* instruction) OVERRIDE;
76 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitOr(HOr* instruction) OVERRIDE;
78 void VisitShl(HShl* instruction) OVERRIDE;
79 void VisitShr(HShr* instruction) OVERRIDE;
80 void VisitSub(HSub* instruction) OVERRIDE;
81 void VisitUShr(HUShr* instruction) OVERRIDE;
82 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000083 void VisitSelect(HSelect* select) OVERRIDE;
84 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010085 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010086 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070087 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010088
89 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000090
Scott Wakeling40a04bf2015-12-11 09:50:36 +000091 void SimplifyRotate(HInvoke* invoke, bool is_left);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010092 void SimplifySystemArrayCopy(HInvoke* invoke);
93 void SimplifyStringEquals(HInvoke* invoke);
Aart Bika19616e2016-02-01 18:57:58 -080094 void SimplifyCompare(HInvoke* invoke, bool has_zero_op);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010095
Calin Juravleacf735c2015-02-12 15:25:22 +000096 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010097 bool simplification_occurred_ = false;
98 int simplifications_at_current_position_ = 0;
99 // We ensure we do not loop infinitely. The value is a finger in the air guess
100 // that should allow enough simplification.
101 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000102};
103
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100104void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000105 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100106 visitor.Run();
107}
108
109void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100110 // Iterate in reverse post order to open up more simplifications to users
111 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100112 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
113 // The simplification of an instruction to another instruction may yield
114 // possibilities for other simplifications. So although we perform a reverse
115 // post order visit, we sometimes need to revisit an instruction index.
116 simplification_occurred_ = false;
117 VisitBasicBlock(it.Current());
118 if (simplification_occurred_ &&
119 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
120 // New simplifications may be applicable to the instruction at the
121 // current index, so don't advance the iterator.
122 continue;
123 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100124 simplifications_at_current_position_ = 0;
125 it.Advance();
126 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100127}
128
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000129namespace {
130
131bool AreAllBitsSet(HConstant* constant) {
132 return Int64FromConstant(constant) == -1;
133}
134
135} // namespace
136
Alexandre Rames188d4312015-04-09 18:30:21 +0100137// Returns true if the code was simplified to use only one negation operation
138// after the binary operation instead of one on each of the inputs.
139bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
140 DCHECK(binop->IsAdd() || binop->IsSub());
141 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
142 HNeg* left_neg = binop->GetLeft()->AsNeg();
143 HNeg* right_neg = binop->GetRight()->AsNeg();
144 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
145 !right_neg->HasOnlyOneNonEnvironmentUse()) {
146 return false;
147 }
148 // Replace code looking like
149 // NEG tmp1, a
150 // NEG tmp2, b
151 // ADD dst, tmp1, tmp2
152 // with
153 // ADD tmp, a, b
154 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600155 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
156 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
157 // while the later yields `-0.0`.
158 if (!Primitive::IsIntegralType(binop->GetType())) {
159 return false;
160 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100161 binop->ReplaceInput(left_neg->GetInput(), 0);
162 binop->ReplaceInput(right_neg->GetInput(), 1);
163 left_neg->GetBlock()->RemoveInstruction(left_neg);
164 right_neg->GetBlock()->RemoveInstruction(right_neg);
165 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
166 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
167 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
168 RecordSimplification();
169 return true;
170}
171
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000172bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
173 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
174 Primitive::Type type = op->GetType();
175 HInstruction* left = op->GetLeft();
176 HInstruction* right = op->GetRight();
177
178 // We can apply De Morgan's laws if both inputs are Not's and are only used
179 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000180 if (((left->IsNot() && right->IsNot()) ||
181 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000182 left->HasOnlyOneNonEnvironmentUse() &&
183 right->HasOnlyOneNonEnvironmentUse()) {
184 // Replace code looking like
185 // NOT nota, a
186 // NOT notb, b
187 // AND dst, nota, notb (respectively OR)
188 // with
189 // OR or, a, b (respectively AND)
190 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000191 HInstruction* src_left = left->InputAt(0);
192 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193 uint32_t dex_pc = op->GetDexPc();
194
195 // Remove the negations on the inputs.
196 left->ReplaceWith(src_left);
197 right->ReplaceWith(src_right);
198 left->GetBlock()->RemoveInstruction(left);
199 right->GetBlock()->RemoveInstruction(right);
200
201 // Replace the `HAnd` or `HOr`.
202 HBinaryOperation* hbin;
203 if (op->IsAnd()) {
204 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
205 } else {
206 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
207 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000208 HInstruction* hnot;
209 if (left->IsBooleanNot()) {
210 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
211 } else {
212 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
213 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000214
215 op->GetBlock()->InsertInstructionBefore(hbin, op);
216 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
217
218 RecordSimplification();
219 return true;
220 }
221
222 return false;
223}
224
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000225void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
226 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
227 HConstant* input_cst = instruction->GetConstantRight();
228 HInstruction* input_other = instruction->GetLeastConstantLeft();
229
Mark Mendellba56d062015-05-05 21:34:03 -0400230 if (input_cst != nullptr) {
231 if (input_cst->IsZero()) {
232 // Replace code looking like
233 // SHL dst, src, 0
234 // with
235 // src
236 instruction->ReplaceWith(input_other);
237 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400238 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000239 }
240}
241
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000242static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
243 return (sub->GetRight() == other &&
244 sub->GetLeft()->IsConstant() &&
245 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
246}
247
248bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
249 HUShr* ushr,
250 HShl* shl) {
251 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
252 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
253 ushr->GetLeft(),
254 ushr->GetRight());
255 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
256 if (!ushr->HasUses()) {
257 ushr->GetBlock()->RemoveInstruction(ushr);
258 }
259 if (!ushr->GetRight()->HasUses()) {
260 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
261 }
262 if (!shl->HasUses()) {
263 shl->GetBlock()->RemoveInstruction(shl);
264 }
265 if (!shl->GetRight()->HasUses()) {
266 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
267 }
268 return true;
269}
270
271// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
272bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000273 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
274 HInstruction* left = op->GetLeft();
275 HInstruction* right = op->GetRight();
276 // If we have an UShr and a Shl (in either order).
277 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
278 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
279 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
280 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
281 if (ushr->GetType() == shl->GetType() &&
282 ushr->GetLeft() == shl->GetLeft()) {
283 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
284 // Shift distances are both constant, try replacing with Ror if they
285 // add up to the register size.
286 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
287 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
288 // Shift distances are potentially of the form x and (reg_size - x).
289 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
290 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
291 // Shift distances are potentially of the form d and -d.
292 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
293 }
294 }
295 }
296 return false;
297}
298
299// Try replacing code looking like (x >>> #rdist OP x << #ldist):
300// UShr dst, x, #rdist
301// Shl tmp, x, #ldist
302// OP dst, dst, tmp
303// or like (x >>> #rdist OP x << #-ldist):
304// UShr dst, x, #rdist
305// Shl tmp, x, #-ldist
306// OP dst, dst, tmp
307// with
308// Ror dst, x, #rdist
309bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
310 HUShr* ushr,
311 HShl* shl) {
312 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
313 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
314 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
315 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
316 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
317 ReplaceRotateWithRor(op, ushr, shl);
318 return true;
319 }
320 return false;
321}
322
323// Replace code looking like (x >>> -d OP x << d):
324// Neg neg, d
325// UShr dst, x, neg
326// Shl tmp, x, d
327// OP dst, dst, tmp
328// with
329// Neg neg, d
330// Ror dst, x, neg
331// *** OR ***
332// Replace code looking like (x >>> d OP x << -d):
333// UShr dst, x, d
334// Neg neg, d
335// Shl tmp, x, neg
336// OP dst, dst, tmp
337// with
338// Ror dst, x, d
339bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
340 HUShr* ushr,
341 HShl* shl) {
342 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
343 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
344 bool neg_is_left = shl->GetRight()->IsNeg();
345 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
346 // And the shift distance being negated is the distance being shifted the other way.
347 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
348 ReplaceRotateWithRor(op, ushr, shl);
349 }
350 return false;
351}
352
353// Try replacing code looking like (x >>> d OP x << (#bits - d)):
354// UShr dst, x, d
355// Sub ld, #bits, d
356// Shl tmp, x, ld
357// OP dst, dst, tmp
358// with
359// Ror dst, x, d
360// *** OR ***
361// Replace code looking like (x >>> (#bits - d) OP x << d):
362// Sub rd, #bits, d
363// UShr dst, x, rd
364// Shl tmp, x, d
365// OP dst, dst, tmp
366// with
367// Neg neg, d
368// Ror dst, x, neg
369bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
370 HUShr* ushr,
371 HShl* shl) {
372 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
373 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
374 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
375 HInstruction* shl_shift = shl->GetRight();
376 HInstruction* ushr_shift = ushr->GetRight();
377 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
378 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
379 return ReplaceRotateWithRor(op, ushr, shl);
380 }
381 return false;
382}
383
Calin Juravle10e244f2015-01-26 18:54:32 +0000384void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
385 HInstruction* obj = null_check->InputAt(0);
386 if (!obj->CanBeNull()) {
387 null_check->ReplaceWith(obj);
388 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000389 if (stats_ != nullptr) {
390 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
391 }
392 }
393}
394
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100395bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
396 if (!input->CanBeNull()) {
397 return true;
398 }
399
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100400 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
401 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100402 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100403 return true;
404 }
405 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100406
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100407 return false;
408}
409
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100410// Returns whether doing a type test between the class of `object` against `klass` has
411// a statically known outcome. The result of the test is stored in `outcome`.
412static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000413 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
414 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
415 ScopedObjectAccess soa(Thread::Current());
416 if (!obj_rti.IsValid()) {
417 // We run the simplifier before the reference type propagation so type info might not be
418 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100419 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000420 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100421
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100422 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100423 if (!class_rti.IsValid()) {
424 // Happens when the loaded class is unresolved.
425 return false;
426 }
427 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000428 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100429 *outcome = true;
430 return true;
431 } else if (obj_rti.IsExact()) {
432 // The test failed at compile time so will also fail at runtime.
433 *outcome = false;
434 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100435 } else if (!class_rti.IsInterface()
436 && !obj_rti.IsInterface()
437 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100438 // Different type hierarchy. The test will fail.
439 *outcome = false;
440 return true;
441 }
442 return false;
443}
444
445void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
446 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100447 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
448 if (load_class->NeedsAccessCheck()) {
449 // If we need to perform an access check we cannot remove the instruction.
450 return;
451 }
452
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100453 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100454 check_cast->ClearMustDoNullCheck();
455 }
456
457 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000458 check_cast->GetBlock()->RemoveInstruction(check_cast);
459 if (stats_ != nullptr) {
460 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
461 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100462 return;
463 }
464
465 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700466 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100467 if (outcome) {
468 check_cast->GetBlock()->RemoveInstruction(check_cast);
469 if (stats_ != nullptr) {
470 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
471 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700472 if (!load_class->HasUses()) {
473 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
474 // However, here we know that it cannot because the checkcast was successfull, hence
475 // the class was already loaded.
476 load_class->GetBlock()->RemoveInstruction(load_class);
477 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100478 } else {
479 // Don't do anything for exceptional cases for now. Ideally we should remove
480 // all instructions and blocks this instruction dominates.
481 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000482 }
483}
484
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100485void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100486 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100487 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
488 if (load_class->NeedsAccessCheck()) {
489 // If we need to perform an access check we cannot remove the instruction.
490 return;
491 }
492
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100494 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100495 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100496 instruction->ClearMustDoNullCheck();
497 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100498
499 HGraph* graph = GetGraph();
500 if (object->IsNullConstant()) {
501 instruction->ReplaceWith(graph->GetIntConstant(0));
502 instruction->GetBlock()->RemoveInstruction(instruction);
503 RecordSimplification();
504 return;
505 }
506
507 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700508 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 if (outcome && can_be_null) {
510 // Type test will succeed, we just need a null test.
511 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
512 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
513 instruction->ReplaceWith(test);
514 } else {
515 // We've statically determined the result of the instanceof.
516 instruction->ReplaceWith(graph->GetIntConstant(outcome));
517 }
518 RecordSimplification();
519 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700520 if (outcome && !load_class->HasUses()) {
521 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
522 // However, here we know that it cannot because the instanceof check was successfull, hence
523 // the class was already loaded.
524 load_class->GetBlock()->RemoveInstruction(load_class);
525 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100526 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100527}
528
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100529void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
530 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100531 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100532 instruction->ClearValueCanBeNull();
533 }
534}
535
536void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
537 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100538 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100539 instruction->ClearValueCanBeNull();
540 }
541}
542
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000543void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100544 HBasicBlock* block = check->GetBlock();
545 // Currently always keep the suspend check at entry.
546 if (block->IsEntryBlock()) return;
547
548 // Currently always keep suspend checks at loop entry.
549 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
550 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
551 return;
552 }
553
554 // Remove the suspend check that was added at build time for the baseline
555 // compiler.
556 block->RemoveInstruction(check);
557}
558
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000559void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100560 HInstruction* input_const = equal->GetConstantRight();
561 if (input_const != nullptr) {
562 HInstruction* input_value = equal->GetLeastConstantLeft();
563 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
564 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100565 // We are comparing the boolean to a constant which is of type int and can
566 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100567 if (input_const->AsIntConstant()->IsOne()) {
568 // Replace (bool_value == true) with bool_value
569 equal->ReplaceWith(input_value);
570 block->RemoveInstruction(equal);
571 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100572 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500573 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
574 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100575 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100576 } else {
577 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
578 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
579 block->RemoveInstruction(equal);
580 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100581 }
Mark Mendellc4701932015-04-10 13:18:51 -0400582 } else {
583 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100584 }
Mark Mendellc4701932015-04-10 13:18:51 -0400585 } else {
586 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100587 }
588}
589
David Brazdil0d13fee2015-04-17 14:52:19 +0100590void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
591 HInstruction* input_const = not_equal->GetConstantRight();
592 if (input_const != nullptr) {
593 HInstruction* input_value = not_equal->GetLeastConstantLeft();
594 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
595 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100596 // We are comparing the boolean to a constant which is of type int and can
597 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100598 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500599 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
600 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100601 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100602 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100603 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100604 not_equal->ReplaceWith(input_value);
605 block->RemoveInstruction(not_equal);
606 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100607 } else {
608 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
609 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
610 block->RemoveInstruction(not_equal);
611 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100612 }
Mark Mendellc4701932015-04-10 13:18:51 -0400613 } else {
614 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100615 }
Mark Mendellc4701932015-04-10 13:18:51 -0400616 } else {
617 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100618 }
619}
620
621void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000622 HInstruction* input = bool_not->InputAt(0);
623 HInstruction* replace_with = nullptr;
624
625 if (input->IsIntConstant()) {
626 // Replace !(true/false) with false/true.
627 if (input->AsIntConstant()->IsOne()) {
628 replace_with = GetGraph()->GetIntConstant(0);
629 } else {
630 DCHECK(input->AsIntConstant()->IsZero());
631 replace_with = GetGraph()->GetIntConstant(1);
632 }
633 } else if (input->IsBooleanNot()) {
634 // Replace (!(!bool_value)) with bool_value.
635 replace_with = input->InputAt(0);
636 } else if (input->IsCondition() &&
637 // Don't change FP compares. The definition of compares involving
638 // NaNs forces the compares to be done as written by the user.
639 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
640 // Replace condition with its opposite.
641 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
642 }
643
644 if (replace_with != nullptr) {
645 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100646 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000647 RecordSimplification();
648 }
649}
650
651void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
652 HInstruction* replace_with = nullptr;
653 HInstruction* condition = select->GetCondition();
654 HInstruction* true_value = select->GetTrueValue();
655 HInstruction* false_value = select->GetFalseValue();
656
657 if (condition->IsBooleanNot()) {
658 // Change ((!cond) ? x : y) to (cond ? y : x).
659 condition = condition->InputAt(0);
660 std::swap(true_value, false_value);
661 select->ReplaceInput(false_value, 0);
662 select->ReplaceInput(true_value, 1);
663 select->ReplaceInput(condition, 2);
664 RecordSimplification();
665 }
666
667 if (true_value == false_value) {
668 // Replace (cond ? x : x) with (x).
669 replace_with = true_value;
670 } else if (condition->IsIntConstant()) {
671 if (condition->AsIntConstant()->IsOne()) {
672 // Replace (true ? x : y) with (x).
673 replace_with = true_value;
674 } else {
675 // Replace (false ? x : y) with (y).
676 DCHECK(condition->AsIntConstant()->IsZero());
677 replace_with = false_value;
678 }
679 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
680 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
681 // Replace (cond ? true : false) with (cond).
682 replace_with = condition;
683 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
684 // Replace (cond ? false : true) with (!cond).
685 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
686 }
687 }
688
689 if (replace_with != nullptr) {
690 select->ReplaceWith(replace_with);
691 select->GetBlock()->RemoveInstruction(select);
692 RecordSimplification();
693 }
694}
695
696void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
697 HInstruction* condition = instruction->InputAt(0);
698 if (condition->IsBooleanNot()) {
699 // Swap successors if input is negated.
700 instruction->ReplaceInput(condition->InputAt(0), 0);
701 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100702 RecordSimplification();
703 }
704}
705
Mingyao Yang0304e182015-01-30 16:41:29 -0800706void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
707 HInstruction* input = instruction->InputAt(0);
708 // If the array is a NewArray with constant size, replace the array length
709 // with the constant instruction. This helps the bounds check elimination phase.
710 if (input->IsNewArray()) {
711 input = input->InputAt(0);
712 if (input->IsIntConstant()) {
713 instruction->ReplaceWith(input);
714 }
715 }
716}
717
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000718void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000719 HInstruction* value = instruction->GetValue();
720 if (value->GetType() != Primitive::kPrimNot) return;
721
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100722 if (CanEnsureNotNullAt(value, instruction)) {
723 instruction->ClearValueCanBeNull();
724 }
725
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000726 if (value->IsArrayGet()) {
727 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
728 // If the code is just swapping elements in the array, no need for a type check.
729 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100730 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000731 }
732 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100733
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100734 if (value->IsNullConstant()) {
735 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100736 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100737 }
738
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100739 ScopedObjectAccess soa(Thread::Current());
740 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
741 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
742 if (!array_rti.IsValid()) {
743 return;
744 }
745
746 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
747 instruction->ClearNeedsTypeCheck();
748 return;
749 }
750
751 if (array_rti.IsObjectArray()) {
752 if (array_rti.IsExact()) {
753 instruction->ClearNeedsTypeCheck();
754 return;
755 }
756 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100757 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000758}
759
Vladimir Markob52bbde2016-02-12 12:06:05 +0000760static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
761 // Besides conversion to the same type, widening integral conversions are implicit,
762 // excluding conversions to long and the byte->char conversion where we need to
763 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
764 return result_type == input_type ||
765 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
766 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
767 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
768 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
769}
770
771static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
772 // The conversion to a larger type is loss-less with the exception of two cases,
773 // - conversion to char, the only unsigned type, where we may lose some bits, and
774 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
775 // For integral to FP conversions this holds because the FP mantissa is large enough.
776 DCHECK_NE(input_type, result_type);
777 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
778 result_type != Primitive::kPrimChar &&
779 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
780}
781
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000782void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000783 HInstruction* input = instruction->GetInput();
784 Primitive::Type input_type = input->GetType();
785 Primitive::Type result_type = instruction->GetResultType();
786 if (IsTypeConversionImplicit(input_type, result_type)) {
787 // Remove the implicit conversion; this includes conversion to the same type.
788 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000789 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000790 RecordSimplification();
791 return;
792 }
793
794 if (input->IsTypeConversion()) {
795 HTypeConversion* input_conversion = input->AsTypeConversion();
796 HInstruction* original_input = input_conversion->GetInput();
797 Primitive::Type original_type = original_input->GetType();
798
799 // When the first conversion is lossless, a direct conversion from the original type
800 // to the final type yields the same result, even for a lossy second conversion, for
801 // example float->double->int or int->double->float.
802 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
803
804 // For integral conversions, see if the first conversion loses only bits that the second
805 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
806 // conversion yields the same result, for example long->int->short or int->char->short.
807 bool integral_conversions_with_non_widening_second =
808 Primitive::IsIntegralType(input_type) &&
809 Primitive::IsIntegralType(original_type) &&
810 Primitive::IsIntegralType(result_type) &&
811 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
812
813 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
814 // If the merged conversion is implicit, do the simplification unconditionally.
815 if (IsTypeConversionImplicit(original_type, result_type)) {
816 instruction->ReplaceWith(original_input);
817 instruction->GetBlock()->RemoveInstruction(instruction);
818 if (!input_conversion->HasUses()) {
819 // Don't wait for DCE.
820 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
821 }
822 RecordSimplification();
823 return;
824 }
825 // Otherwise simplify only if the first conversion has no other use.
826 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
827 input_conversion->ReplaceWith(original_input);
828 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
829 RecordSimplification();
830 return;
831 }
832 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000833 }
834}
835
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000836void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
837 HConstant* input_cst = instruction->GetConstantRight();
838 HInstruction* input_other = instruction->GetLeastConstantLeft();
839 if ((input_cst != nullptr) && input_cst->IsZero()) {
840 // Replace code looking like
841 // ADD dst, src, 0
842 // with
843 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600844 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
845 // `x` is `-0.0`, the former expression yields `0.0`, while the later
846 // yields `-0.0`.
847 if (Primitive::IsIntegralType(instruction->GetType())) {
848 instruction->ReplaceWith(input_other);
849 instruction->GetBlock()->RemoveInstruction(instruction);
850 return;
851 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100852 }
853
854 HInstruction* left = instruction->GetLeft();
855 HInstruction* right = instruction->GetRight();
856 bool left_is_neg = left->IsNeg();
857 bool right_is_neg = right->IsNeg();
858
859 if (left_is_neg && right_is_neg) {
860 if (TryMoveNegOnInputsAfterBinop(instruction)) {
861 return;
862 }
863 }
864
865 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
866 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
867 // Replace code looking like
868 // NEG tmp, b
869 // ADD dst, a, tmp
870 // with
871 // SUB dst, a, b
872 // We do not perform the optimization if the input negation has environment
873 // uses or multiple non-environment uses as it could lead to worse code. In
874 // particular, we do not want the live range of `b` to be extended if we are
875 // not sure the initial 'NEG' instruction can be removed.
876 HInstruction* other = left_is_neg ? right : left;
877 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
878 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
879 RecordSimplification();
880 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000881 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000882 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000883
884 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000885}
886
887void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
888 HConstant* input_cst = instruction->GetConstantRight();
889 HInstruction* input_other = instruction->GetLeastConstantLeft();
890
Vladimir Marko452c1b62015-09-25 14:44:17 +0100891 if (input_cst != nullptr) {
892 int64_t value = Int64FromConstant(input_cst);
893 if (value == -1) {
894 // Replace code looking like
895 // AND dst, src, 0xFFF...FF
896 // with
897 // src
898 instruction->ReplaceWith(input_other);
899 instruction->GetBlock()->RemoveInstruction(instruction);
900 RecordSimplification();
901 return;
902 }
903 // Eliminate And from UShr+And if the And-mask contains all the bits that
904 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
905 // precisely clears the shifted-in sign bits.
906 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
907 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
908 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
909 size_t num_tail_bits_set = CTZ(value + 1);
910 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
911 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
912 instruction->ReplaceWith(input_other);
913 instruction->GetBlock()->RemoveInstruction(instruction);
914 RecordSimplification();
915 return;
916 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
917 input_other->HasOnlyOneNonEnvironmentUse()) {
918 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
919 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
920 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
921 input_other->InputAt(0),
922 input_other->InputAt(1),
923 input_other->GetDexPc());
924 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
925 input_other->GetBlock()->RemoveInstruction(input_other);
926 RecordSimplification();
927 return;
928 }
929 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000930 }
931
932 // We assume that GVN has run before, so we only perform a pointer comparison.
933 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100934 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000935 if (instruction->GetLeft() == instruction->GetRight()) {
936 // Replace code looking like
937 // AND dst, src, src
938 // with
939 // src
940 instruction->ReplaceWith(instruction->GetLeft());
941 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000942 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000943 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000944
945 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000946}
947
Mark Mendellc4701932015-04-10 13:18:51 -0400948void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
949 VisitCondition(condition);
950}
951
952void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
953 VisitCondition(condition);
954}
955
956void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
957 VisitCondition(condition);
958}
959
960void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
961 VisitCondition(condition);
962}
963
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000964// TODO: unsigned comparisons too?
Aart Bike9f37602015-10-09 11:15:55 -0700965
Mark Mendellc4701932015-04-10 13:18:51 -0400966void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000967 // Try to fold an HCompare into this HCondition.
Mark Mendellc4701932015-04-10 13:18:51 -0400968
Mark Mendellc4701932015-04-10 13:18:51 -0400969 HInstruction* left = condition->GetLeft();
970 HInstruction* right = condition->GetRight();
971 // We can only replace an HCondition which compares a Compare to 0.
972 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
973 // condition with a long, float or double comparison as input.
974 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
975 // Conversion is not possible.
976 return;
977 }
978
979 // Is the Compare only used for this purpose?
980 if (!left->GetUses().HasOnlyOneUse()) {
981 // Someone else also wants the result of the compare.
982 return;
983 }
984
985 if (!left->GetEnvUses().IsEmpty()) {
986 // There is a reference to the compare result in an environment. Do we really need it?
987 if (GetGraph()->IsDebuggable()) {
988 return;
989 }
990
991 // We have to ensure that there are no deopt points in the sequence.
992 if (left->HasAnyEnvironmentUseBefore(condition)) {
993 return;
994 }
995 }
996
997 // Clean up any environment uses from the HCompare, if any.
998 left->RemoveEnvironmentUsers();
999
1000 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1001 condition->SetBias(left->AsCompare()->GetBias());
1002
1003 // Replace the operands of the HCondition.
1004 condition->ReplaceInput(left->InputAt(0), 0);
1005 condition->ReplaceInput(left->InputAt(1), 1);
1006
1007 // Remove the HCompare.
1008 left->GetBlock()->RemoveInstruction(left);
1009
1010 RecordSimplification();
1011}
1012
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001013void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1014 HConstant* input_cst = instruction->GetConstantRight();
1015 HInstruction* input_other = instruction->GetLeastConstantLeft();
1016 Primitive::Type type = instruction->GetType();
1017
1018 if ((input_cst != nullptr) && input_cst->IsOne()) {
1019 // Replace code looking like
1020 // DIV dst, src, 1
1021 // with
1022 // src
1023 instruction->ReplaceWith(input_other);
1024 instruction->GetBlock()->RemoveInstruction(instruction);
1025 return;
1026 }
1027
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001028 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001029 // Replace code looking like
1030 // DIV dst, src, -1
1031 // with
1032 // NEG dst, src
1033 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001034 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001035 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001036 return;
1037 }
1038
1039 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1040 // Try replacing code looking like
1041 // DIV dst, src, constant
1042 // with
1043 // MUL dst, src, 1 / constant
1044 HConstant* reciprocal = nullptr;
1045 if (type == Primitive::Primitive::kPrimDouble) {
1046 double value = input_cst->AsDoubleConstant()->GetValue();
1047 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1048 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1049 }
1050 } else {
1051 DCHECK_EQ(type, Primitive::kPrimFloat);
1052 float value = input_cst->AsFloatConstant()->GetValue();
1053 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1054 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1055 }
1056 }
1057
1058 if (reciprocal != nullptr) {
1059 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1060 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1061 RecordSimplification();
1062 return;
1063 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001064 }
1065}
1066
1067void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1068 HConstant* input_cst = instruction->GetConstantRight();
1069 HInstruction* input_other = instruction->GetLeastConstantLeft();
1070 Primitive::Type type = instruction->GetType();
1071 HBasicBlock* block = instruction->GetBlock();
1072 ArenaAllocator* allocator = GetGraph()->GetArena();
1073
1074 if (input_cst == nullptr) {
1075 return;
1076 }
1077
1078 if (input_cst->IsOne()) {
1079 // Replace code looking like
1080 // MUL dst, src, 1
1081 // with
1082 // src
1083 instruction->ReplaceWith(input_other);
1084 instruction->GetBlock()->RemoveInstruction(instruction);
1085 return;
1086 }
1087
1088 if (input_cst->IsMinusOne() &&
1089 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1090 // Replace code looking like
1091 // MUL dst, src, -1
1092 // with
1093 // NEG dst, src
1094 HNeg* neg = new (allocator) HNeg(type, input_other);
1095 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001096 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001097 return;
1098 }
1099
1100 if (Primitive::IsFloatingPointType(type) &&
1101 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1102 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1103 // Replace code looking like
1104 // FP_MUL dst, src, 2.0
1105 // with
1106 // FP_ADD dst, src, src
1107 // The 'int' and 'long' cases are handled below.
1108 block->ReplaceAndRemoveInstructionWith(instruction,
1109 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001110 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001111 return;
1112 }
1113
1114 if (Primitive::IsIntOrLongType(type)) {
1115 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001116 // Even though constant propagation also takes care of the zero case, other
1117 // optimizations can lead to having a zero multiplication.
1118 if (factor == 0) {
1119 // Replace code looking like
1120 // MUL dst, src, 0
1121 // with
1122 // 0
1123 instruction->ReplaceWith(input_cst);
1124 instruction->GetBlock()->RemoveInstruction(instruction);
1125 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001126 // Replace code looking like
1127 // MUL dst, src, pow_of_2
1128 // with
1129 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001130 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001131 HShl* shl = new(allocator) HShl(type, input_other, shift);
1132 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001133 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001134 } else if (IsPowerOfTwo(factor - 1)) {
1135 // Transform code looking like
1136 // MUL dst, src, (2^n + 1)
1137 // into
1138 // SHL tmp, src, n
1139 // ADD dst, src, tmp
1140 HShl* shl = new (allocator) HShl(type,
1141 input_other,
1142 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1143 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1144
1145 block->InsertInstructionBefore(shl, instruction);
1146 block->ReplaceAndRemoveInstructionWith(instruction, add);
1147 RecordSimplification();
1148 } else if (IsPowerOfTwo(factor + 1)) {
1149 // Transform code looking like
1150 // MUL dst, src, (2^n - 1)
1151 // into
1152 // SHL tmp, src, n
1153 // SUB dst, tmp, src
1154 HShl* shl = new (allocator) HShl(type,
1155 input_other,
1156 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1157 HSub* sub = new (allocator) HSub(type, shl, input_other);
1158
1159 block->InsertInstructionBefore(shl, instruction);
1160 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1161 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001162 }
1163 }
1164}
1165
Alexandre Rames188d4312015-04-09 18:30:21 +01001166void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1167 HInstruction* input = instruction->GetInput();
1168 if (input->IsNeg()) {
1169 // Replace code looking like
1170 // NEG tmp, src
1171 // NEG dst, tmp
1172 // with
1173 // src
1174 HNeg* previous_neg = input->AsNeg();
1175 instruction->ReplaceWith(previous_neg->GetInput());
1176 instruction->GetBlock()->RemoveInstruction(instruction);
1177 // We perform the optimization even if the input negation has environment
1178 // uses since it allows removing the current instruction. But we only delete
1179 // the input negation only if it is does not have any uses left.
1180 if (!previous_neg->HasUses()) {
1181 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1182 }
1183 RecordSimplification();
1184 return;
1185 }
1186
Serguei Katkov339dfc22015-04-20 12:29:32 +06001187 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1188 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001189 // Replace code looking like
1190 // SUB tmp, a, b
1191 // NEG dst, tmp
1192 // with
1193 // SUB dst, b, a
1194 // We do not perform the optimization if the input subtraction has
1195 // environment uses or multiple non-environment uses as it could lead to
1196 // worse code. In particular, we do not want the live ranges of `a` and `b`
1197 // to be extended if we are not sure the initial 'SUB' instruction can be
1198 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001199 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001200 HSub* sub = input->AsSub();
1201 HSub* new_sub =
1202 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1203 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1204 if (!sub->HasUses()) {
1205 sub->GetBlock()->RemoveInstruction(sub);
1206 }
1207 RecordSimplification();
1208 }
1209}
1210
1211void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1212 HInstruction* input = instruction->GetInput();
1213 if (input->IsNot()) {
1214 // Replace code looking like
1215 // NOT tmp, src
1216 // NOT dst, tmp
1217 // with
1218 // src
1219 // We perform the optimization even if the input negation has environment
1220 // uses since it allows removing the current instruction. But we only delete
1221 // the input negation only if it is does not have any uses left.
1222 HNot* previous_not = input->AsNot();
1223 instruction->ReplaceWith(previous_not->GetInput());
1224 instruction->GetBlock()->RemoveInstruction(instruction);
1225 if (!previous_not->HasUses()) {
1226 previous_not->GetBlock()->RemoveInstruction(previous_not);
1227 }
1228 RecordSimplification();
1229 }
1230}
1231
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001232void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1233 HConstant* input_cst = instruction->GetConstantRight();
1234 HInstruction* input_other = instruction->GetLeastConstantLeft();
1235
1236 if ((input_cst != nullptr) && input_cst->IsZero()) {
1237 // Replace code looking like
1238 // OR dst, src, 0
1239 // with
1240 // src
1241 instruction->ReplaceWith(input_other);
1242 instruction->GetBlock()->RemoveInstruction(instruction);
1243 return;
1244 }
1245
1246 // We assume that GVN has run before, so we only perform a pointer comparison.
1247 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001248 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001249 if (instruction->GetLeft() == instruction->GetRight()) {
1250 // Replace code looking like
1251 // OR dst, src, src
1252 // with
1253 // src
1254 instruction->ReplaceWith(instruction->GetLeft());
1255 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001256 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001257 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001258
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001259 if (TryDeMorganNegationFactoring(instruction)) return;
1260
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001261 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001262}
1263
1264void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1265 VisitShift(instruction);
1266}
1267
1268void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1269 VisitShift(instruction);
1270}
1271
1272void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1273 HConstant* input_cst = instruction->GetConstantRight();
1274 HInstruction* input_other = instruction->GetLeastConstantLeft();
1275
Serguei Katkov115b53f2015-08-05 17:03:30 +06001276 Primitive::Type type = instruction->GetType();
1277 if (Primitive::IsFloatingPointType(type)) {
1278 return;
1279 }
1280
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001281 if ((input_cst != nullptr) && input_cst->IsZero()) {
1282 // Replace code looking like
1283 // SUB dst, src, 0
1284 // with
1285 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001286 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1287 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1288 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001289 instruction->ReplaceWith(input_other);
1290 instruction->GetBlock()->RemoveInstruction(instruction);
1291 return;
1292 }
1293
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001294 HBasicBlock* block = instruction->GetBlock();
1295 ArenaAllocator* allocator = GetGraph()->GetArena();
1296
Alexandre Rames188d4312015-04-09 18:30:21 +01001297 HInstruction* left = instruction->GetLeft();
1298 HInstruction* right = instruction->GetRight();
1299 if (left->IsConstant()) {
1300 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001301 // Replace code looking like
1302 // SUB dst, 0, src
1303 // with
1304 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001305 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001306 // `x` is `0.0`, the former expression yields `0.0`, while the later
1307 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001308 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001309 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001310 RecordSimplification();
1311 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001312 }
1313 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001314
1315 if (left->IsNeg() && right->IsNeg()) {
1316 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1317 return;
1318 }
1319 }
1320
1321 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1322 // Replace code looking like
1323 // NEG tmp, b
1324 // SUB dst, a, tmp
1325 // with
1326 // ADD dst, a, b
1327 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1328 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1329 RecordSimplification();
1330 right->GetBlock()->RemoveInstruction(right);
1331 return;
1332 }
1333
1334 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1335 // Replace code looking like
1336 // NEG tmp, a
1337 // SUB dst, tmp, b
1338 // with
1339 // ADD tmp, a, b
1340 // NEG dst, tmp
1341 // The second version is not intrinsically better, but enables more
1342 // transformations.
1343 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1344 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1345 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1346 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1347 instruction->ReplaceWith(neg);
1348 instruction->GetBlock()->RemoveInstruction(instruction);
1349 RecordSimplification();
1350 left->GetBlock()->RemoveInstruction(left);
1351 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001352}
1353
1354void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1355 VisitShift(instruction);
1356}
1357
1358void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1359 HConstant* input_cst = instruction->GetConstantRight();
1360 HInstruction* input_other = instruction->GetLeastConstantLeft();
1361
1362 if ((input_cst != nullptr) && input_cst->IsZero()) {
1363 // Replace code looking like
1364 // XOR dst, src, 0
1365 // with
1366 // src
1367 instruction->ReplaceWith(input_other);
1368 instruction->GetBlock()->RemoveInstruction(instruction);
1369 return;
1370 }
1371
1372 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1373 // Replace code looking like
1374 // XOR dst, src, 0xFFF...FF
1375 // with
1376 // NOT dst, src
1377 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1378 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001379 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001380 return;
1381 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001382
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001383 HInstruction* left = instruction->GetLeft();
1384 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001385 if (((left->IsNot() && right->IsNot()) ||
1386 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001387 left->HasOnlyOneNonEnvironmentUse() &&
1388 right->HasOnlyOneNonEnvironmentUse()) {
1389 // Replace code looking like
1390 // NOT nota, a
1391 // NOT notb, b
1392 // XOR dst, nota, notb
1393 // with
1394 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001395 instruction->ReplaceInput(left->InputAt(0), 0);
1396 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001397 left->GetBlock()->RemoveInstruction(left);
1398 right->GetBlock()->RemoveInstruction(right);
1399 RecordSimplification();
1400 return;
1401 }
1402
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001403 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001404}
1405
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001406void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1407 HInstruction* argument = instruction->InputAt(1);
1408 HInstruction* receiver = instruction->InputAt(0);
1409 if (receiver == argument) {
1410 // Because String.equals is an instance call, the receiver is
1411 // a null check if we don't know it's null. The argument however, will
1412 // be the actual object. So we cannot end up in a situation where both
1413 // are equal but could be null.
1414 DCHECK(CanEnsureNotNullAt(argument, instruction));
1415 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1416 instruction->GetBlock()->RemoveInstruction(instruction);
1417 } else {
1418 StringEqualsOptimizations optimizations(instruction);
1419 if (CanEnsureNotNullAt(argument, instruction)) {
1420 optimizations.SetArgumentNotNull();
1421 }
1422 ScopedObjectAccess soa(Thread::Current());
1423 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1424 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1425 optimizations.SetArgumentIsString();
1426 }
1427 }
1428}
1429
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001430void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1431 DCHECK(invoke->IsInvokeStaticOrDirect());
1432 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001433 HInstruction* value = invoke->InputAt(0);
1434 HInstruction* distance = invoke->InputAt(1);
1435 // Replace the invoke with an HRor.
1436 if (is_left) {
1437 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1438 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1439 }
1440 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1441 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1442 // Remove ClinitCheck and LoadClass, if possible.
1443 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1444 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1445 clinit->GetBlock()->RemoveInstruction(clinit);
1446 HInstruction* ldclass = clinit->InputAt(0);
1447 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1448 ldclass->GetBlock()->RemoveInstruction(ldclass);
1449 }
1450 }
1451}
1452
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001453static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1454 if (potential_length->IsArrayLength()) {
1455 return potential_length->InputAt(0) == potential_array;
1456 }
1457
1458 if (potential_array->IsNewArray()) {
1459 return potential_array->InputAt(0) == potential_length;
1460 }
1461
1462 return false;
1463}
1464
1465void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1466 HInstruction* source = instruction->InputAt(0);
1467 HInstruction* destination = instruction->InputAt(2);
1468 HInstruction* count = instruction->InputAt(4);
1469 SystemArrayCopyOptimizations optimizations(instruction);
1470 if (CanEnsureNotNullAt(source, instruction)) {
1471 optimizations.SetSourceIsNotNull();
1472 }
1473 if (CanEnsureNotNullAt(destination, instruction)) {
1474 optimizations.SetDestinationIsNotNull();
1475 }
1476 if (destination == source) {
1477 optimizations.SetDestinationIsSource();
1478 }
1479
1480 if (IsArrayLengthOf(count, source)) {
1481 optimizations.SetCountIsSourceLength();
1482 }
1483
1484 if (IsArrayLengthOf(count, destination)) {
1485 optimizations.SetCountIsDestinationLength();
1486 }
1487
1488 {
1489 ScopedObjectAccess soa(Thread::Current());
1490 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1491 if (destination_rti.IsValid()) {
1492 if (destination_rti.IsObjectArray()) {
1493 if (destination_rti.IsExact()) {
1494 optimizations.SetDoesNotNeedTypeCheck();
1495 }
1496 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001497 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001498 if (destination_rti.IsPrimitiveArrayClass()) {
1499 optimizations.SetDestinationIsPrimitiveArray();
1500 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1501 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001502 }
1503 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001504 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1505 if (source_rti.IsValid()) {
1506 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1507 optimizations.SetDoesNotNeedTypeCheck();
1508 }
1509 if (source_rti.IsPrimitiveArrayClass()) {
1510 optimizations.SetSourceIsPrimitiveArray();
1511 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1512 optimizations.SetSourceIsNonPrimitiveArray();
1513 }
1514 }
1515 }
1516}
1517
Aart Bika19616e2016-02-01 18:57:58 -08001518void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1519 DCHECK(invoke->IsInvokeStaticOrDirect());
1520 uint32_t dex_pc = invoke->GetDexPc();
1521 HInstruction* left = invoke->InputAt(0);
1522 HInstruction* right;
1523 Primitive::Type type = left->GetType();
1524 if (!is_signum) {
1525 right = invoke->InputAt(1);
1526 } else if (type == Primitive::kPrimLong) {
1527 right = GetGraph()->GetLongConstant(0);
1528 } else {
1529 right = GetGraph()->GetIntConstant(0);
1530 }
1531 HCompare* compare = new (GetGraph()->GetArena())
1532 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1533 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1534}
1535
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001536void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1537 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1538 SimplifyStringEquals(instruction);
1539 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1540 SimplifySystemArrayCopy(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001541 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateRight ||
1542 instruction->GetIntrinsic() == Intrinsics::kLongRotateRight) {
1543 SimplifyRotate(instruction, false);
1544 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateLeft ||
1545 instruction->GetIntrinsic() == Intrinsics::kLongRotateLeft) {
1546 SimplifyRotate(instruction, true);
Aart Bika19616e2016-02-01 18:57:58 -08001547 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerCompare ||
1548 instruction->GetIntrinsic() == Intrinsics::kLongCompare) {
1549 SimplifyCompare(instruction, /* is_signum */ false);
1550 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerSignum ||
1551 instruction->GetIntrinsic() == Intrinsics::kLongSignum) {
1552 SimplifyCompare(instruction, /* is_signum */ true);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001553 }
1554}
1555
Aart Bikbb245d12015-10-19 11:05:03 -07001556void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1557 HInstruction* cond = deoptimize->InputAt(0);
1558 if (cond->IsConstant()) {
1559 if (cond->AsIntConstant()->IsZero()) {
1560 // Never deopt: instruction can be removed.
1561 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1562 } else {
1563 // Always deopt.
1564 }
1565 }
1566}
1567
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001568} // namespace art