blob: 13d3f752c3a60488d0f8a3a4df7304ddb54a3c5c [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);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010096
Calin Juravleacf735c2015-02-12 15:25:22 +000097 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010098 bool simplification_occurred_ = false;
99 int simplifications_at_current_position_ = 0;
100 // We ensure we do not loop infinitely. The value is a finger in the air guess
101 // that should allow enough simplification.
102 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000103};
104
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100105void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000106 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100107 visitor.Run();
108}
109
110void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100111 // Iterate in reverse post order to open up more simplifications to users
112 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100113 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
114 // The simplification of an instruction to another instruction may yield
115 // possibilities for other simplifications. So although we perform a reverse
116 // post order visit, we sometimes need to revisit an instruction index.
117 simplification_occurred_ = false;
118 VisitBasicBlock(it.Current());
119 if (simplification_occurred_ &&
120 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
121 // New simplifications may be applicable to the instruction at the
122 // current index, so don't advance the iterator.
123 continue;
124 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100125 simplifications_at_current_position_ = 0;
126 it.Advance();
127 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100128}
129
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000130namespace {
131
132bool AreAllBitsSet(HConstant* constant) {
133 return Int64FromConstant(constant) == -1;
134}
135
136} // namespace
137
Alexandre Rames188d4312015-04-09 18:30:21 +0100138// Returns true if the code was simplified to use only one negation operation
139// after the binary operation instead of one on each of the inputs.
140bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
141 DCHECK(binop->IsAdd() || binop->IsSub());
142 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
143 HNeg* left_neg = binop->GetLeft()->AsNeg();
144 HNeg* right_neg = binop->GetRight()->AsNeg();
145 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
146 !right_neg->HasOnlyOneNonEnvironmentUse()) {
147 return false;
148 }
149 // Replace code looking like
150 // NEG tmp1, a
151 // NEG tmp2, b
152 // ADD dst, tmp1, tmp2
153 // with
154 // ADD tmp, a, b
155 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600156 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
157 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
158 // while the later yields `-0.0`.
159 if (!Primitive::IsIntegralType(binop->GetType())) {
160 return false;
161 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100162 binop->ReplaceInput(left_neg->GetInput(), 0);
163 binop->ReplaceInput(right_neg->GetInput(), 1);
164 left_neg->GetBlock()->RemoveInstruction(left_neg);
165 right_neg->GetBlock()->RemoveInstruction(right_neg);
166 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
167 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
168 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
169 RecordSimplification();
170 return true;
171}
172
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000173bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
174 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
175 Primitive::Type type = op->GetType();
176 HInstruction* left = op->GetLeft();
177 HInstruction* right = op->GetRight();
178
179 // We can apply De Morgan's laws if both inputs are Not's and are only used
180 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000181 if (((left->IsNot() && right->IsNot()) ||
182 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000183 left->HasOnlyOneNonEnvironmentUse() &&
184 right->HasOnlyOneNonEnvironmentUse()) {
185 // Replace code looking like
186 // NOT nota, a
187 // NOT notb, b
188 // AND dst, nota, notb (respectively OR)
189 // with
190 // OR or, a, b (respectively AND)
191 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000192 HInstruction* src_left = left->InputAt(0);
193 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000194 uint32_t dex_pc = op->GetDexPc();
195
196 // Remove the negations on the inputs.
197 left->ReplaceWith(src_left);
198 right->ReplaceWith(src_right);
199 left->GetBlock()->RemoveInstruction(left);
200 right->GetBlock()->RemoveInstruction(right);
201
202 // Replace the `HAnd` or `HOr`.
203 HBinaryOperation* hbin;
204 if (op->IsAnd()) {
205 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
206 } else {
207 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
208 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000209 HInstruction* hnot;
210 if (left->IsBooleanNot()) {
211 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
212 } else {
213 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
214 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000215
216 op->GetBlock()->InsertInstructionBefore(hbin, op);
217 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
218
219 RecordSimplification();
220 return true;
221 }
222
223 return false;
224}
225
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000226void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
227 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
228 HConstant* input_cst = instruction->GetConstantRight();
229 HInstruction* input_other = instruction->GetLeastConstantLeft();
230
Mark Mendellba56d062015-05-05 21:34:03 -0400231 if (input_cst != nullptr) {
232 if (input_cst->IsZero()) {
233 // Replace code looking like
234 // SHL dst, src, 0
235 // with
236 // src
237 instruction->ReplaceWith(input_other);
238 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400239 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000240 }
241}
242
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000243static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
244 return (sub->GetRight() == other &&
245 sub->GetLeft()->IsConstant() &&
246 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
247}
248
249bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
250 HUShr* ushr,
251 HShl* shl) {
252 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
253 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
254 ushr->GetLeft(),
255 ushr->GetRight());
256 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
257 if (!ushr->HasUses()) {
258 ushr->GetBlock()->RemoveInstruction(ushr);
259 }
260 if (!ushr->GetRight()->HasUses()) {
261 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
262 }
263 if (!shl->HasUses()) {
264 shl->GetBlock()->RemoveInstruction(shl);
265 }
266 if (!shl->GetRight()->HasUses()) {
267 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
268 }
269 return true;
270}
271
272// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
273bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000274 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
275 HInstruction* left = op->GetLeft();
276 HInstruction* right = op->GetRight();
277 // If we have an UShr and a Shl (in either order).
278 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
279 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
280 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
281 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
282 if (ushr->GetType() == shl->GetType() &&
283 ushr->GetLeft() == shl->GetLeft()) {
284 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
285 // Shift distances are both constant, try replacing with Ror if they
286 // add up to the register size.
287 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
288 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
289 // Shift distances are potentially of the form x and (reg_size - x).
290 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
291 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
292 // Shift distances are potentially of the form d and -d.
293 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
294 }
295 }
296 }
297 return false;
298}
299
300// Try replacing code looking like (x >>> #rdist OP x << #ldist):
301// UShr dst, x, #rdist
302// Shl tmp, x, #ldist
303// OP dst, dst, tmp
304// or like (x >>> #rdist OP x << #-ldist):
305// UShr dst, x, #rdist
306// Shl tmp, x, #-ldist
307// OP dst, dst, tmp
308// with
309// Ror dst, x, #rdist
310bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
311 HUShr* ushr,
312 HShl* shl) {
313 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
314 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
315 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
316 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
317 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
318 ReplaceRotateWithRor(op, ushr, shl);
319 return true;
320 }
321 return false;
322}
323
324// Replace code looking like (x >>> -d OP x << d):
325// Neg neg, d
326// UShr dst, x, neg
327// Shl tmp, x, d
328// OP dst, dst, tmp
329// with
330// Neg neg, d
331// Ror dst, x, neg
332// *** OR ***
333// Replace code looking like (x >>> d OP x << -d):
334// UShr dst, x, d
335// Neg neg, d
336// Shl tmp, x, neg
337// OP dst, dst, tmp
338// with
339// Ror dst, x, d
340bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
341 HUShr* ushr,
342 HShl* shl) {
343 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
344 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
345 bool neg_is_left = shl->GetRight()->IsNeg();
346 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
347 // And the shift distance being negated is the distance being shifted the other way.
348 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
349 ReplaceRotateWithRor(op, ushr, shl);
350 }
351 return false;
352}
353
354// Try replacing code looking like (x >>> d OP x << (#bits - d)):
355// UShr dst, x, d
356// Sub ld, #bits, d
357// Shl tmp, x, ld
358// OP dst, dst, tmp
359// with
360// Ror dst, x, d
361// *** OR ***
362// Replace code looking like (x >>> (#bits - d) OP x << d):
363// Sub rd, #bits, d
364// UShr dst, x, rd
365// Shl tmp, x, d
366// OP dst, dst, tmp
367// with
368// Neg neg, d
369// Ror dst, x, neg
370bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
371 HUShr* ushr,
372 HShl* shl) {
373 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
374 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
375 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
376 HInstruction* shl_shift = shl->GetRight();
377 HInstruction* ushr_shift = ushr->GetRight();
378 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
379 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
380 return ReplaceRotateWithRor(op, ushr, shl);
381 }
382 return false;
383}
384
Calin Juravle10e244f2015-01-26 18:54:32 +0000385void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
386 HInstruction* obj = null_check->InputAt(0);
387 if (!obj->CanBeNull()) {
388 null_check->ReplaceWith(obj);
389 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000390 if (stats_ != nullptr) {
391 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
392 }
393 }
394}
395
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100396bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
397 if (!input->CanBeNull()) {
398 return true;
399 }
400
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100401 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
402 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100403 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100404 return true;
405 }
406 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100407
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100408 return false;
409}
410
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100411// Returns whether doing a type test between the class of `object` against `klass` has
412// a statically known outcome. The result of the test is stored in `outcome`.
413static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000414 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
415 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
416 ScopedObjectAccess soa(Thread::Current());
417 if (!obj_rti.IsValid()) {
418 // We run the simplifier before the reference type propagation so type info might not be
419 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100420 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000421 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100422
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100423 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100424 if (!class_rti.IsValid()) {
425 // Happens when the loaded class is unresolved.
426 return false;
427 }
428 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000429 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100430 *outcome = true;
431 return true;
432 } else if (obj_rti.IsExact()) {
433 // The test failed at compile time so will also fail at runtime.
434 *outcome = false;
435 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100436 } else if (!class_rti.IsInterface()
437 && !obj_rti.IsInterface()
438 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100439 // Different type hierarchy. The test will fail.
440 *outcome = false;
441 return true;
442 }
443 return false;
444}
445
446void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
447 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100448 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
449 if (load_class->NeedsAccessCheck()) {
450 // If we need to perform an access check we cannot remove the instruction.
451 return;
452 }
453
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100454 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100455 check_cast->ClearMustDoNullCheck();
456 }
457
458 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000459 check_cast->GetBlock()->RemoveInstruction(check_cast);
460 if (stats_ != nullptr) {
461 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
462 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100463 return;
464 }
465
466 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700467 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100468 if (outcome) {
469 check_cast->GetBlock()->RemoveInstruction(check_cast);
470 if (stats_ != nullptr) {
471 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
472 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700473 if (!load_class->HasUses()) {
474 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
475 // However, here we know that it cannot because the checkcast was successfull, hence
476 // the class was already loaded.
477 load_class->GetBlock()->RemoveInstruction(load_class);
478 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100479 } else {
480 // Don't do anything for exceptional cases for now. Ideally we should remove
481 // all instructions and blocks this instruction dominates.
482 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000483 }
484}
485
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100486void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100487 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100488 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
489 if (load_class->NeedsAccessCheck()) {
490 // If we need to perform an access check we cannot remove the instruction.
491 return;
492 }
493
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100494 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100495 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100496 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100497 instruction->ClearMustDoNullCheck();
498 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100499
500 HGraph* graph = GetGraph();
501 if (object->IsNullConstant()) {
502 instruction->ReplaceWith(graph->GetIntConstant(0));
503 instruction->GetBlock()->RemoveInstruction(instruction);
504 RecordSimplification();
505 return;
506 }
507
508 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700509 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100510 if (outcome && can_be_null) {
511 // Type test will succeed, we just need a null test.
512 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
513 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
514 instruction->ReplaceWith(test);
515 } else {
516 // We've statically determined the result of the instanceof.
517 instruction->ReplaceWith(graph->GetIntConstant(outcome));
518 }
519 RecordSimplification();
520 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700521 if (outcome && !load_class->HasUses()) {
522 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
523 // However, here we know that it cannot because the instanceof check was successfull, hence
524 // the class was already loaded.
525 load_class->GetBlock()->RemoveInstruction(load_class);
526 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100527 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100528}
529
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100530void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
531 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100532 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100533 instruction->ClearValueCanBeNull();
534 }
535}
536
537void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
538 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100539 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100540 instruction->ClearValueCanBeNull();
541 }
542}
543
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000544void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100545 HBasicBlock* block = check->GetBlock();
546 // Currently always keep the suspend check at entry.
547 if (block->IsEntryBlock()) return;
548
549 // Currently always keep suspend checks at loop entry.
550 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
551 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
552 return;
553 }
554
555 // Remove the suspend check that was added at build time for the baseline
556 // compiler.
557 block->RemoveInstruction(check);
558}
559
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000560void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100561 HInstruction* input_const = equal->GetConstantRight();
562 if (input_const != nullptr) {
563 HInstruction* input_value = equal->GetLeastConstantLeft();
564 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
565 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100566 // We are comparing the boolean to a constant which is of type int and can
567 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100568 if (input_const->AsIntConstant()->IsOne()) {
569 // Replace (bool_value == true) with bool_value
570 equal->ReplaceWith(input_value);
571 block->RemoveInstruction(equal);
572 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100573 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500574 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
575 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100576 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100577 } else {
578 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
579 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
580 block->RemoveInstruction(equal);
581 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100582 }
Mark Mendellc4701932015-04-10 13:18:51 -0400583 } else {
584 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100585 }
Mark Mendellc4701932015-04-10 13:18:51 -0400586 } else {
587 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100588 }
589}
590
David Brazdil0d13fee2015-04-17 14:52:19 +0100591void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
592 HInstruction* input_const = not_equal->GetConstantRight();
593 if (input_const != nullptr) {
594 HInstruction* input_value = not_equal->GetLeastConstantLeft();
595 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
596 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100597 // We are comparing the boolean to a constant which is of type int and can
598 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100599 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500600 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
601 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100602 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100603 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100604 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100605 not_equal->ReplaceWith(input_value);
606 block->RemoveInstruction(not_equal);
607 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100608 } else {
609 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
610 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
611 block->RemoveInstruction(not_equal);
612 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100613 }
Mark Mendellc4701932015-04-10 13:18:51 -0400614 } else {
615 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100616 }
Mark Mendellc4701932015-04-10 13:18:51 -0400617 } else {
618 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100619 }
620}
621
622void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000623 HInstruction* input = bool_not->InputAt(0);
624 HInstruction* replace_with = nullptr;
625
626 if (input->IsIntConstant()) {
627 // Replace !(true/false) with false/true.
628 if (input->AsIntConstant()->IsOne()) {
629 replace_with = GetGraph()->GetIntConstant(0);
630 } else {
631 DCHECK(input->AsIntConstant()->IsZero());
632 replace_with = GetGraph()->GetIntConstant(1);
633 }
634 } else if (input->IsBooleanNot()) {
635 // Replace (!(!bool_value)) with bool_value.
636 replace_with = input->InputAt(0);
637 } else if (input->IsCondition() &&
638 // Don't change FP compares. The definition of compares involving
639 // NaNs forces the compares to be done as written by the user.
640 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
641 // Replace condition with its opposite.
642 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
643 }
644
645 if (replace_with != nullptr) {
646 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100647 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000648 RecordSimplification();
649 }
650}
651
652void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
653 HInstruction* replace_with = nullptr;
654 HInstruction* condition = select->GetCondition();
655 HInstruction* true_value = select->GetTrueValue();
656 HInstruction* false_value = select->GetFalseValue();
657
658 if (condition->IsBooleanNot()) {
659 // Change ((!cond) ? x : y) to (cond ? y : x).
660 condition = condition->InputAt(0);
661 std::swap(true_value, false_value);
662 select->ReplaceInput(false_value, 0);
663 select->ReplaceInput(true_value, 1);
664 select->ReplaceInput(condition, 2);
665 RecordSimplification();
666 }
667
668 if (true_value == false_value) {
669 // Replace (cond ? x : x) with (x).
670 replace_with = true_value;
671 } else if (condition->IsIntConstant()) {
672 if (condition->AsIntConstant()->IsOne()) {
673 // Replace (true ? x : y) with (x).
674 replace_with = true_value;
675 } else {
676 // Replace (false ? x : y) with (y).
677 DCHECK(condition->AsIntConstant()->IsZero());
678 replace_with = false_value;
679 }
680 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
681 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
682 // Replace (cond ? true : false) with (cond).
683 replace_with = condition;
684 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
685 // Replace (cond ? false : true) with (!cond).
686 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
687 }
688 }
689
690 if (replace_with != nullptr) {
691 select->ReplaceWith(replace_with);
692 select->GetBlock()->RemoveInstruction(select);
693 RecordSimplification();
694 }
695}
696
697void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
698 HInstruction* condition = instruction->InputAt(0);
699 if (condition->IsBooleanNot()) {
700 // Swap successors if input is negated.
701 instruction->ReplaceInput(condition->InputAt(0), 0);
702 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100703 RecordSimplification();
704 }
705}
706
Mingyao Yang0304e182015-01-30 16:41:29 -0800707void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
708 HInstruction* input = instruction->InputAt(0);
709 // If the array is a NewArray with constant size, replace the array length
710 // with the constant instruction. This helps the bounds check elimination phase.
711 if (input->IsNewArray()) {
712 input = input->InputAt(0);
713 if (input->IsIntConstant()) {
714 instruction->ReplaceWith(input);
715 }
716 }
717}
718
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000719void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000720 HInstruction* value = instruction->GetValue();
721 if (value->GetType() != Primitive::kPrimNot) return;
722
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100723 if (CanEnsureNotNullAt(value, instruction)) {
724 instruction->ClearValueCanBeNull();
725 }
726
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000727 if (value->IsArrayGet()) {
728 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
729 // If the code is just swapping elements in the array, no need for a type check.
730 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100731 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000732 }
733 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100734
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100735 if (value->IsNullConstant()) {
736 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100737 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100738 }
739
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100740 ScopedObjectAccess soa(Thread::Current());
741 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
742 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
743 if (!array_rti.IsValid()) {
744 return;
745 }
746
747 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
748 instruction->ClearNeedsTypeCheck();
749 return;
750 }
751
752 if (array_rti.IsObjectArray()) {
753 if (array_rti.IsExact()) {
754 instruction->ClearNeedsTypeCheck();
755 return;
756 }
757 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100758 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000759}
760
Vladimir Markob52bbde2016-02-12 12:06:05 +0000761static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
762 // Besides conversion to the same type, widening integral conversions are implicit,
763 // excluding conversions to long and the byte->char conversion where we need to
764 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
765 return result_type == input_type ||
766 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
767 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
768 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
769 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
770}
771
772static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
773 // The conversion to a larger type is loss-less with the exception of two cases,
774 // - conversion to char, the only unsigned type, where we may lose some bits, and
775 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
776 // For integral to FP conversions this holds because the FP mantissa is large enough.
777 DCHECK_NE(input_type, result_type);
778 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
779 result_type != Primitive::kPrimChar &&
780 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
781}
782
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000783void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000784 HInstruction* input = instruction->GetInput();
785 Primitive::Type input_type = input->GetType();
786 Primitive::Type result_type = instruction->GetResultType();
787 if (IsTypeConversionImplicit(input_type, result_type)) {
788 // Remove the implicit conversion; this includes conversion to the same type.
789 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000790 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000791 RecordSimplification();
792 return;
793 }
794
795 if (input->IsTypeConversion()) {
796 HTypeConversion* input_conversion = input->AsTypeConversion();
797 HInstruction* original_input = input_conversion->GetInput();
798 Primitive::Type original_type = original_input->GetType();
799
800 // When the first conversion is lossless, a direct conversion from the original type
801 // to the final type yields the same result, even for a lossy second conversion, for
802 // example float->double->int or int->double->float.
803 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
804
805 // For integral conversions, see if the first conversion loses only bits that the second
806 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
807 // conversion yields the same result, for example long->int->short or int->char->short.
808 bool integral_conversions_with_non_widening_second =
809 Primitive::IsIntegralType(input_type) &&
810 Primitive::IsIntegralType(original_type) &&
811 Primitive::IsIntegralType(result_type) &&
812 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
813
814 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
815 // If the merged conversion is implicit, do the simplification unconditionally.
816 if (IsTypeConversionImplicit(original_type, result_type)) {
817 instruction->ReplaceWith(original_input);
818 instruction->GetBlock()->RemoveInstruction(instruction);
819 if (!input_conversion->HasUses()) {
820 // Don't wait for DCE.
821 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
822 }
823 RecordSimplification();
824 return;
825 }
826 // Otherwise simplify only if the first conversion has no other use.
827 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
828 input_conversion->ReplaceWith(original_input);
829 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
830 RecordSimplification();
831 return;
832 }
833 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000834 } else if (input->IsAnd() &&
835 Primitive::IsIntegralType(result_type) &&
836 input->HasOnlyOneNonEnvironmentUse()) {
837 DCHECK(Primitive::IsIntegralType(input_type));
838 HAnd* input_and = input->AsAnd();
839 HConstant* constant = input_and->GetConstantRight();
840 if (constant != nullptr) {
841 int64_t value = Int64FromConstant(constant);
842 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
843 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
844 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
845 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
846 input_and->ReplaceWith(input_and->GetLeastConstantLeft());
847 input_and->GetBlock()->RemoveInstruction(input_and);
848 RecordSimplification();
849 return;
850 }
851 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000852 }
853}
854
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000855void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
856 HConstant* input_cst = instruction->GetConstantRight();
857 HInstruction* input_other = instruction->GetLeastConstantLeft();
858 if ((input_cst != nullptr) && input_cst->IsZero()) {
859 // Replace code looking like
860 // ADD dst, src, 0
861 // with
862 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600863 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
864 // `x` is `-0.0`, the former expression yields `0.0`, while the later
865 // yields `-0.0`.
866 if (Primitive::IsIntegralType(instruction->GetType())) {
867 instruction->ReplaceWith(input_other);
868 instruction->GetBlock()->RemoveInstruction(instruction);
869 return;
870 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100871 }
872
873 HInstruction* left = instruction->GetLeft();
874 HInstruction* right = instruction->GetRight();
875 bool left_is_neg = left->IsNeg();
876 bool right_is_neg = right->IsNeg();
877
878 if (left_is_neg && right_is_neg) {
879 if (TryMoveNegOnInputsAfterBinop(instruction)) {
880 return;
881 }
882 }
883
884 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
885 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
886 // Replace code looking like
887 // NEG tmp, b
888 // ADD dst, a, tmp
889 // with
890 // SUB dst, a, b
891 // We do not perform the optimization if the input negation has environment
892 // uses or multiple non-environment uses as it could lead to worse code. In
893 // particular, we do not want the live range of `b` to be extended if we are
894 // not sure the initial 'NEG' instruction can be removed.
895 HInstruction* other = left_is_neg ? right : left;
896 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
897 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
898 RecordSimplification();
899 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000900 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000901 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000902
903 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000904}
905
906void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
907 HConstant* input_cst = instruction->GetConstantRight();
908 HInstruction* input_other = instruction->GetLeastConstantLeft();
909
Vladimir Marko452c1b62015-09-25 14:44:17 +0100910 if (input_cst != nullptr) {
911 int64_t value = Int64FromConstant(input_cst);
912 if (value == -1) {
913 // Replace code looking like
914 // AND dst, src, 0xFFF...FF
915 // with
916 // src
917 instruction->ReplaceWith(input_other);
918 instruction->GetBlock()->RemoveInstruction(instruction);
919 RecordSimplification();
920 return;
921 }
922 // Eliminate And from UShr+And if the And-mask contains all the bits that
923 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
924 // precisely clears the shifted-in sign bits.
925 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
926 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
927 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
928 size_t num_tail_bits_set = CTZ(value + 1);
929 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
930 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
931 instruction->ReplaceWith(input_other);
932 instruction->GetBlock()->RemoveInstruction(instruction);
933 RecordSimplification();
934 return;
935 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
936 input_other->HasOnlyOneNonEnvironmentUse()) {
937 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
938 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
939 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
940 input_other->InputAt(0),
941 input_other->InputAt(1),
942 input_other->GetDexPc());
943 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
944 input_other->GetBlock()->RemoveInstruction(input_other);
945 RecordSimplification();
946 return;
947 }
948 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000949 }
950
951 // We assume that GVN has run before, so we only perform a pointer comparison.
952 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100953 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000954 if (instruction->GetLeft() == instruction->GetRight()) {
955 // Replace code looking like
956 // AND dst, src, src
957 // with
958 // src
959 instruction->ReplaceWith(instruction->GetLeft());
960 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000961 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000962 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000963
964 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000965}
966
Mark Mendellc4701932015-04-10 13:18:51 -0400967void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
968 VisitCondition(condition);
969}
970
971void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
972 VisitCondition(condition);
973}
974
975void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
976 VisitCondition(condition);
977}
978
979void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
980 VisitCondition(condition);
981}
982
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000983// TODO: unsigned comparisons too?
Aart Bike9f37602015-10-09 11:15:55 -0700984
Mark Mendellc4701932015-04-10 13:18:51 -0400985void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000986 // Try to fold an HCompare into this HCondition.
Mark Mendellc4701932015-04-10 13:18:51 -0400987
Mark Mendellc4701932015-04-10 13:18:51 -0400988 HInstruction* left = condition->GetLeft();
989 HInstruction* right = condition->GetRight();
990 // We can only replace an HCondition which compares a Compare to 0.
991 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
992 // condition with a long, float or double comparison as input.
993 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
994 // Conversion is not possible.
995 return;
996 }
997
998 // Is the Compare only used for this purpose?
999 if (!left->GetUses().HasOnlyOneUse()) {
1000 // Someone else also wants the result of the compare.
1001 return;
1002 }
1003
1004 if (!left->GetEnvUses().IsEmpty()) {
1005 // There is a reference to the compare result in an environment. Do we really need it?
1006 if (GetGraph()->IsDebuggable()) {
1007 return;
1008 }
1009
1010 // We have to ensure that there are no deopt points in the sequence.
1011 if (left->HasAnyEnvironmentUseBefore(condition)) {
1012 return;
1013 }
1014 }
1015
1016 // Clean up any environment uses from the HCompare, if any.
1017 left->RemoveEnvironmentUsers();
1018
1019 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1020 condition->SetBias(left->AsCompare()->GetBias());
1021
1022 // Replace the operands of the HCondition.
1023 condition->ReplaceInput(left->InputAt(0), 0);
1024 condition->ReplaceInput(left->InputAt(1), 1);
1025
1026 // Remove the HCompare.
1027 left->GetBlock()->RemoveInstruction(left);
1028
1029 RecordSimplification();
1030}
1031
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001032void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1033 HConstant* input_cst = instruction->GetConstantRight();
1034 HInstruction* input_other = instruction->GetLeastConstantLeft();
1035 Primitive::Type type = instruction->GetType();
1036
1037 if ((input_cst != nullptr) && input_cst->IsOne()) {
1038 // Replace code looking like
1039 // DIV dst, src, 1
1040 // with
1041 // src
1042 instruction->ReplaceWith(input_other);
1043 instruction->GetBlock()->RemoveInstruction(instruction);
1044 return;
1045 }
1046
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001047 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001048 // Replace code looking like
1049 // DIV dst, src, -1
1050 // with
1051 // NEG dst, src
1052 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001053 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001054 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001055 return;
1056 }
1057
1058 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1059 // Try replacing code looking like
1060 // DIV dst, src, constant
1061 // with
1062 // MUL dst, src, 1 / constant
1063 HConstant* reciprocal = nullptr;
1064 if (type == Primitive::Primitive::kPrimDouble) {
1065 double value = input_cst->AsDoubleConstant()->GetValue();
1066 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1067 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1068 }
1069 } else {
1070 DCHECK_EQ(type, Primitive::kPrimFloat);
1071 float value = input_cst->AsFloatConstant()->GetValue();
1072 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1073 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1074 }
1075 }
1076
1077 if (reciprocal != nullptr) {
1078 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1079 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1080 RecordSimplification();
1081 return;
1082 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001083 }
1084}
1085
1086void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1087 HConstant* input_cst = instruction->GetConstantRight();
1088 HInstruction* input_other = instruction->GetLeastConstantLeft();
1089 Primitive::Type type = instruction->GetType();
1090 HBasicBlock* block = instruction->GetBlock();
1091 ArenaAllocator* allocator = GetGraph()->GetArena();
1092
1093 if (input_cst == nullptr) {
1094 return;
1095 }
1096
1097 if (input_cst->IsOne()) {
1098 // Replace code looking like
1099 // MUL dst, src, 1
1100 // with
1101 // src
1102 instruction->ReplaceWith(input_other);
1103 instruction->GetBlock()->RemoveInstruction(instruction);
1104 return;
1105 }
1106
1107 if (input_cst->IsMinusOne() &&
1108 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1109 // Replace code looking like
1110 // MUL dst, src, -1
1111 // with
1112 // NEG dst, src
1113 HNeg* neg = new (allocator) HNeg(type, input_other);
1114 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001115 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001116 return;
1117 }
1118
1119 if (Primitive::IsFloatingPointType(type) &&
1120 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1121 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1122 // Replace code looking like
1123 // FP_MUL dst, src, 2.0
1124 // with
1125 // FP_ADD dst, src, src
1126 // The 'int' and 'long' cases are handled below.
1127 block->ReplaceAndRemoveInstructionWith(instruction,
1128 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001129 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001130 return;
1131 }
1132
1133 if (Primitive::IsIntOrLongType(type)) {
1134 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001135 // Even though constant propagation also takes care of the zero case, other
1136 // optimizations can lead to having a zero multiplication.
1137 if (factor == 0) {
1138 // Replace code looking like
1139 // MUL dst, src, 0
1140 // with
1141 // 0
1142 instruction->ReplaceWith(input_cst);
1143 instruction->GetBlock()->RemoveInstruction(instruction);
1144 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001145 // Replace code looking like
1146 // MUL dst, src, pow_of_2
1147 // with
1148 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001149 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001150 HShl* shl = new(allocator) HShl(type, input_other, shift);
1151 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001152 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001153 } else if (IsPowerOfTwo(factor - 1)) {
1154 // Transform code looking like
1155 // MUL dst, src, (2^n + 1)
1156 // into
1157 // SHL tmp, src, n
1158 // ADD dst, src, tmp
1159 HShl* shl = new (allocator) HShl(type,
1160 input_other,
1161 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1162 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1163
1164 block->InsertInstructionBefore(shl, instruction);
1165 block->ReplaceAndRemoveInstructionWith(instruction, add);
1166 RecordSimplification();
1167 } else if (IsPowerOfTwo(factor + 1)) {
1168 // Transform code looking like
1169 // MUL dst, src, (2^n - 1)
1170 // into
1171 // SHL tmp, src, n
1172 // SUB dst, tmp, src
1173 HShl* shl = new (allocator) HShl(type,
1174 input_other,
1175 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1176 HSub* sub = new (allocator) HSub(type, shl, input_other);
1177
1178 block->InsertInstructionBefore(shl, instruction);
1179 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1180 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001181 }
1182 }
1183}
1184
Alexandre Rames188d4312015-04-09 18:30:21 +01001185void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1186 HInstruction* input = instruction->GetInput();
1187 if (input->IsNeg()) {
1188 // Replace code looking like
1189 // NEG tmp, src
1190 // NEG dst, tmp
1191 // with
1192 // src
1193 HNeg* previous_neg = input->AsNeg();
1194 instruction->ReplaceWith(previous_neg->GetInput());
1195 instruction->GetBlock()->RemoveInstruction(instruction);
1196 // We perform the optimization even if the input negation has environment
1197 // uses since it allows removing the current instruction. But we only delete
1198 // the input negation only if it is does not have any uses left.
1199 if (!previous_neg->HasUses()) {
1200 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1201 }
1202 RecordSimplification();
1203 return;
1204 }
1205
Serguei Katkov339dfc22015-04-20 12:29:32 +06001206 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1207 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001208 // Replace code looking like
1209 // SUB tmp, a, b
1210 // NEG dst, tmp
1211 // with
1212 // SUB dst, b, a
1213 // We do not perform the optimization if the input subtraction has
1214 // environment uses or multiple non-environment uses as it could lead to
1215 // worse code. In particular, we do not want the live ranges of `a` and `b`
1216 // to be extended if we are not sure the initial 'SUB' instruction can be
1217 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001218 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001219 HSub* sub = input->AsSub();
1220 HSub* new_sub =
1221 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1222 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1223 if (!sub->HasUses()) {
1224 sub->GetBlock()->RemoveInstruction(sub);
1225 }
1226 RecordSimplification();
1227 }
1228}
1229
1230void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1231 HInstruction* input = instruction->GetInput();
1232 if (input->IsNot()) {
1233 // Replace code looking like
1234 // NOT tmp, src
1235 // NOT dst, tmp
1236 // with
1237 // src
1238 // We perform the optimization even if the input negation has environment
1239 // uses since it allows removing the current instruction. But we only delete
1240 // the input negation only if it is does not have any uses left.
1241 HNot* previous_not = input->AsNot();
1242 instruction->ReplaceWith(previous_not->GetInput());
1243 instruction->GetBlock()->RemoveInstruction(instruction);
1244 if (!previous_not->HasUses()) {
1245 previous_not->GetBlock()->RemoveInstruction(previous_not);
1246 }
1247 RecordSimplification();
1248 }
1249}
1250
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001251void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1252 HConstant* input_cst = instruction->GetConstantRight();
1253 HInstruction* input_other = instruction->GetLeastConstantLeft();
1254
1255 if ((input_cst != nullptr) && input_cst->IsZero()) {
1256 // Replace code looking like
1257 // OR dst, src, 0
1258 // with
1259 // src
1260 instruction->ReplaceWith(input_other);
1261 instruction->GetBlock()->RemoveInstruction(instruction);
1262 return;
1263 }
1264
1265 // We assume that GVN has run before, so we only perform a pointer comparison.
1266 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001267 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001268 if (instruction->GetLeft() == instruction->GetRight()) {
1269 // Replace code looking like
1270 // OR dst, src, src
1271 // with
1272 // src
1273 instruction->ReplaceWith(instruction->GetLeft());
1274 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001275 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001276 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001277
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001278 if (TryDeMorganNegationFactoring(instruction)) return;
1279
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001280 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001281}
1282
1283void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1284 VisitShift(instruction);
1285}
1286
1287void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1288 VisitShift(instruction);
1289}
1290
1291void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1292 HConstant* input_cst = instruction->GetConstantRight();
1293 HInstruction* input_other = instruction->GetLeastConstantLeft();
1294
Serguei Katkov115b53f2015-08-05 17:03:30 +06001295 Primitive::Type type = instruction->GetType();
1296 if (Primitive::IsFloatingPointType(type)) {
1297 return;
1298 }
1299
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001300 if ((input_cst != nullptr) && input_cst->IsZero()) {
1301 // Replace code looking like
1302 // SUB dst, src, 0
1303 // with
1304 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001305 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1306 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1307 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001308 instruction->ReplaceWith(input_other);
1309 instruction->GetBlock()->RemoveInstruction(instruction);
1310 return;
1311 }
1312
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001313 HBasicBlock* block = instruction->GetBlock();
1314 ArenaAllocator* allocator = GetGraph()->GetArena();
1315
Alexandre Rames188d4312015-04-09 18:30:21 +01001316 HInstruction* left = instruction->GetLeft();
1317 HInstruction* right = instruction->GetRight();
1318 if (left->IsConstant()) {
1319 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001320 // Replace code looking like
1321 // SUB dst, 0, src
1322 // with
1323 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001324 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001325 // `x` is `0.0`, the former expression yields `0.0`, while the later
1326 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001327 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001328 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001329 RecordSimplification();
1330 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001331 }
1332 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001333
1334 if (left->IsNeg() && right->IsNeg()) {
1335 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1336 return;
1337 }
1338 }
1339
1340 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1341 // Replace code looking like
1342 // NEG tmp, b
1343 // SUB dst, a, tmp
1344 // with
1345 // ADD dst, a, b
1346 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1347 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1348 RecordSimplification();
1349 right->GetBlock()->RemoveInstruction(right);
1350 return;
1351 }
1352
1353 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1354 // Replace code looking like
1355 // NEG tmp, a
1356 // SUB dst, tmp, b
1357 // with
1358 // ADD tmp, a, b
1359 // NEG dst, tmp
1360 // The second version is not intrinsically better, but enables more
1361 // transformations.
1362 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1363 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1364 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1365 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1366 instruction->ReplaceWith(neg);
1367 instruction->GetBlock()->RemoveInstruction(instruction);
1368 RecordSimplification();
1369 left->GetBlock()->RemoveInstruction(left);
1370 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001371}
1372
1373void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1374 VisitShift(instruction);
1375}
1376
1377void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1378 HConstant* input_cst = instruction->GetConstantRight();
1379 HInstruction* input_other = instruction->GetLeastConstantLeft();
1380
1381 if ((input_cst != nullptr) && input_cst->IsZero()) {
1382 // Replace code looking like
1383 // XOR dst, src, 0
1384 // with
1385 // src
1386 instruction->ReplaceWith(input_other);
1387 instruction->GetBlock()->RemoveInstruction(instruction);
1388 return;
1389 }
1390
1391 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1392 // Replace code looking like
1393 // XOR dst, src, 0xFFF...FF
1394 // with
1395 // NOT dst, src
1396 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1397 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001398 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001399 return;
1400 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001401
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001402 HInstruction* left = instruction->GetLeft();
1403 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001404 if (((left->IsNot() && right->IsNot()) ||
1405 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001406 left->HasOnlyOneNonEnvironmentUse() &&
1407 right->HasOnlyOneNonEnvironmentUse()) {
1408 // Replace code looking like
1409 // NOT nota, a
1410 // NOT notb, b
1411 // XOR dst, nota, notb
1412 // with
1413 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001414 instruction->ReplaceInput(left->InputAt(0), 0);
1415 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001416 left->GetBlock()->RemoveInstruction(left);
1417 right->GetBlock()->RemoveInstruction(right);
1418 RecordSimplification();
1419 return;
1420 }
1421
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001422 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001423}
1424
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001425void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1426 HInstruction* argument = instruction->InputAt(1);
1427 HInstruction* receiver = instruction->InputAt(0);
1428 if (receiver == argument) {
1429 // Because String.equals is an instance call, the receiver is
1430 // a null check if we don't know it's null. The argument however, will
1431 // be the actual object. So we cannot end up in a situation where both
1432 // are equal but could be null.
1433 DCHECK(CanEnsureNotNullAt(argument, instruction));
1434 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1435 instruction->GetBlock()->RemoveInstruction(instruction);
1436 } else {
1437 StringEqualsOptimizations optimizations(instruction);
1438 if (CanEnsureNotNullAt(argument, instruction)) {
1439 optimizations.SetArgumentNotNull();
1440 }
1441 ScopedObjectAccess soa(Thread::Current());
1442 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1443 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1444 optimizations.SetArgumentIsString();
1445 }
1446 }
1447}
1448
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001449void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1450 DCHECK(invoke->IsInvokeStaticOrDirect());
1451 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001452 HInstruction* value = invoke->InputAt(0);
1453 HInstruction* distance = invoke->InputAt(1);
1454 // Replace the invoke with an HRor.
1455 if (is_left) {
1456 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1457 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1458 }
1459 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1460 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1461 // Remove ClinitCheck and LoadClass, if possible.
1462 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1463 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1464 clinit->GetBlock()->RemoveInstruction(clinit);
1465 HInstruction* ldclass = clinit->InputAt(0);
1466 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1467 ldclass->GetBlock()->RemoveInstruction(ldclass);
1468 }
1469 }
1470}
1471
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001472static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1473 if (potential_length->IsArrayLength()) {
1474 return potential_length->InputAt(0) == potential_array;
1475 }
1476
1477 if (potential_array->IsNewArray()) {
1478 return potential_array->InputAt(0) == potential_length;
1479 }
1480
1481 return false;
1482}
1483
1484void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1485 HInstruction* source = instruction->InputAt(0);
1486 HInstruction* destination = instruction->InputAt(2);
1487 HInstruction* count = instruction->InputAt(4);
1488 SystemArrayCopyOptimizations optimizations(instruction);
1489 if (CanEnsureNotNullAt(source, instruction)) {
1490 optimizations.SetSourceIsNotNull();
1491 }
1492 if (CanEnsureNotNullAt(destination, instruction)) {
1493 optimizations.SetDestinationIsNotNull();
1494 }
1495 if (destination == source) {
1496 optimizations.SetDestinationIsSource();
1497 }
1498
1499 if (IsArrayLengthOf(count, source)) {
1500 optimizations.SetCountIsSourceLength();
1501 }
1502
1503 if (IsArrayLengthOf(count, destination)) {
1504 optimizations.SetCountIsDestinationLength();
1505 }
1506
1507 {
1508 ScopedObjectAccess soa(Thread::Current());
1509 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1510 if (destination_rti.IsValid()) {
1511 if (destination_rti.IsObjectArray()) {
1512 if (destination_rti.IsExact()) {
1513 optimizations.SetDoesNotNeedTypeCheck();
1514 }
1515 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001516 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001517 if (destination_rti.IsPrimitiveArrayClass()) {
1518 optimizations.SetDestinationIsPrimitiveArray();
1519 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1520 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001521 }
1522 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001523 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1524 if (source_rti.IsValid()) {
1525 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1526 optimizations.SetDoesNotNeedTypeCheck();
1527 }
1528 if (source_rti.IsPrimitiveArrayClass()) {
1529 optimizations.SetSourceIsPrimitiveArray();
1530 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1531 optimizations.SetSourceIsNonPrimitiveArray();
1532 }
1533 }
1534 }
1535}
1536
Aart Bika19616e2016-02-01 18:57:58 -08001537void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1538 DCHECK(invoke->IsInvokeStaticOrDirect());
1539 uint32_t dex_pc = invoke->GetDexPc();
1540 HInstruction* left = invoke->InputAt(0);
1541 HInstruction* right;
1542 Primitive::Type type = left->GetType();
1543 if (!is_signum) {
1544 right = invoke->InputAt(1);
1545 } else if (type == Primitive::kPrimLong) {
1546 right = GetGraph()->GetLongConstant(0);
1547 } else {
1548 right = GetGraph()->GetIntConstant(0);
1549 }
1550 HCompare* compare = new (GetGraph()->GetArena())
1551 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1552 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1553}
1554
Aart Bik75a38b22016-02-17 10:41:50 -08001555void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1556 DCHECK(invoke->IsInvokeStaticOrDirect());
1557 uint32_t dex_pc = invoke->GetDexPc();
1558 // IsNaN(x) is the same as x != x.
1559 HInstruction* x = invoke->InputAt(0);
1560 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001561 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001562 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1563}
1564
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001565void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1566 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1567 SimplifyStringEquals(instruction);
1568 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1569 SimplifySystemArrayCopy(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001570 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateRight ||
1571 instruction->GetIntrinsic() == Intrinsics::kLongRotateRight) {
1572 SimplifyRotate(instruction, false);
1573 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateLeft ||
1574 instruction->GetIntrinsic() == Intrinsics::kLongRotateLeft) {
1575 SimplifyRotate(instruction, true);
Aart Bika19616e2016-02-01 18:57:58 -08001576 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerCompare ||
1577 instruction->GetIntrinsic() == Intrinsics::kLongCompare) {
1578 SimplifyCompare(instruction, /* is_signum */ false);
1579 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerSignum ||
1580 instruction->GetIntrinsic() == Intrinsics::kLongSignum) {
1581 SimplifyCompare(instruction, /* is_signum */ true);
Aart Bik75a38b22016-02-17 10:41:50 -08001582 } else if (instruction->GetIntrinsic() == Intrinsics::kFloatIsNaN ||
1583 instruction->GetIntrinsic() == Intrinsics::kDoubleIsNaN) {
1584 SimplifyIsNaN(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001585 }
1586}
1587
Aart Bikbb245d12015-10-19 11:05:03 -07001588void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1589 HInstruction* cond = deoptimize->InputAt(0);
1590 if (cond->IsConstant()) {
1591 if (cond->AsIntConstant()->IsZero()) {
1592 // Never deopt: instruction can be removed.
1593 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1594 } else {
1595 // Always deopt.
1596 }
1597 }
1598}
1599
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001600} // namespace art