blob: f8a9a94e62a76d573f79214b7ecf3bed76bc155f [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);
Aart Bik75a38b22016-02-17 10:41:50 -080095 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -080096 void SimplifyFP2Int(HInvoke* invoke);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010097
Calin Juravleacf735c2015-02-12 15:25:22 +000098 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010099 bool simplification_occurred_ = false;
100 int simplifications_at_current_position_ = 0;
101 // We ensure we do not loop infinitely. The value is a finger in the air guess
102 // that should allow enough simplification.
103 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000104};
105
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100106void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000107 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100108 visitor.Run();
109}
110
111void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100112 // Iterate in reverse post order to open up more simplifications to users
113 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100114 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
115 // The simplification of an instruction to another instruction may yield
116 // possibilities for other simplifications. So although we perform a reverse
117 // post order visit, we sometimes need to revisit an instruction index.
118 simplification_occurred_ = false;
119 VisitBasicBlock(it.Current());
120 if (simplification_occurred_ &&
121 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
122 // New simplifications may be applicable to the instruction at the
123 // current index, so don't advance the iterator.
124 continue;
125 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100126 simplifications_at_current_position_ = 0;
127 it.Advance();
128 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100129}
130
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000131namespace {
132
133bool AreAllBitsSet(HConstant* constant) {
134 return Int64FromConstant(constant) == -1;
135}
136
137} // namespace
138
Alexandre Rames188d4312015-04-09 18:30:21 +0100139// Returns true if the code was simplified to use only one negation operation
140// after the binary operation instead of one on each of the inputs.
141bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
142 DCHECK(binop->IsAdd() || binop->IsSub());
143 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
144 HNeg* left_neg = binop->GetLeft()->AsNeg();
145 HNeg* right_neg = binop->GetRight()->AsNeg();
146 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
147 !right_neg->HasOnlyOneNonEnvironmentUse()) {
148 return false;
149 }
150 // Replace code looking like
151 // NEG tmp1, a
152 // NEG tmp2, b
153 // ADD dst, tmp1, tmp2
154 // with
155 // ADD tmp, a, b
156 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600157 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
158 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
159 // while the later yields `-0.0`.
160 if (!Primitive::IsIntegralType(binop->GetType())) {
161 return false;
162 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100163 binop->ReplaceInput(left_neg->GetInput(), 0);
164 binop->ReplaceInput(right_neg->GetInput(), 1);
165 left_neg->GetBlock()->RemoveInstruction(left_neg);
166 right_neg->GetBlock()->RemoveInstruction(right_neg);
167 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
168 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
169 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
170 RecordSimplification();
171 return true;
172}
173
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000174bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
175 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
176 Primitive::Type type = op->GetType();
177 HInstruction* left = op->GetLeft();
178 HInstruction* right = op->GetRight();
179
180 // We can apply De Morgan's laws if both inputs are Not's and are only used
181 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000182 if (((left->IsNot() && right->IsNot()) ||
183 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000184 left->HasOnlyOneNonEnvironmentUse() &&
185 right->HasOnlyOneNonEnvironmentUse()) {
186 // Replace code looking like
187 // NOT nota, a
188 // NOT notb, b
189 // AND dst, nota, notb (respectively OR)
190 // with
191 // OR or, a, b (respectively AND)
192 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000193 HInstruction* src_left = left->InputAt(0);
194 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000195 uint32_t dex_pc = op->GetDexPc();
196
197 // Remove the negations on the inputs.
198 left->ReplaceWith(src_left);
199 right->ReplaceWith(src_right);
200 left->GetBlock()->RemoveInstruction(left);
201 right->GetBlock()->RemoveInstruction(right);
202
203 // Replace the `HAnd` or `HOr`.
204 HBinaryOperation* hbin;
205 if (op->IsAnd()) {
206 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
207 } else {
208 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
209 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000210 HInstruction* hnot;
211 if (left->IsBooleanNot()) {
212 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
213 } else {
214 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
215 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000216
217 op->GetBlock()->InsertInstructionBefore(hbin, op);
218 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
219
220 RecordSimplification();
221 return true;
222 }
223
224 return false;
225}
226
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000227void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
228 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
229 HConstant* input_cst = instruction->GetConstantRight();
230 HInstruction* input_other = instruction->GetLeastConstantLeft();
231
Mark Mendellba56d062015-05-05 21:34:03 -0400232 if (input_cst != nullptr) {
233 if (input_cst->IsZero()) {
234 // Replace code looking like
235 // SHL dst, src, 0
236 // with
237 // src
238 instruction->ReplaceWith(input_other);
239 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400240 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000241 }
242}
243
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000244static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
245 return (sub->GetRight() == other &&
246 sub->GetLeft()->IsConstant() &&
247 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
248}
249
250bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
251 HUShr* ushr,
252 HShl* shl) {
253 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
254 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
255 ushr->GetLeft(),
256 ushr->GetRight());
257 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
258 if (!ushr->HasUses()) {
259 ushr->GetBlock()->RemoveInstruction(ushr);
260 }
261 if (!ushr->GetRight()->HasUses()) {
262 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
263 }
264 if (!shl->HasUses()) {
265 shl->GetBlock()->RemoveInstruction(shl);
266 }
267 if (!shl->GetRight()->HasUses()) {
268 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
269 }
270 return true;
271}
272
273// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
274bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000275 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
276 HInstruction* left = op->GetLeft();
277 HInstruction* right = op->GetRight();
278 // If we have an UShr and a Shl (in either order).
279 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
280 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
281 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
282 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
283 if (ushr->GetType() == shl->GetType() &&
284 ushr->GetLeft() == shl->GetLeft()) {
285 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
286 // Shift distances are both constant, try replacing with Ror if they
287 // add up to the register size.
288 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
289 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
290 // Shift distances are potentially of the form x and (reg_size - x).
291 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
292 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
293 // Shift distances are potentially of the form d and -d.
294 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
295 }
296 }
297 }
298 return false;
299}
300
301// Try replacing code looking like (x >>> #rdist OP x << #ldist):
302// UShr dst, x, #rdist
303// Shl tmp, x, #ldist
304// OP dst, dst, tmp
305// or like (x >>> #rdist OP x << #-ldist):
306// UShr dst, x, #rdist
307// Shl tmp, x, #-ldist
308// OP dst, dst, tmp
309// with
310// Ror dst, x, #rdist
311bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
312 HUShr* ushr,
313 HShl* shl) {
314 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
315 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
316 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
317 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
318 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
319 ReplaceRotateWithRor(op, ushr, shl);
320 return true;
321 }
322 return false;
323}
324
325// Replace code looking like (x >>> -d OP x << d):
326// Neg neg, d
327// UShr dst, x, neg
328// Shl tmp, x, d
329// OP dst, dst, tmp
330// with
331// Neg neg, d
332// Ror dst, x, neg
333// *** OR ***
334// Replace code looking like (x >>> d OP x << -d):
335// UShr dst, x, d
336// Neg neg, d
337// Shl tmp, x, neg
338// OP dst, dst, tmp
339// with
340// Ror dst, x, d
341bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
342 HUShr* ushr,
343 HShl* shl) {
344 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
345 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
346 bool neg_is_left = shl->GetRight()->IsNeg();
347 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
348 // And the shift distance being negated is the distance being shifted the other way.
349 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
350 ReplaceRotateWithRor(op, ushr, shl);
351 }
352 return false;
353}
354
355// Try replacing code looking like (x >>> d OP x << (#bits - d)):
356// UShr dst, x, d
357// Sub ld, #bits, d
358// Shl tmp, x, ld
359// OP dst, dst, tmp
360// with
361// Ror dst, x, d
362// *** OR ***
363// Replace code looking like (x >>> (#bits - d) OP x << d):
364// Sub rd, #bits, d
365// UShr dst, x, rd
366// Shl tmp, x, d
367// OP dst, dst, tmp
368// with
369// Neg neg, d
370// Ror dst, x, neg
371bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
372 HUShr* ushr,
373 HShl* shl) {
374 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
375 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
376 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
377 HInstruction* shl_shift = shl->GetRight();
378 HInstruction* ushr_shift = ushr->GetRight();
379 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
380 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
381 return ReplaceRotateWithRor(op, ushr, shl);
382 }
383 return false;
384}
385
Calin Juravle10e244f2015-01-26 18:54:32 +0000386void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
387 HInstruction* obj = null_check->InputAt(0);
388 if (!obj->CanBeNull()) {
389 null_check->ReplaceWith(obj);
390 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000391 if (stats_ != nullptr) {
392 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
393 }
394 }
395}
396
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100397bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
398 if (!input->CanBeNull()) {
399 return true;
400 }
401
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100402 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
403 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100404 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100405 return true;
406 }
407 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100408
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100409 return false;
410}
411
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100412// Returns whether doing a type test between the class of `object` against `klass` has
413// a statically known outcome. The result of the test is stored in `outcome`.
414static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000415 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
416 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
417 ScopedObjectAccess soa(Thread::Current());
418 if (!obj_rti.IsValid()) {
419 // We run the simplifier before the reference type propagation so type info might not be
420 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100421 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000422 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100423
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100424 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100425 if (!class_rti.IsValid()) {
426 // Happens when the loaded class is unresolved.
427 return false;
428 }
429 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000430 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100431 *outcome = true;
432 return true;
433 } else if (obj_rti.IsExact()) {
434 // The test failed at compile time so will also fail at runtime.
435 *outcome = false;
436 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100437 } else if (!class_rti.IsInterface()
438 && !obj_rti.IsInterface()
439 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100440 // Different type hierarchy. The test will fail.
441 *outcome = false;
442 return true;
443 }
444 return false;
445}
446
447void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
448 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100449 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
450 if (load_class->NeedsAccessCheck()) {
451 // If we need to perform an access check we cannot remove the instruction.
452 return;
453 }
454
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100455 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100456 check_cast->ClearMustDoNullCheck();
457 }
458
459 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000460 check_cast->GetBlock()->RemoveInstruction(check_cast);
461 if (stats_ != nullptr) {
462 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
463 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100464 return;
465 }
466
467 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700468 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100469 if (outcome) {
470 check_cast->GetBlock()->RemoveInstruction(check_cast);
471 if (stats_ != nullptr) {
472 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
473 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700474 if (!load_class->HasUses()) {
475 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
476 // However, here we know that it cannot because the checkcast was successfull, hence
477 // the class was already loaded.
478 load_class->GetBlock()->RemoveInstruction(load_class);
479 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100480 } else {
481 // Don't do anything for exceptional cases for now. Ideally we should remove
482 // all instructions and blocks this instruction dominates.
483 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000484 }
485}
486
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100487void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100488 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100489 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
490 if (load_class->NeedsAccessCheck()) {
491 // If we need to perform an access check we cannot remove the instruction.
492 return;
493 }
494
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100495 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100496 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100497 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100498 instruction->ClearMustDoNullCheck();
499 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100500
501 HGraph* graph = GetGraph();
502 if (object->IsNullConstant()) {
503 instruction->ReplaceWith(graph->GetIntConstant(0));
504 instruction->GetBlock()->RemoveInstruction(instruction);
505 RecordSimplification();
506 return;
507 }
508
509 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700510 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100511 if (outcome && can_be_null) {
512 // Type test will succeed, we just need a null test.
513 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
514 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
515 instruction->ReplaceWith(test);
516 } else {
517 // We've statically determined the result of the instanceof.
518 instruction->ReplaceWith(graph->GetIntConstant(outcome));
519 }
520 RecordSimplification();
521 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700522 if (outcome && !load_class->HasUses()) {
523 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
524 // However, here we know that it cannot because the instanceof check was successfull, hence
525 // the class was already loaded.
526 load_class->GetBlock()->RemoveInstruction(load_class);
527 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100528 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100529}
530
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100531void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
532 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100533 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100534 instruction->ClearValueCanBeNull();
535 }
536}
537
538void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
539 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100540 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100541 instruction->ClearValueCanBeNull();
542 }
543}
544
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000545void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100546 HBasicBlock* block = check->GetBlock();
547 // Currently always keep the suspend check at entry.
548 if (block->IsEntryBlock()) return;
549
550 // Currently always keep suspend checks at loop entry.
551 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
552 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
553 return;
554 }
555
556 // Remove the suspend check that was added at build time for the baseline
557 // compiler.
558 block->RemoveInstruction(check);
559}
560
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000561void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100562 HInstruction* input_const = equal->GetConstantRight();
563 if (input_const != nullptr) {
564 HInstruction* input_value = equal->GetLeastConstantLeft();
565 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
566 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100567 // We are comparing the boolean to a constant which is of type int and can
568 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100569 if (input_const->AsIntConstant()->IsOne()) {
570 // Replace (bool_value == true) with bool_value
571 equal->ReplaceWith(input_value);
572 block->RemoveInstruction(equal);
573 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100574 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500575 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
576 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100577 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100578 } else {
579 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
580 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
581 block->RemoveInstruction(equal);
582 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100583 }
Mark Mendellc4701932015-04-10 13:18:51 -0400584 } else {
585 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100586 }
Mark Mendellc4701932015-04-10 13:18:51 -0400587 } else {
588 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100589 }
590}
591
David Brazdil0d13fee2015-04-17 14:52:19 +0100592void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
593 HInstruction* input_const = not_equal->GetConstantRight();
594 if (input_const != nullptr) {
595 HInstruction* input_value = not_equal->GetLeastConstantLeft();
596 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
597 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100598 // We are comparing the boolean to a constant which is of type int and can
599 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100600 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500601 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
602 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100603 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100604 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100605 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100606 not_equal->ReplaceWith(input_value);
607 block->RemoveInstruction(not_equal);
608 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100609 } else {
610 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
611 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
612 block->RemoveInstruction(not_equal);
613 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100614 }
Mark Mendellc4701932015-04-10 13:18:51 -0400615 } else {
616 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100617 }
Mark Mendellc4701932015-04-10 13:18:51 -0400618 } else {
619 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100620 }
621}
622
623void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000624 HInstruction* input = bool_not->InputAt(0);
625 HInstruction* replace_with = nullptr;
626
627 if (input->IsIntConstant()) {
628 // Replace !(true/false) with false/true.
629 if (input->AsIntConstant()->IsOne()) {
630 replace_with = GetGraph()->GetIntConstant(0);
631 } else {
632 DCHECK(input->AsIntConstant()->IsZero());
633 replace_with = GetGraph()->GetIntConstant(1);
634 }
635 } else if (input->IsBooleanNot()) {
636 // Replace (!(!bool_value)) with bool_value.
637 replace_with = input->InputAt(0);
638 } else if (input->IsCondition() &&
639 // Don't change FP compares. The definition of compares involving
640 // NaNs forces the compares to be done as written by the user.
641 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
642 // Replace condition with its opposite.
643 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
644 }
645
646 if (replace_with != nullptr) {
647 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100648 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000649 RecordSimplification();
650 }
651}
652
653void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
654 HInstruction* replace_with = nullptr;
655 HInstruction* condition = select->GetCondition();
656 HInstruction* true_value = select->GetTrueValue();
657 HInstruction* false_value = select->GetFalseValue();
658
659 if (condition->IsBooleanNot()) {
660 // Change ((!cond) ? x : y) to (cond ? y : x).
661 condition = condition->InputAt(0);
662 std::swap(true_value, false_value);
663 select->ReplaceInput(false_value, 0);
664 select->ReplaceInput(true_value, 1);
665 select->ReplaceInput(condition, 2);
666 RecordSimplification();
667 }
668
669 if (true_value == false_value) {
670 // Replace (cond ? x : x) with (x).
671 replace_with = true_value;
672 } else if (condition->IsIntConstant()) {
673 if (condition->AsIntConstant()->IsOne()) {
674 // Replace (true ? x : y) with (x).
675 replace_with = true_value;
676 } else {
677 // Replace (false ? x : y) with (y).
678 DCHECK(condition->AsIntConstant()->IsZero());
679 replace_with = false_value;
680 }
681 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
682 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
683 // Replace (cond ? true : false) with (cond).
684 replace_with = condition;
685 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
686 // Replace (cond ? false : true) with (!cond).
687 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
688 }
689 }
690
691 if (replace_with != nullptr) {
692 select->ReplaceWith(replace_with);
693 select->GetBlock()->RemoveInstruction(select);
694 RecordSimplification();
695 }
696}
697
698void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
699 HInstruction* condition = instruction->InputAt(0);
700 if (condition->IsBooleanNot()) {
701 // Swap successors if input is negated.
702 instruction->ReplaceInput(condition->InputAt(0), 0);
703 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100704 RecordSimplification();
705 }
706}
707
Mingyao Yang0304e182015-01-30 16:41:29 -0800708void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
709 HInstruction* input = instruction->InputAt(0);
710 // If the array is a NewArray with constant size, replace the array length
711 // with the constant instruction. This helps the bounds check elimination phase.
712 if (input->IsNewArray()) {
713 input = input->InputAt(0);
714 if (input->IsIntConstant()) {
715 instruction->ReplaceWith(input);
716 }
717 }
718}
719
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000720void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000721 HInstruction* value = instruction->GetValue();
722 if (value->GetType() != Primitive::kPrimNot) return;
723
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100724 if (CanEnsureNotNullAt(value, instruction)) {
725 instruction->ClearValueCanBeNull();
726 }
727
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000728 if (value->IsArrayGet()) {
729 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
730 // If the code is just swapping elements in the array, no need for a type check.
731 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100732 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000733 }
734 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100735
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100736 if (value->IsNullConstant()) {
737 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100738 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100739 }
740
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100741 ScopedObjectAccess soa(Thread::Current());
742 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
743 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
744 if (!array_rti.IsValid()) {
745 return;
746 }
747
748 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
749 instruction->ClearNeedsTypeCheck();
750 return;
751 }
752
753 if (array_rti.IsObjectArray()) {
754 if (array_rti.IsExact()) {
755 instruction->ClearNeedsTypeCheck();
756 return;
757 }
758 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100759 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000760}
761
Vladimir Markob52bbde2016-02-12 12:06:05 +0000762static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
763 // Besides conversion to the same type, widening integral conversions are implicit,
764 // excluding conversions to long and the byte->char conversion where we need to
765 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
766 return result_type == input_type ||
767 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
768 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
769 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
770 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
771}
772
773static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
774 // The conversion to a larger type is loss-less with the exception of two cases,
775 // - conversion to char, the only unsigned type, where we may lose some bits, and
776 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
777 // For integral to FP conversions this holds because the FP mantissa is large enough.
778 DCHECK_NE(input_type, result_type);
779 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
780 result_type != Primitive::kPrimChar &&
781 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
782}
783
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000784void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000785 HInstruction* input = instruction->GetInput();
786 Primitive::Type input_type = input->GetType();
787 Primitive::Type result_type = instruction->GetResultType();
788 if (IsTypeConversionImplicit(input_type, result_type)) {
789 // Remove the implicit conversion; this includes conversion to the same type.
790 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000791 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000792 RecordSimplification();
793 return;
794 }
795
796 if (input->IsTypeConversion()) {
797 HTypeConversion* input_conversion = input->AsTypeConversion();
798 HInstruction* original_input = input_conversion->GetInput();
799 Primitive::Type original_type = original_input->GetType();
800
801 // When the first conversion is lossless, a direct conversion from the original type
802 // to the final type yields the same result, even for a lossy second conversion, for
803 // example float->double->int or int->double->float.
804 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
805
806 // For integral conversions, see if the first conversion loses only bits that the second
807 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
808 // conversion yields the same result, for example long->int->short or int->char->short.
809 bool integral_conversions_with_non_widening_second =
810 Primitive::IsIntegralType(input_type) &&
811 Primitive::IsIntegralType(original_type) &&
812 Primitive::IsIntegralType(result_type) &&
813 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
814
815 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
816 // If the merged conversion is implicit, do the simplification unconditionally.
817 if (IsTypeConversionImplicit(original_type, result_type)) {
818 instruction->ReplaceWith(original_input);
819 instruction->GetBlock()->RemoveInstruction(instruction);
820 if (!input_conversion->HasUses()) {
821 // Don't wait for DCE.
822 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
823 }
824 RecordSimplification();
825 return;
826 }
827 // Otherwise simplify only if the first conversion has no other use.
828 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
829 input_conversion->ReplaceWith(original_input);
830 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
831 RecordSimplification();
832 return;
833 }
834 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000835 } else if (input->IsAnd() &&
836 Primitive::IsIntegralType(result_type) &&
837 input->HasOnlyOneNonEnvironmentUse()) {
838 DCHECK(Primitive::IsIntegralType(input_type));
839 HAnd* input_and = input->AsAnd();
840 HConstant* constant = input_and->GetConstantRight();
841 if (constant != nullptr) {
842 int64_t value = Int64FromConstant(constant);
843 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
844 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
845 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
846 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
847 input_and->ReplaceWith(input_and->GetLeastConstantLeft());
848 input_and->GetBlock()->RemoveInstruction(input_and);
849 RecordSimplification();
850 return;
851 }
852 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000853 }
854}
855
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000856void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
857 HConstant* input_cst = instruction->GetConstantRight();
858 HInstruction* input_other = instruction->GetLeastConstantLeft();
859 if ((input_cst != nullptr) && input_cst->IsZero()) {
860 // Replace code looking like
861 // ADD dst, src, 0
862 // with
863 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600864 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
865 // `x` is `-0.0`, the former expression yields `0.0`, while the later
866 // yields `-0.0`.
867 if (Primitive::IsIntegralType(instruction->GetType())) {
868 instruction->ReplaceWith(input_other);
869 instruction->GetBlock()->RemoveInstruction(instruction);
870 return;
871 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100872 }
873
874 HInstruction* left = instruction->GetLeft();
875 HInstruction* right = instruction->GetRight();
876 bool left_is_neg = left->IsNeg();
877 bool right_is_neg = right->IsNeg();
878
879 if (left_is_neg && right_is_neg) {
880 if (TryMoveNegOnInputsAfterBinop(instruction)) {
881 return;
882 }
883 }
884
885 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
886 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
887 // Replace code looking like
888 // NEG tmp, b
889 // ADD dst, a, tmp
890 // with
891 // SUB dst, a, b
892 // We do not perform the optimization if the input negation has environment
893 // uses or multiple non-environment uses as it could lead to worse code. In
894 // particular, we do not want the live range of `b` to be extended if we are
895 // not sure the initial 'NEG' instruction can be removed.
896 HInstruction* other = left_is_neg ? right : left;
897 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
898 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
899 RecordSimplification();
900 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000901 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000902 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000903
904 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000905}
906
907void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
908 HConstant* input_cst = instruction->GetConstantRight();
909 HInstruction* input_other = instruction->GetLeastConstantLeft();
910
Vladimir Marko452c1b62015-09-25 14:44:17 +0100911 if (input_cst != nullptr) {
912 int64_t value = Int64FromConstant(input_cst);
913 if (value == -1) {
914 // Replace code looking like
915 // AND dst, src, 0xFFF...FF
916 // with
917 // src
918 instruction->ReplaceWith(input_other);
919 instruction->GetBlock()->RemoveInstruction(instruction);
920 RecordSimplification();
921 return;
922 }
923 // Eliminate And from UShr+And if the And-mask contains all the bits that
924 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
925 // precisely clears the shifted-in sign bits.
926 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
927 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
928 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
929 size_t num_tail_bits_set = CTZ(value + 1);
930 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
931 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
932 instruction->ReplaceWith(input_other);
933 instruction->GetBlock()->RemoveInstruction(instruction);
934 RecordSimplification();
935 return;
936 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
937 input_other->HasOnlyOneNonEnvironmentUse()) {
938 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
939 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
940 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
941 input_other->InputAt(0),
942 input_other->InputAt(1),
943 input_other->GetDexPc());
944 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
945 input_other->GetBlock()->RemoveInstruction(input_other);
946 RecordSimplification();
947 return;
948 }
949 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000950 }
951
952 // We assume that GVN has run before, so we only perform a pointer comparison.
953 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100954 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000955 if (instruction->GetLeft() == instruction->GetRight()) {
956 // Replace code looking like
957 // AND dst, src, src
958 // with
959 // src
960 instruction->ReplaceWith(instruction->GetLeft());
961 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000962 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000963 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000964
965 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000966}
967
Mark Mendellc4701932015-04-10 13:18:51 -0400968void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
969 VisitCondition(condition);
970}
971
972void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
973 VisitCondition(condition);
974}
975
976void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
977 VisitCondition(condition);
978}
979
980void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
981 VisitCondition(condition);
982}
983
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000984// TODO: unsigned comparisons too?
Aart Bike9f37602015-10-09 11:15:55 -0700985
Mark Mendellc4701932015-04-10 13:18:51 -0400986void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000987 // Try to fold an HCompare into this HCondition.
Mark Mendellc4701932015-04-10 13:18:51 -0400988
Mark Mendellc4701932015-04-10 13:18:51 -0400989 HInstruction* left = condition->GetLeft();
990 HInstruction* right = condition->GetRight();
991 // We can only replace an HCondition which compares a Compare to 0.
992 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
993 // condition with a long, float or double comparison as input.
994 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
995 // Conversion is not possible.
996 return;
997 }
998
999 // Is the Compare only used for this purpose?
1000 if (!left->GetUses().HasOnlyOneUse()) {
1001 // Someone else also wants the result of the compare.
1002 return;
1003 }
1004
1005 if (!left->GetEnvUses().IsEmpty()) {
1006 // There is a reference to the compare result in an environment. Do we really need it?
1007 if (GetGraph()->IsDebuggable()) {
1008 return;
1009 }
1010
1011 // We have to ensure that there are no deopt points in the sequence.
1012 if (left->HasAnyEnvironmentUseBefore(condition)) {
1013 return;
1014 }
1015 }
1016
1017 // Clean up any environment uses from the HCompare, if any.
1018 left->RemoveEnvironmentUsers();
1019
1020 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1021 condition->SetBias(left->AsCompare()->GetBias());
1022
1023 // Replace the operands of the HCondition.
1024 condition->ReplaceInput(left->InputAt(0), 0);
1025 condition->ReplaceInput(left->InputAt(1), 1);
1026
1027 // Remove the HCompare.
1028 left->GetBlock()->RemoveInstruction(left);
1029
1030 RecordSimplification();
1031}
1032
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001033void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1034 HConstant* input_cst = instruction->GetConstantRight();
1035 HInstruction* input_other = instruction->GetLeastConstantLeft();
1036 Primitive::Type type = instruction->GetType();
1037
1038 if ((input_cst != nullptr) && input_cst->IsOne()) {
1039 // Replace code looking like
1040 // DIV dst, src, 1
1041 // with
1042 // src
1043 instruction->ReplaceWith(input_other);
1044 instruction->GetBlock()->RemoveInstruction(instruction);
1045 return;
1046 }
1047
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001048 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001049 // Replace code looking like
1050 // DIV dst, src, -1
1051 // with
1052 // NEG dst, src
1053 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001054 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001055 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001056 return;
1057 }
1058
1059 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1060 // Try replacing code looking like
1061 // DIV dst, src, constant
1062 // with
1063 // MUL dst, src, 1 / constant
1064 HConstant* reciprocal = nullptr;
1065 if (type == Primitive::Primitive::kPrimDouble) {
1066 double value = input_cst->AsDoubleConstant()->GetValue();
1067 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1068 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1069 }
1070 } else {
1071 DCHECK_EQ(type, Primitive::kPrimFloat);
1072 float value = input_cst->AsFloatConstant()->GetValue();
1073 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1074 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1075 }
1076 }
1077
1078 if (reciprocal != nullptr) {
1079 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1080 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1081 RecordSimplification();
1082 return;
1083 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001084 }
1085}
1086
1087void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1088 HConstant* input_cst = instruction->GetConstantRight();
1089 HInstruction* input_other = instruction->GetLeastConstantLeft();
1090 Primitive::Type type = instruction->GetType();
1091 HBasicBlock* block = instruction->GetBlock();
1092 ArenaAllocator* allocator = GetGraph()->GetArena();
1093
1094 if (input_cst == nullptr) {
1095 return;
1096 }
1097
1098 if (input_cst->IsOne()) {
1099 // Replace code looking like
1100 // MUL dst, src, 1
1101 // with
1102 // src
1103 instruction->ReplaceWith(input_other);
1104 instruction->GetBlock()->RemoveInstruction(instruction);
1105 return;
1106 }
1107
1108 if (input_cst->IsMinusOne() &&
1109 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1110 // Replace code looking like
1111 // MUL dst, src, -1
1112 // with
1113 // NEG dst, src
1114 HNeg* neg = new (allocator) HNeg(type, input_other);
1115 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001116 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001117 return;
1118 }
1119
1120 if (Primitive::IsFloatingPointType(type) &&
1121 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1122 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1123 // Replace code looking like
1124 // FP_MUL dst, src, 2.0
1125 // with
1126 // FP_ADD dst, src, src
1127 // The 'int' and 'long' cases are handled below.
1128 block->ReplaceAndRemoveInstructionWith(instruction,
1129 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001130 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001131 return;
1132 }
1133
1134 if (Primitive::IsIntOrLongType(type)) {
1135 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001136 // Even though constant propagation also takes care of the zero case, other
1137 // optimizations can lead to having a zero multiplication.
1138 if (factor == 0) {
1139 // Replace code looking like
1140 // MUL dst, src, 0
1141 // with
1142 // 0
1143 instruction->ReplaceWith(input_cst);
1144 instruction->GetBlock()->RemoveInstruction(instruction);
1145 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001146 // Replace code looking like
1147 // MUL dst, src, pow_of_2
1148 // with
1149 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001150 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001151 HShl* shl = new(allocator) HShl(type, input_other, shift);
1152 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001153 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001154 } else if (IsPowerOfTwo(factor - 1)) {
1155 // Transform code looking like
1156 // MUL dst, src, (2^n + 1)
1157 // into
1158 // SHL tmp, src, n
1159 // ADD dst, src, tmp
1160 HShl* shl = new (allocator) HShl(type,
1161 input_other,
1162 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1163 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1164
1165 block->InsertInstructionBefore(shl, instruction);
1166 block->ReplaceAndRemoveInstructionWith(instruction, add);
1167 RecordSimplification();
1168 } else if (IsPowerOfTwo(factor + 1)) {
1169 // Transform code looking like
1170 // MUL dst, src, (2^n - 1)
1171 // into
1172 // SHL tmp, src, n
1173 // SUB dst, tmp, src
1174 HShl* shl = new (allocator) HShl(type,
1175 input_other,
1176 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1177 HSub* sub = new (allocator) HSub(type, shl, input_other);
1178
1179 block->InsertInstructionBefore(shl, instruction);
1180 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1181 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001182 }
1183 }
1184}
1185
Alexandre Rames188d4312015-04-09 18:30:21 +01001186void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1187 HInstruction* input = instruction->GetInput();
1188 if (input->IsNeg()) {
1189 // Replace code looking like
1190 // NEG tmp, src
1191 // NEG dst, tmp
1192 // with
1193 // src
1194 HNeg* previous_neg = input->AsNeg();
1195 instruction->ReplaceWith(previous_neg->GetInput());
1196 instruction->GetBlock()->RemoveInstruction(instruction);
1197 // We perform the optimization even if the input negation has environment
1198 // uses since it allows removing the current instruction. But we only delete
1199 // the input negation only if it is does not have any uses left.
1200 if (!previous_neg->HasUses()) {
1201 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1202 }
1203 RecordSimplification();
1204 return;
1205 }
1206
Serguei Katkov339dfc22015-04-20 12:29:32 +06001207 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1208 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001209 // Replace code looking like
1210 // SUB tmp, a, b
1211 // NEG dst, tmp
1212 // with
1213 // SUB dst, b, a
1214 // We do not perform the optimization if the input subtraction has
1215 // environment uses or multiple non-environment uses as it could lead to
1216 // worse code. In particular, we do not want the live ranges of `a` and `b`
1217 // to be extended if we are not sure the initial 'SUB' instruction can be
1218 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001219 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001220 HSub* sub = input->AsSub();
1221 HSub* new_sub =
1222 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1223 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1224 if (!sub->HasUses()) {
1225 sub->GetBlock()->RemoveInstruction(sub);
1226 }
1227 RecordSimplification();
1228 }
1229}
1230
1231void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1232 HInstruction* input = instruction->GetInput();
1233 if (input->IsNot()) {
1234 // Replace code looking like
1235 // NOT tmp, src
1236 // NOT dst, tmp
1237 // with
1238 // src
1239 // We perform the optimization even if the input negation has environment
1240 // uses since it allows removing the current instruction. But we only delete
1241 // the input negation only if it is does not have any uses left.
1242 HNot* previous_not = input->AsNot();
1243 instruction->ReplaceWith(previous_not->GetInput());
1244 instruction->GetBlock()->RemoveInstruction(instruction);
1245 if (!previous_not->HasUses()) {
1246 previous_not->GetBlock()->RemoveInstruction(previous_not);
1247 }
1248 RecordSimplification();
1249 }
1250}
1251
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001252void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1253 HConstant* input_cst = instruction->GetConstantRight();
1254 HInstruction* input_other = instruction->GetLeastConstantLeft();
1255
1256 if ((input_cst != nullptr) && input_cst->IsZero()) {
1257 // Replace code looking like
1258 // OR dst, src, 0
1259 // with
1260 // src
1261 instruction->ReplaceWith(input_other);
1262 instruction->GetBlock()->RemoveInstruction(instruction);
1263 return;
1264 }
1265
1266 // We assume that GVN has run before, so we only perform a pointer comparison.
1267 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001268 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001269 if (instruction->GetLeft() == instruction->GetRight()) {
1270 // Replace code looking like
1271 // OR dst, src, src
1272 // with
1273 // src
1274 instruction->ReplaceWith(instruction->GetLeft());
1275 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001276 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001277 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001278
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001279 if (TryDeMorganNegationFactoring(instruction)) return;
1280
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001281 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001282}
1283
1284void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1285 VisitShift(instruction);
1286}
1287
1288void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1289 VisitShift(instruction);
1290}
1291
1292void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1293 HConstant* input_cst = instruction->GetConstantRight();
1294 HInstruction* input_other = instruction->GetLeastConstantLeft();
1295
Serguei Katkov115b53f2015-08-05 17:03:30 +06001296 Primitive::Type type = instruction->GetType();
1297 if (Primitive::IsFloatingPointType(type)) {
1298 return;
1299 }
1300
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001301 if ((input_cst != nullptr) && input_cst->IsZero()) {
1302 // Replace code looking like
1303 // SUB dst, src, 0
1304 // with
1305 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001306 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1307 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1308 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001309 instruction->ReplaceWith(input_other);
1310 instruction->GetBlock()->RemoveInstruction(instruction);
1311 return;
1312 }
1313
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001314 HBasicBlock* block = instruction->GetBlock();
1315 ArenaAllocator* allocator = GetGraph()->GetArena();
1316
Alexandre Rames188d4312015-04-09 18:30:21 +01001317 HInstruction* left = instruction->GetLeft();
1318 HInstruction* right = instruction->GetRight();
1319 if (left->IsConstant()) {
1320 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001321 // Replace code looking like
1322 // SUB dst, 0, src
1323 // with
1324 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001325 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001326 // `x` is `0.0`, the former expression yields `0.0`, while the later
1327 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001328 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001329 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001330 RecordSimplification();
1331 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001332 }
1333 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001334
1335 if (left->IsNeg() && right->IsNeg()) {
1336 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1337 return;
1338 }
1339 }
1340
1341 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1342 // Replace code looking like
1343 // NEG tmp, b
1344 // SUB dst, a, tmp
1345 // with
1346 // ADD dst, a, b
1347 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1348 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1349 RecordSimplification();
1350 right->GetBlock()->RemoveInstruction(right);
1351 return;
1352 }
1353
1354 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1355 // Replace code looking like
1356 // NEG tmp, a
1357 // SUB dst, tmp, b
1358 // with
1359 // ADD tmp, a, b
1360 // NEG dst, tmp
1361 // The second version is not intrinsically better, but enables more
1362 // transformations.
1363 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1364 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1365 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1366 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1367 instruction->ReplaceWith(neg);
1368 instruction->GetBlock()->RemoveInstruction(instruction);
1369 RecordSimplification();
1370 left->GetBlock()->RemoveInstruction(left);
1371 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001372}
1373
1374void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1375 VisitShift(instruction);
1376}
1377
1378void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1379 HConstant* input_cst = instruction->GetConstantRight();
1380 HInstruction* input_other = instruction->GetLeastConstantLeft();
1381
1382 if ((input_cst != nullptr) && input_cst->IsZero()) {
1383 // Replace code looking like
1384 // XOR dst, src, 0
1385 // with
1386 // src
1387 instruction->ReplaceWith(input_other);
1388 instruction->GetBlock()->RemoveInstruction(instruction);
1389 return;
1390 }
1391
1392 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1393 // Replace code looking like
1394 // XOR dst, src, 0xFFF...FF
1395 // with
1396 // NOT dst, src
1397 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1398 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001399 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001400 return;
1401 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001402
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001403 HInstruction* left = instruction->GetLeft();
1404 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001405 if (((left->IsNot() && right->IsNot()) ||
1406 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001407 left->HasOnlyOneNonEnvironmentUse() &&
1408 right->HasOnlyOneNonEnvironmentUse()) {
1409 // Replace code looking like
1410 // NOT nota, a
1411 // NOT notb, b
1412 // XOR dst, nota, notb
1413 // with
1414 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001415 instruction->ReplaceInput(left->InputAt(0), 0);
1416 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001417 left->GetBlock()->RemoveInstruction(left);
1418 right->GetBlock()->RemoveInstruction(right);
1419 RecordSimplification();
1420 return;
1421 }
1422
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001423 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001424}
1425
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001426void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1427 HInstruction* argument = instruction->InputAt(1);
1428 HInstruction* receiver = instruction->InputAt(0);
1429 if (receiver == argument) {
1430 // Because String.equals is an instance call, the receiver is
1431 // a null check if we don't know it's null. The argument however, will
1432 // be the actual object. So we cannot end up in a situation where both
1433 // are equal but could be null.
1434 DCHECK(CanEnsureNotNullAt(argument, instruction));
1435 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1436 instruction->GetBlock()->RemoveInstruction(instruction);
1437 } else {
1438 StringEqualsOptimizations optimizations(instruction);
1439 if (CanEnsureNotNullAt(argument, instruction)) {
1440 optimizations.SetArgumentNotNull();
1441 }
1442 ScopedObjectAccess soa(Thread::Current());
1443 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1444 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1445 optimizations.SetArgumentIsString();
1446 }
1447 }
1448}
1449
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001450void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1451 DCHECK(invoke->IsInvokeStaticOrDirect());
1452 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001453 HInstruction* value = invoke->InputAt(0);
1454 HInstruction* distance = invoke->InputAt(1);
1455 // Replace the invoke with an HRor.
1456 if (is_left) {
1457 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1458 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1459 }
1460 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1461 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1462 // Remove ClinitCheck and LoadClass, if possible.
1463 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1464 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1465 clinit->GetBlock()->RemoveInstruction(clinit);
1466 HInstruction* ldclass = clinit->InputAt(0);
1467 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1468 ldclass->GetBlock()->RemoveInstruction(ldclass);
1469 }
1470 }
1471}
1472
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001473static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1474 if (potential_length->IsArrayLength()) {
1475 return potential_length->InputAt(0) == potential_array;
1476 }
1477
1478 if (potential_array->IsNewArray()) {
1479 return potential_array->InputAt(0) == potential_length;
1480 }
1481
1482 return false;
1483}
1484
1485void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1486 HInstruction* source = instruction->InputAt(0);
1487 HInstruction* destination = instruction->InputAt(2);
1488 HInstruction* count = instruction->InputAt(4);
1489 SystemArrayCopyOptimizations optimizations(instruction);
1490 if (CanEnsureNotNullAt(source, instruction)) {
1491 optimizations.SetSourceIsNotNull();
1492 }
1493 if (CanEnsureNotNullAt(destination, instruction)) {
1494 optimizations.SetDestinationIsNotNull();
1495 }
1496 if (destination == source) {
1497 optimizations.SetDestinationIsSource();
1498 }
1499
1500 if (IsArrayLengthOf(count, source)) {
1501 optimizations.SetCountIsSourceLength();
1502 }
1503
1504 if (IsArrayLengthOf(count, destination)) {
1505 optimizations.SetCountIsDestinationLength();
1506 }
1507
1508 {
1509 ScopedObjectAccess soa(Thread::Current());
1510 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1511 if (destination_rti.IsValid()) {
1512 if (destination_rti.IsObjectArray()) {
1513 if (destination_rti.IsExact()) {
1514 optimizations.SetDoesNotNeedTypeCheck();
1515 }
1516 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001517 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001518 if (destination_rti.IsPrimitiveArrayClass()) {
1519 optimizations.SetDestinationIsPrimitiveArray();
1520 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1521 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001522 }
1523 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001524 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1525 if (source_rti.IsValid()) {
1526 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1527 optimizations.SetDoesNotNeedTypeCheck();
1528 }
1529 if (source_rti.IsPrimitiveArrayClass()) {
1530 optimizations.SetSourceIsPrimitiveArray();
1531 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1532 optimizations.SetSourceIsNonPrimitiveArray();
1533 }
1534 }
1535 }
1536}
1537
Aart Bika19616e2016-02-01 18:57:58 -08001538void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1539 DCHECK(invoke->IsInvokeStaticOrDirect());
1540 uint32_t dex_pc = invoke->GetDexPc();
1541 HInstruction* left = invoke->InputAt(0);
1542 HInstruction* right;
1543 Primitive::Type type = left->GetType();
1544 if (!is_signum) {
1545 right = invoke->InputAt(1);
1546 } else if (type == Primitive::kPrimLong) {
1547 right = GetGraph()->GetLongConstant(0);
1548 } else {
1549 right = GetGraph()->GetIntConstant(0);
1550 }
1551 HCompare* compare = new (GetGraph()->GetArena())
1552 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1553 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1554}
1555
Aart Bik75a38b22016-02-17 10:41:50 -08001556void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1557 DCHECK(invoke->IsInvokeStaticOrDirect());
1558 uint32_t dex_pc = invoke->GetDexPc();
1559 // IsNaN(x) is the same as x != x.
1560 HInstruction* x = invoke->InputAt(0);
1561 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001562 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001563 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1564}
1565
Aart Bik2a6aad92016-02-25 11:32:32 -08001566void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1567 DCHECK(invoke->IsInvokeStaticOrDirect());
1568 uint32_t dex_pc = invoke->GetDexPc();
1569 HInstruction* x = invoke->InputAt(0);
1570 Primitive::Type type = x->GetType();
1571 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1572 HInstruction* nan;
1573 if (type == Primitive::kPrimDouble) {
1574 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1575 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1576 kNeedsEnvironmentOrCache,
1577 kNoSideEffects,
1578 kNoThrow);
1579 } else {
1580 DCHECK_EQ(type, Primitive::kPrimFloat);
1581 nan = GetGraph()->GetIntConstant(0x7fc00000);
1582 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1583 kNeedsEnvironmentOrCache,
1584 kNoSideEffects,
1585 kNoThrow);
1586 }
1587 // Test IsNaN(x), which is the same as x != x.
1588 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1589 condition->SetBias(ComparisonBias::kLtBias);
1590 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1591 // Select between the two.
1592 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1593 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1594 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1595}
1596
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001597void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001598 switch (instruction->GetIntrinsic()) {
1599 case Intrinsics::kStringEquals:
1600 SimplifyStringEquals(instruction);
1601 break;
1602 case Intrinsics::kSystemArrayCopy:
1603 SimplifySystemArrayCopy(instruction);
1604 break;
1605 case Intrinsics::kIntegerRotateRight:
1606 case Intrinsics::kLongRotateRight:
1607 SimplifyRotate(instruction, false);
1608 break;
1609 case Intrinsics::kIntegerRotateLeft:
1610 case Intrinsics::kLongRotateLeft:
1611 SimplifyRotate(instruction, true);
1612 break;
1613 case Intrinsics::kIntegerCompare:
1614 case Intrinsics::kLongCompare:
1615 SimplifyCompare(instruction, /* is_signum */ false);
1616 break;
1617 case Intrinsics::kIntegerSignum:
1618 case Intrinsics::kLongSignum:
1619 SimplifyCompare(instruction, /* is_signum */ true);
1620 break;
1621 case Intrinsics::kFloatIsNaN:
1622 case Intrinsics::kDoubleIsNaN:
1623 SimplifyIsNaN(instruction);
1624 break;
1625 case Intrinsics::kFloatFloatToIntBits:
1626 case Intrinsics::kDoubleDoubleToLongBits:
1627 SimplifyFP2Int(instruction);
1628 break;
1629 default:
1630 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001631 }
1632}
1633
Aart Bikbb245d12015-10-19 11:05:03 -07001634void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1635 HInstruction* cond = deoptimize->InputAt(0);
1636 if (cond->IsConstant()) {
1637 if (cond->AsIntConstant()->IsZero()) {
1638 // Never deopt: instruction can be removed.
1639 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1640 } else {
1641 // Always deopt.
1642 }
1643 }
1644}
1645
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001646} // namespace art