blob: 8daa46c09a640f96931b57fc1efe8a86a44c1c77 [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;
Anton Shaminbdd79352016-02-15 12:48:36 +060073 void VisitBelow(HBelow* condition) OVERRIDE;
74 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
75 void VisitAbove(HAbove* condition) OVERRIDE;
76 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitDiv(HDiv* instruction) OVERRIDE;
78 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010079 void VisitNeg(HNeg* instruction) OVERRIDE;
80 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000081 void VisitOr(HOr* instruction) OVERRIDE;
82 void VisitShl(HShl* instruction) OVERRIDE;
83 void VisitShr(HShr* instruction) OVERRIDE;
84 void VisitSub(HSub* instruction) OVERRIDE;
85 void VisitUShr(HUShr* instruction) OVERRIDE;
86 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000087 void VisitSelect(HSelect* select) OVERRIDE;
88 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010089 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010090 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070091 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010092
93 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000094
Scott Wakeling40a04bf2015-12-11 09:50:36 +000095 void SimplifyRotate(HInvoke* invoke, bool is_left);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010096 void SimplifySystemArrayCopy(HInvoke* invoke);
97 void SimplifyStringEquals(HInvoke* invoke);
Aart Bika19616e2016-02-01 18:57:58 -080098 void SimplifyCompare(HInvoke* invoke, bool has_zero_op);
Aart Bik75a38b22016-02-17 10:41:50 -080099 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800100 void SimplifyFP2Int(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800101 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100102
Calin Juravleacf735c2015-02-12 15:25:22 +0000103 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100104 bool simplification_occurred_ = false;
105 int simplifications_at_current_position_ = 0;
106 // We ensure we do not loop infinitely. The value is a finger in the air guess
107 // that should allow enough simplification.
108 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000109};
110
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100111void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000112 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100113 visitor.Run();
114}
115
116void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100117 // Iterate in reverse post order to open up more simplifications to users
118 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100119 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
120 // The simplification of an instruction to another instruction may yield
121 // possibilities for other simplifications. So although we perform a reverse
122 // post order visit, we sometimes need to revisit an instruction index.
123 simplification_occurred_ = false;
124 VisitBasicBlock(it.Current());
125 if (simplification_occurred_ &&
126 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
127 // New simplifications may be applicable to the instruction at the
128 // current index, so don't advance the iterator.
129 continue;
130 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100131 simplifications_at_current_position_ = 0;
132 it.Advance();
133 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100134}
135
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000136namespace {
137
138bool AreAllBitsSet(HConstant* constant) {
139 return Int64FromConstant(constant) == -1;
140}
141
142} // namespace
143
Alexandre Rames188d4312015-04-09 18:30:21 +0100144// Returns true if the code was simplified to use only one negation operation
145// after the binary operation instead of one on each of the inputs.
146bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
147 DCHECK(binop->IsAdd() || binop->IsSub());
148 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
149 HNeg* left_neg = binop->GetLeft()->AsNeg();
150 HNeg* right_neg = binop->GetRight()->AsNeg();
151 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
152 !right_neg->HasOnlyOneNonEnvironmentUse()) {
153 return false;
154 }
155 // Replace code looking like
156 // NEG tmp1, a
157 // NEG tmp2, b
158 // ADD dst, tmp1, tmp2
159 // with
160 // ADD tmp, a, b
161 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600162 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
163 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
164 // while the later yields `-0.0`.
165 if (!Primitive::IsIntegralType(binop->GetType())) {
166 return false;
167 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100168 binop->ReplaceInput(left_neg->GetInput(), 0);
169 binop->ReplaceInput(right_neg->GetInput(), 1);
170 left_neg->GetBlock()->RemoveInstruction(left_neg);
171 right_neg->GetBlock()->RemoveInstruction(right_neg);
172 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
173 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
174 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
175 RecordSimplification();
176 return true;
177}
178
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000179bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
180 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
181 Primitive::Type type = op->GetType();
182 HInstruction* left = op->GetLeft();
183 HInstruction* right = op->GetRight();
184
185 // We can apply De Morgan's laws if both inputs are Not's and are only used
186 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000187 if (((left->IsNot() && right->IsNot()) ||
188 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000189 left->HasOnlyOneNonEnvironmentUse() &&
190 right->HasOnlyOneNonEnvironmentUse()) {
191 // Replace code looking like
192 // NOT nota, a
193 // NOT notb, b
194 // AND dst, nota, notb (respectively OR)
195 // with
196 // OR or, a, b (respectively AND)
197 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000198 HInstruction* src_left = left->InputAt(0);
199 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000200 uint32_t dex_pc = op->GetDexPc();
201
202 // Remove the negations on the inputs.
203 left->ReplaceWith(src_left);
204 right->ReplaceWith(src_right);
205 left->GetBlock()->RemoveInstruction(left);
206 right->GetBlock()->RemoveInstruction(right);
207
208 // Replace the `HAnd` or `HOr`.
209 HBinaryOperation* hbin;
210 if (op->IsAnd()) {
211 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
212 } else {
213 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
214 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* hnot;
216 if (left->IsBooleanNot()) {
217 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
218 } else {
219 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
220 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000221
222 op->GetBlock()->InsertInstructionBefore(hbin, op);
223 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
224
225 RecordSimplification();
226 return true;
227 }
228
229 return false;
230}
231
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000232void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
233 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
234 HConstant* input_cst = instruction->GetConstantRight();
235 HInstruction* input_other = instruction->GetLeastConstantLeft();
236
Mark Mendellba56d062015-05-05 21:34:03 -0400237 if (input_cst != nullptr) {
238 if (input_cst->IsZero()) {
239 // Replace code looking like
240 // SHL dst, src, 0
241 // with
242 // src
243 instruction->ReplaceWith(input_other);
244 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400245 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000246 }
247}
248
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000249static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
250 return (sub->GetRight() == other &&
251 sub->GetLeft()->IsConstant() &&
252 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
253}
254
255bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
256 HUShr* ushr,
257 HShl* shl) {
258 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
259 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
260 ushr->GetLeft(),
261 ushr->GetRight());
262 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
263 if (!ushr->HasUses()) {
264 ushr->GetBlock()->RemoveInstruction(ushr);
265 }
266 if (!ushr->GetRight()->HasUses()) {
267 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
268 }
269 if (!shl->HasUses()) {
270 shl->GetBlock()->RemoveInstruction(shl);
271 }
272 if (!shl->GetRight()->HasUses()) {
273 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
274 }
275 return true;
276}
277
278// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
279bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000280 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
281 HInstruction* left = op->GetLeft();
282 HInstruction* right = op->GetRight();
283 // If we have an UShr and a Shl (in either order).
284 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
285 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
286 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
287 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
288 if (ushr->GetType() == shl->GetType() &&
289 ushr->GetLeft() == shl->GetLeft()) {
290 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
291 // Shift distances are both constant, try replacing with Ror if they
292 // add up to the register size.
293 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
294 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
295 // Shift distances are potentially of the form x and (reg_size - x).
296 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
297 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
298 // Shift distances are potentially of the form d and -d.
299 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
300 }
301 }
302 }
303 return false;
304}
305
306// Try replacing code looking like (x >>> #rdist OP x << #ldist):
307// UShr dst, x, #rdist
308// Shl tmp, x, #ldist
309// OP dst, dst, tmp
310// or like (x >>> #rdist OP x << #-ldist):
311// UShr dst, x, #rdist
312// Shl tmp, x, #-ldist
313// OP dst, dst, tmp
314// with
315// Ror dst, x, #rdist
316bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
317 HUShr* ushr,
318 HShl* shl) {
319 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
320 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
321 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
322 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
323 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
324 ReplaceRotateWithRor(op, ushr, shl);
325 return true;
326 }
327 return false;
328}
329
330// Replace code looking like (x >>> -d OP x << d):
331// Neg neg, d
332// UShr dst, x, neg
333// Shl tmp, x, d
334// OP dst, dst, tmp
335// with
336// Neg neg, d
337// Ror dst, x, neg
338// *** OR ***
339// Replace code looking like (x >>> d OP x << -d):
340// UShr dst, x, d
341// Neg neg, d
342// Shl tmp, x, neg
343// OP dst, dst, tmp
344// with
345// Ror dst, x, d
346bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
347 HUShr* ushr,
348 HShl* shl) {
349 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
350 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
351 bool neg_is_left = shl->GetRight()->IsNeg();
352 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
353 // And the shift distance being negated is the distance being shifted the other way.
354 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
355 ReplaceRotateWithRor(op, ushr, shl);
356 }
357 return false;
358}
359
360// Try replacing code looking like (x >>> d OP x << (#bits - d)):
361// UShr dst, x, d
362// Sub ld, #bits, d
363// Shl tmp, x, ld
364// OP dst, dst, tmp
365// with
366// Ror dst, x, d
367// *** OR ***
368// Replace code looking like (x >>> (#bits - d) OP x << d):
369// Sub rd, #bits, d
370// UShr dst, x, rd
371// Shl tmp, x, d
372// OP dst, dst, tmp
373// with
374// Neg neg, d
375// Ror dst, x, neg
376bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
377 HUShr* ushr,
378 HShl* shl) {
379 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
380 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
381 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
382 HInstruction* shl_shift = shl->GetRight();
383 HInstruction* ushr_shift = ushr->GetRight();
384 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
385 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
386 return ReplaceRotateWithRor(op, ushr, shl);
387 }
388 return false;
389}
390
Calin Juravle10e244f2015-01-26 18:54:32 +0000391void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
392 HInstruction* obj = null_check->InputAt(0);
393 if (!obj->CanBeNull()) {
394 null_check->ReplaceWith(obj);
395 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000396 if (stats_ != nullptr) {
397 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
398 }
399 }
400}
401
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100402bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
403 if (!input->CanBeNull()) {
404 return true;
405 }
406
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100407 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
408 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100409 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100410 return true;
411 }
412 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100413
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100414 return false;
415}
416
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100417// Returns whether doing a type test between the class of `object` against `klass` has
418// a statically known outcome. The result of the test is stored in `outcome`.
419static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000420 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
421 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
422 ScopedObjectAccess soa(Thread::Current());
423 if (!obj_rti.IsValid()) {
424 // We run the simplifier before the reference type propagation so type info might not be
425 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100426 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000427 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100428
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100429 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100430 if (!class_rti.IsValid()) {
431 // Happens when the loaded class is unresolved.
432 return false;
433 }
434 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000435 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100436 *outcome = true;
437 return true;
438 } else if (obj_rti.IsExact()) {
439 // The test failed at compile time so will also fail at runtime.
440 *outcome = false;
441 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100442 } else if (!class_rti.IsInterface()
443 && !obj_rti.IsInterface()
444 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100445 // Different type hierarchy. The test will fail.
446 *outcome = false;
447 return true;
448 }
449 return false;
450}
451
452void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
453 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100454 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
455 if (load_class->NeedsAccessCheck()) {
456 // If we need to perform an access check we cannot remove the instruction.
457 return;
458 }
459
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100460 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100461 check_cast->ClearMustDoNullCheck();
462 }
463
464 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000465 check_cast->GetBlock()->RemoveInstruction(check_cast);
466 if (stats_ != nullptr) {
467 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
468 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100469 return;
470 }
471
Vladimir Markoa65ed302016-03-14 21:21:29 +0000472 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
473 // the return value check with the `outcome` check, b/27651442 .
474 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700475 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100476 if (outcome) {
477 check_cast->GetBlock()->RemoveInstruction(check_cast);
478 if (stats_ != nullptr) {
479 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
480 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700481 if (!load_class->HasUses()) {
482 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
483 // However, here we know that it cannot because the checkcast was successfull, hence
484 // the class was already loaded.
485 load_class->GetBlock()->RemoveInstruction(load_class);
486 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100487 } else {
488 // Don't do anything for exceptional cases for now. Ideally we should remove
489 // all instructions and blocks this instruction dominates.
490 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000491 }
492}
493
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100494void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100495 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100496 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
497 if (load_class->NeedsAccessCheck()) {
498 // If we need to perform an access check we cannot remove the instruction.
499 return;
500 }
501
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100502 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100503 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100504 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100505 instruction->ClearMustDoNullCheck();
506 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100507
508 HGraph* graph = GetGraph();
509 if (object->IsNullConstant()) {
510 instruction->ReplaceWith(graph->GetIntConstant(0));
511 instruction->GetBlock()->RemoveInstruction(instruction);
512 RecordSimplification();
513 return;
514 }
515
516 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700517 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100518 if (outcome && can_be_null) {
519 // Type test will succeed, we just need a null test.
520 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
521 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
522 instruction->ReplaceWith(test);
523 } else {
524 // We've statically determined the result of the instanceof.
525 instruction->ReplaceWith(graph->GetIntConstant(outcome));
526 }
527 RecordSimplification();
528 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700529 if (outcome && !load_class->HasUses()) {
530 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
531 // However, here we know that it cannot because the instanceof check was successfull, hence
532 // the class was already loaded.
533 load_class->GetBlock()->RemoveInstruction(load_class);
534 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100535 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100536}
537
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100538void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* 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
545void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
546 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100547 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100548 instruction->ClearValueCanBeNull();
549 }
550}
551
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000552void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100553 HBasicBlock* block = check->GetBlock();
554 // Currently always keep the suspend check at entry.
555 if (block->IsEntryBlock()) return;
556
557 // Currently always keep suspend checks at loop entry.
558 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
559 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
560 return;
561 }
562
563 // Remove the suspend check that was added at build time for the baseline
564 // compiler.
565 block->RemoveInstruction(check);
566}
567
Anton Shaminbdd79352016-02-15 12:48:36 +0600568static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
569 HInstruction *lhs = cond->InputAt(0);
570 HInstruction *rhs = cond->InputAt(1);
571 switch (cond->GetKind()) {
572 case HInstruction::kEqual:
573 return new (arena) HEqual(rhs, lhs);
574 case HInstruction::kNotEqual:
575 return new (arena) HNotEqual(rhs, lhs);
576 case HInstruction::kLessThan:
577 return new (arena) HGreaterThan(rhs, lhs);
578 case HInstruction::kLessThanOrEqual:
579 return new (arena) HGreaterThanOrEqual(rhs, lhs);
580 case HInstruction::kGreaterThan:
581 return new (arena) HLessThan(rhs, lhs);
582 case HInstruction::kGreaterThanOrEqual:
583 return new (arena) HLessThanOrEqual(rhs, lhs);
584 case HInstruction::kBelow:
585 return new (arena) HAbove(rhs, lhs);
586 case HInstruction::kBelowOrEqual:
587 return new (arena) HAboveOrEqual(rhs, lhs);
588 case HInstruction::kAbove:
589 return new (arena) HBelow(rhs, lhs);
590 case HInstruction::kAboveOrEqual:
591 return new (arena) HBelowOrEqual(rhs, lhs);
592 default:
593 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
594 }
595 return nullptr;
596}
597
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000598void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100599 HInstruction* input_const = equal->GetConstantRight();
600 if (input_const != nullptr) {
601 HInstruction* input_value = equal->GetLeastConstantLeft();
602 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
603 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100604 // We are comparing the boolean to a constant which is of type int and can
605 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100606 if (input_const->AsIntConstant()->IsOne()) {
607 // Replace (bool_value == true) with bool_value
608 equal->ReplaceWith(input_value);
609 block->RemoveInstruction(equal);
610 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100611 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500612 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
613 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100614 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100615 } else {
616 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
617 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
618 block->RemoveInstruction(equal);
619 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100620 }
Mark Mendellc4701932015-04-10 13:18:51 -0400621 } else {
622 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100623 }
Mark Mendellc4701932015-04-10 13:18:51 -0400624 } else {
625 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100626 }
627}
628
David Brazdil0d13fee2015-04-17 14:52:19 +0100629void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
630 HInstruction* input_const = not_equal->GetConstantRight();
631 if (input_const != nullptr) {
632 HInstruction* input_value = not_equal->GetLeastConstantLeft();
633 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
634 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100635 // We are comparing the boolean to a constant which is of type int and can
636 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100637 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500638 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
639 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100640 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100641 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100642 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100643 not_equal->ReplaceWith(input_value);
644 block->RemoveInstruction(not_equal);
645 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100646 } else {
647 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
648 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
649 block->RemoveInstruction(not_equal);
650 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100651 }
Mark Mendellc4701932015-04-10 13:18:51 -0400652 } else {
653 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100654 }
Mark Mendellc4701932015-04-10 13:18:51 -0400655 } else {
656 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100657 }
658}
659
660void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000661 HInstruction* input = bool_not->InputAt(0);
662 HInstruction* replace_with = nullptr;
663
664 if (input->IsIntConstant()) {
665 // Replace !(true/false) with false/true.
666 if (input->AsIntConstant()->IsOne()) {
667 replace_with = GetGraph()->GetIntConstant(0);
668 } else {
669 DCHECK(input->AsIntConstant()->IsZero());
670 replace_with = GetGraph()->GetIntConstant(1);
671 }
672 } else if (input->IsBooleanNot()) {
673 // Replace (!(!bool_value)) with bool_value.
674 replace_with = input->InputAt(0);
675 } else if (input->IsCondition() &&
676 // Don't change FP compares. The definition of compares involving
677 // NaNs forces the compares to be done as written by the user.
678 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
679 // Replace condition with its opposite.
680 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
681 }
682
683 if (replace_with != nullptr) {
684 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100685 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000686 RecordSimplification();
687 }
688}
689
690void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
691 HInstruction* replace_with = nullptr;
692 HInstruction* condition = select->GetCondition();
693 HInstruction* true_value = select->GetTrueValue();
694 HInstruction* false_value = select->GetFalseValue();
695
696 if (condition->IsBooleanNot()) {
697 // Change ((!cond) ? x : y) to (cond ? y : x).
698 condition = condition->InputAt(0);
699 std::swap(true_value, false_value);
700 select->ReplaceInput(false_value, 0);
701 select->ReplaceInput(true_value, 1);
702 select->ReplaceInput(condition, 2);
703 RecordSimplification();
704 }
705
706 if (true_value == false_value) {
707 // Replace (cond ? x : x) with (x).
708 replace_with = true_value;
709 } else if (condition->IsIntConstant()) {
710 if (condition->AsIntConstant()->IsOne()) {
711 // Replace (true ? x : y) with (x).
712 replace_with = true_value;
713 } else {
714 // Replace (false ? x : y) with (y).
715 DCHECK(condition->AsIntConstant()->IsZero());
716 replace_with = false_value;
717 }
718 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
719 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
720 // Replace (cond ? true : false) with (cond).
721 replace_with = condition;
722 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
723 // Replace (cond ? false : true) with (!cond).
724 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
725 }
726 }
727
728 if (replace_with != nullptr) {
729 select->ReplaceWith(replace_with);
730 select->GetBlock()->RemoveInstruction(select);
731 RecordSimplification();
732 }
733}
734
735void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
736 HInstruction* condition = instruction->InputAt(0);
737 if (condition->IsBooleanNot()) {
738 // Swap successors if input is negated.
739 instruction->ReplaceInput(condition->InputAt(0), 0);
740 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100741 RecordSimplification();
742 }
743}
744
Mingyao Yang0304e182015-01-30 16:41:29 -0800745void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
746 HInstruction* input = instruction->InputAt(0);
747 // If the array is a NewArray with constant size, replace the array length
748 // with the constant instruction. This helps the bounds check elimination phase.
749 if (input->IsNewArray()) {
750 input = input->InputAt(0);
751 if (input->IsIntConstant()) {
752 instruction->ReplaceWith(input);
753 }
754 }
755}
756
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000757void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000758 HInstruction* value = instruction->GetValue();
759 if (value->GetType() != Primitive::kPrimNot) return;
760
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100761 if (CanEnsureNotNullAt(value, instruction)) {
762 instruction->ClearValueCanBeNull();
763 }
764
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000765 if (value->IsArrayGet()) {
766 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
767 // If the code is just swapping elements in the array, no need for a type check.
768 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100769 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000770 }
771 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100772
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100773 if (value->IsNullConstant()) {
774 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100775 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100776 }
777
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100778 ScopedObjectAccess soa(Thread::Current());
779 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
780 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
781 if (!array_rti.IsValid()) {
782 return;
783 }
784
785 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
786 instruction->ClearNeedsTypeCheck();
787 return;
788 }
789
790 if (array_rti.IsObjectArray()) {
791 if (array_rti.IsExact()) {
792 instruction->ClearNeedsTypeCheck();
793 return;
794 }
795 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100796 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000797}
798
Vladimir Markob52bbde2016-02-12 12:06:05 +0000799static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
800 // Besides conversion to the same type, widening integral conversions are implicit,
801 // excluding conversions to long and the byte->char conversion where we need to
802 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
803 return result_type == input_type ||
804 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
805 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
806 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
807 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
808}
809
810static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
811 // The conversion to a larger type is loss-less with the exception of two cases,
812 // - conversion to char, the only unsigned type, where we may lose some bits, and
813 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
814 // For integral to FP conversions this holds because the FP mantissa is large enough.
815 DCHECK_NE(input_type, result_type);
816 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
817 result_type != Primitive::kPrimChar &&
818 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
819}
820
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000821void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000822 HInstruction* input = instruction->GetInput();
823 Primitive::Type input_type = input->GetType();
824 Primitive::Type result_type = instruction->GetResultType();
825 if (IsTypeConversionImplicit(input_type, result_type)) {
826 // Remove the implicit conversion; this includes conversion to the same type.
827 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000828 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000829 RecordSimplification();
830 return;
831 }
832
833 if (input->IsTypeConversion()) {
834 HTypeConversion* input_conversion = input->AsTypeConversion();
835 HInstruction* original_input = input_conversion->GetInput();
836 Primitive::Type original_type = original_input->GetType();
837
838 // When the first conversion is lossless, a direct conversion from the original type
839 // to the final type yields the same result, even for a lossy second conversion, for
840 // example float->double->int or int->double->float.
841 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
842
843 // For integral conversions, see if the first conversion loses only bits that the second
844 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
845 // conversion yields the same result, for example long->int->short or int->char->short.
846 bool integral_conversions_with_non_widening_second =
847 Primitive::IsIntegralType(input_type) &&
848 Primitive::IsIntegralType(original_type) &&
849 Primitive::IsIntegralType(result_type) &&
850 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
851
852 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
853 // If the merged conversion is implicit, do the simplification unconditionally.
854 if (IsTypeConversionImplicit(original_type, result_type)) {
855 instruction->ReplaceWith(original_input);
856 instruction->GetBlock()->RemoveInstruction(instruction);
857 if (!input_conversion->HasUses()) {
858 // Don't wait for DCE.
859 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
860 }
861 RecordSimplification();
862 return;
863 }
864 // Otherwise simplify only if the first conversion has no other use.
865 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
866 input_conversion->ReplaceWith(original_input);
867 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
868 RecordSimplification();
869 return;
870 }
871 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000872 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000873 DCHECK(Primitive::IsIntegralType(input_type));
874 HAnd* input_and = input->AsAnd();
875 HConstant* constant = input_and->GetConstantRight();
876 if (constant != nullptr) {
877 int64_t value = Int64FromConstant(constant);
878 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
879 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
880 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
881 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000882 HInstruction* original_input = input_and->GetLeastConstantLeft();
883 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
884 instruction->ReplaceWith(original_input);
885 instruction->GetBlock()->RemoveInstruction(instruction);
886 RecordSimplification();
887 return;
888 } else if (input->HasOnlyOneNonEnvironmentUse()) {
889 input_and->ReplaceWith(original_input);
890 input_and->GetBlock()->RemoveInstruction(input_and);
891 RecordSimplification();
892 return;
893 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000894 }
895 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000896 }
897}
898
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000899void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
900 HConstant* input_cst = instruction->GetConstantRight();
901 HInstruction* input_other = instruction->GetLeastConstantLeft();
902 if ((input_cst != nullptr) && input_cst->IsZero()) {
903 // Replace code looking like
904 // ADD dst, src, 0
905 // with
906 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600907 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
908 // `x` is `-0.0`, the former expression yields `0.0`, while the later
909 // yields `-0.0`.
910 if (Primitive::IsIntegralType(instruction->GetType())) {
911 instruction->ReplaceWith(input_other);
912 instruction->GetBlock()->RemoveInstruction(instruction);
913 return;
914 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100915 }
916
917 HInstruction* left = instruction->GetLeft();
918 HInstruction* right = instruction->GetRight();
919 bool left_is_neg = left->IsNeg();
920 bool right_is_neg = right->IsNeg();
921
922 if (left_is_neg && right_is_neg) {
923 if (TryMoveNegOnInputsAfterBinop(instruction)) {
924 return;
925 }
926 }
927
928 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
929 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
930 // Replace code looking like
931 // NEG tmp, b
932 // ADD dst, a, tmp
933 // with
934 // SUB dst, a, b
935 // We do not perform the optimization if the input negation has environment
936 // uses or multiple non-environment uses as it could lead to worse code. In
937 // particular, we do not want the live range of `b` to be extended if we are
938 // not sure the initial 'NEG' instruction can be removed.
939 HInstruction* other = left_is_neg ? right : left;
940 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
941 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
942 RecordSimplification();
943 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000944 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000945 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000946
947 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000948}
949
950void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
951 HConstant* input_cst = instruction->GetConstantRight();
952 HInstruction* input_other = instruction->GetLeastConstantLeft();
953
Vladimir Marko452c1b62015-09-25 14:44:17 +0100954 if (input_cst != nullptr) {
955 int64_t value = Int64FromConstant(input_cst);
956 if (value == -1) {
957 // Replace code looking like
958 // AND dst, src, 0xFFF...FF
959 // with
960 // src
961 instruction->ReplaceWith(input_other);
962 instruction->GetBlock()->RemoveInstruction(instruction);
963 RecordSimplification();
964 return;
965 }
966 // Eliminate And from UShr+And if the And-mask contains all the bits that
967 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
968 // precisely clears the shifted-in sign bits.
969 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
970 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
971 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
972 size_t num_tail_bits_set = CTZ(value + 1);
973 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
974 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
975 instruction->ReplaceWith(input_other);
976 instruction->GetBlock()->RemoveInstruction(instruction);
977 RecordSimplification();
978 return;
979 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
980 input_other->HasOnlyOneNonEnvironmentUse()) {
981 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
982 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
983 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
984 input_other->InputAt(0),
985 input_other->InputAt(1),
986 input_other->GetDexPc());
987 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
988 input_other->GetBlock()->RemoveInstruction(input_other);
989 RecordSimplification();
990 return;
991 }
992 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000993 }
994
995 // We assume that GVN has run before, so we only perform a pointer comparison.
996 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100997 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000998 if (instruction->GetLeft() == instruction->GetRight()) {
999 // Replace code looking like
1000 // AND dst, src, src
1001 // with
1002 // src
1003 instruction->ReplaceWith(instruction->GetLeft());
1004 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001005 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001006 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001007
1008 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001009}
1010
Mark Mendellc4701932015-04-10 13:18:51 -04001011void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1012 VisitCondition(condition);
1013}
1014
1015void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1016 VisitCondition(condition);
1017}
1018
1019void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1020 VisitCondition(condition);
1021}
1022
1023void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1024 VisitCondition(condition);
1025}
1026
Anton Shaminbdd79352016-02-15 12:48:36 +06001027void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1028 VisitCondition(condition);
1029}
1030
1031void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1032 VisitCondition(condition);
1033}
1034
1035void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1036 VisitCondition(condition);
1037}
1038
1039void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1040 VisitCondition(condition);
1041}
Aart Bike9f37602015-10-09 11:15:55 -07001042
Mark Mendellc4701932015-04-10 13:18:51 -04001043void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001044 // Reverse condition if left is constant. Our code generators prefer constant
1045 // on the right hand side.
1046 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1047 HBasicBlock* block = condition->GetBlock();
1048 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1049 // If it is a fp we must set the opposite bias.
1050 if (replacement != nullptr) {
1051 if (condition->IsLtBias()) {
1052 replacement->SetBias(ComparisonBias::kGtBias);
1053 } else if (condition->IsGtBias()) {
1054 replacement->SetBias(ComparisonBias::kLtBias);
1055 }
1056 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1057 RecordSimplification();
1058
1059 condition = replacement;
1060 }
1061 }
Mark Mendellc4701932015-04-10 13:18:51 -04001062
Mark Mendellc4701932015-04-10 13:18:51 -04001063 HInstruction* left = condition->GetLeft();
1064 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001065
1066 // Try to fold an HCompare into this HCondition.
1067
Mark Mendellc4701932015-04-10 13:18:51 -04001068 // We can only replace an HCondition which compares a Compare to 0.
1069 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1070 // condition with a long, float or double comparison as input.
1071 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1072 // Conversion is not possible.
1073 return;
1074 }
1075
1076 // Is the Compare only used for this purpose?
1077 if (!left->GetUses().HasOnlyOneUse()) {
1078 // Someone else also wants the result of the compare.
1079 return;
1080 }
1081
1082 if (!left->GetEnvUses().IsEmpty()) {
1083 // There is a reference to the compare result in an environment. Do we really need it?
1084 if (GetGraph()->IsDebuggable()) {
1085 return;
1086 }
1087
1088 // We have to ensure that there are no deopt points in the sequence.
1089 if (left->HasAnyEnvironmentUseBefore(condition)) {
1090 return;
1091 }
1092 }
1093
1094 // Clean up any environment uses from the HCompare, if any.
1095 left->RemoveEnvironmentUsers();
1096
1097 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1098 condition->SetBias(left->AsCompare()->GetBias());
1099
1100 // Replace the operands of the HCondition.
1101 condition->ReplaceInput(left->InputAt(0), 0);
1102 condition->ReplaceInput(left->InputAt(1), 1);
1103
1104 // Remove the HCompare.
1105 left->GetBlock()->RemoveInstruction(left);
1106
1107 RecordSimplification();
1108}
1109
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001110void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1111 HConstant* input_cst = instruction->GetConstantRight();
1112 HInstruction* input_other = instruction->GetLeastConstantLeft();
1113 Primitive::Type type = instruction->GetType();
1114
1115 if ((input_cst != nullptr) && input_cst->IsOne()) {
1116 // Replace code looking like
1117 // DIV dst, src, 1
1118 // with
1119 // src
1120 instruction->ReplaceWith(input_other);
1121 instruction->GetBlock()->RemoveInstruction(instruction);
1122 return;
1123 }
1124
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001125 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001126 // Replace code looking like
1127 // DIV dst, src, -1
1128 // with
1129 // NEG dst, src
1130 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001131 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001132 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001133 return;
1134 }
1135
1136 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1137 // Try replacing code looking like
1138 // DIV dst, src, constant
1139 // with
1140 // MUL dst, src, 1 / constant
1141 HConstant* reciprocal = nullptr;
1142 if (type == Primitive::Primitive::kPrimDouble) {
1143 double value = input_cst->AsDoubleConstant()->GetValue();
1144 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1145 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1146 }
1147 } else {
1148 DCHECK_EQ(type, Primitive::kPrimFloat);
1149 float value = input_cst->AsFloatConstant()->GetValue();
1150 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1151 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1152 }
1153 }
1154
1155 if (reciprocal != nullptr) {
1156 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1157 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1158 RecordSimplification();
1159 return;
1160 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001161 }
1162}
1163
1164void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1165 HConstant* input_cst = instruction->GetConstantRight();
1166 HInstruction* input_other = instruction->GetLeastConstantLeft();
1167 Primitive::Type type = instruction->GetType();
1168 HBasicBlock* block = instruction->GetBlock();
1169 ArenaAllocator* allocator = GetGraph()->GetArena();
1170
1171 if (input_cst == nullptr) {
1172 return;
1173 }
1174
1175 if (input_cst->IsOne()) {
1176 // Replace code looking like
1177 // MUL dst, src, 1
1178 // with
1179 // src
1180 instruction->ReplaceWith(input_other);
1181 instruction->GetBlock()->RemoveInstruction(instruction);
1182 return;
1183 }
1184
1185 if (input_cst->IsMinusOne() &&
1186 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1187 // Replace code looking like
1188 // MUL dst, src, -1
1189 // with
1190 // NEG dst, src
1191 HNeg* neg = new (allocator) HNeg(type, input_other);
1192 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001193 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001194 return;
1195 }
1196
1197 if (Primitive::IsFloatingPointType(type) &&
1198 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1199 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1200 // Replace code looking like
1201 // FP_MUL dst, src, 2.0
1202 // with
1203 // FP_ADD dst, src, src
1204 // The 'int' and 'long' cases are handled below.
1205 block->ReplaceAndRemoveInstructionWith(instruction,
1206 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001207 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001208 return;
1209 }
1210
1211 if (Primitive::IsIntOrLongType(type)) {
1212 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001213 // Even though constant propagation also takes care of the zero case, other
1214 // optimizations can lead to having a zero multiplication.
1215 if (factor == 0) {
1216 // Replace code looking like
1217 // MUL dst, src, 0
1218 // with
1219 // 0
1220 instruction->ReplaceWith(input_cst);
1221 instruction->GetBlock()->RemoveInstruction(instruction);
1222 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001223 // Replace code looking like
1224 // MUL dst, src, pow_of_2
1225 // with
1226 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001227 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001228 HShl* shl = new(allocator) HShl(type, input_other, shift);
1229 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001230 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001231 } else if (IsPowerOfTwo(factor - 1)) {
1232 // Transform code looking like
1233 // MUL dst, src, (2^n + 1)
1234 // into
1235 // SHL tmp, src, n
1236 // ADD dst, src, tmp
1237 HShl* shl = new (allocator) HShl(type,
1238 input_other,
1239 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1240 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1241
1242 block->InsertInstructionBefore(shl, instruction);
1243 block->ReplaceAndRemoveInstructionWith(instruction, add);
1244 RecordSimplification();
1245 } else if (IsPowerOfTwo(factor + 1)) {
1246 // Transform code looking like
1247 // MUL dst, src, (2^n - 1)
1248 // into
1249 // SHL tmp, src, n
1250 // SUB dst, tmp, src
1251 HShl* shl = new (allocator) HShl(type,
1252 input_other,
1253 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1254 HSub* sub = new (allocator) HSub(type, shl, input_other);
1255
1256 block->InsertInstructionBefore(shl, instruction);
1257 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1258 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001259 }
1260 }
1261}
1262
Alexandre Rames188d4312015-04-09 18:30:21 +01001263void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1264 HInstruction* input = instruction->GetInput();
1265 if (input->IsNeg()) {
1266 // Replace code looking like
1267 // NEG tmp, src
1268 // NEG dst, tmp
1269 // with
1270 // src
1271 HNeg* previous_neg = input->AsNeg();
1272 instruction->ReplaceWith(previous_neg->GetInput());
1273 instruction->GetBlock()->RemoveInstruction(instruction);
1274 // We perform the optimization even if the input negation has environment
1275 // uses since it allows removing the current instruction. But we only delete
1276 // the input negation only if it is does not have any uses left.
1277 if (!previous_neg->HasUses()) {
1278 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1279 }
1280 RecordSimplification();
1281 return;
1282 }
1283
Serguei Katkov339dfc22015-04-20 12:29:32 +06001284 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1285 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001286 // Replace code looking like
1287 // SUB tmp, a, b
1288 // NEG dst, tmp
1289 // with
1290 // SUB dst, b, a
1291 // We do not perform the optimization if the input subtraction has
1292 // environment uses or multiple non-environment uses as it could lead to
1293 // worse code. In particular, we do not want the live ranges of `a` and `b`
1294 // to be extended if we are not sure the initial 'SUB' instruction can be
1295 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001296 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001297 HSub* sub = input->AsSub();
1298 HSub* new_sub =
1299 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1300 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1301 if (!sub->HasUses()) {
1302 sub->GetBlock()->RemoveInstruction(sub);
1303 }
1304 RecordSimplification();
1305 }
1306}
1307
1308void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1309 HInstruction* input = instruction->GetInput();
1310 if (input->IsNot()) {
1311 // Replace code looking like
1312 // NOT tmp, src
1313 // NOT dst, tmp
1314 // with
1315 // src
1316 // We perform the optimization even if the input negation has environment
1317 // uses since it allows removing the current instruction. But we only delete
1318 // the input negation only if it is does not have any uses left.
1319 HNot* previous_not = input->AsNot();
1320 instruction->ReplaceWith(previous_not->GetInput());
1321 instruction->GetBlock()->RemoveInstruction(instruction);
1322 if (!previous_not->HasUses()) {
1323 previous_not->GetBlock()->RemoveInstruction(previous_not);
1324 }
1325 RecordSimplification();
1326 }
1327}
1328
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001329void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1330 HConstant* input_cst = instruction->GetConstantRight();
1331 HInstruction* input_other = instruction->GetLeastConstantLeft();
1332
1333 if ((input_cst != nullptr) && input_cst->IsZero()) {
1334 // Replace code looking like
1335 // OR dst, src, 0
1336 // with
1337 // src
1338 instruction->ReplaceWith(input_other);
1339 instruction->GetBlock()->RemoveInstruction(instruction);
1340 return;
1341 }
1342
1343 // We assume that GVN has run before, so we only perform a pointer comparison.
1344 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001345 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001346 if (instruction->GetLeft() == instruction->GetRight()) {
1347 // Replace code looking like
1348 // OR dst, src, src
1349 // with
1350 // src
1351 instruction->ReplaceWith(instruction->GetLeft());
1352 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001353 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001354 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001355
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001356 if (TryDeMorganNegationFactoring(instruction)) return;
1357
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001358 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001359}
1360
1361void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1362 VisitShift(instruction);
1363}
1364
1365void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1366 VisitShift(instruction);
1367}
1368
1369void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1370 HConstant* input_cst = instruction->GetConstantRight();
1371 HInstruction* input_other = instruction->GetLeastConstantLeft();
1372
Serguei Katkov115b53f2015-08-05 17:03:30 +06001373 Primitive::Type type = instruction->GetType();
1374 if (Primitive::IsFloatingPointType(type)) {
1375 return;
1376 }
1377
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001378 if ((input_cst != nullptr) && input_cst->IsZero()) {
1379 // Replace code looking like
1380 // SUB dst, src, 0
1381 // with
1382 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001383 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1384 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1385 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001386 instruction->ReplaceWith(input_other);
1387 instruction->GetBlock()->RemoveInstruction(instruction);
1388 return;
1389 }
1390
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001391 HBasicBlock* block = instruction->GetBlock();
1392 ArenaAllocator* allocator = GetGraph()->GetArena();
1393
Alexandre Rames188d4312015-04-09 18:30:21 +01001394 HInstruction* left = instruction->GetLeft();
1395 HInstruction* right = instruction->GetRight();
1396 if (left->IsConstant()) {
1397 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001398 // Replace code looking like
1399 // SUB dst, 0, src
1400 // with
1401 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001402 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001403 // `x` is `0.0`, the former expression yields `0.0`, while the later
1404 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001405 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001406 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001407 RecordSimplification();
1408 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001409 }
1410 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001411
1412 if (left->IsNeg() && right->IsNeg()) {
1413 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1414 return;
1415 }
1416 }
1417
1418 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1419 // Replace code looking like
1420 // NEG tmp, b
1421 // SUB dst, a, tmp
1422 // with
1423 // ADD dst, a, b
1424 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1425 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1426 RecordSimplification();
1427 right->GetBlock()->RemoveInstruction(right);
1428 return;
1429 }
1430
1431 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1432 // Replace code looking like
1433 // NEG tmp, a
1434 // SUB dst, tmp, b
1435 // with
1436 // ADD tmp, a, b
1437 // NEG dst, tmp
1438 // The second version is not intrinsically better, but enables more
1439 // transformations.
1440 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1441 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1442 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1443 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1444 instruction->ReplaceWith(neg);
1445 instruction->GetBlock()->RemoveInstruction(instruction);
1446 RecordSimplification();
1447 left->GetBlock()->RemoveInstruction(left);
1448 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001449}
1450
1451void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1452 VisitShift(instruction);
1453}
1454
1455void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1456 HConstant* input_cst = instruction->GetConstantRight();
1457 HInstruction* input_other = instruction->GetLeastConstantLeft();
1458
1459 if ((input_cst != nullptr) && input_cst->IsZero()) {
1460 // Replace code looking like
1461 // XOR dst, src, 0
1462 // with
1463 // src
1464 instruction->ReplaceWith(input_other);
1465 instruction->GetBlock()->RemoveInstruction(instruction);
1466 return;
1467 }
1468
1469 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1470 // Replace code looking like
1471 // XOR dst, src, 0xFFF...FF
1472 // with
1473 // NOT dst, src
1474 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1475 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001476 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001477 return;
1478 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001479
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001480 HInstruction* left = instruction->GetLeft();
1481 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001482 if (((left->IsNot() && right->IsNot()) ||
1483 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001484 left->HasOnlyOneNonEnvironmentUse() &&
1485 right->HasOnlyOneNonEnvironmentUse()) {
1486 // Replace code looking like
1487 // NOT nota, a
1488 // NOT notb, b
1489 // XOR dst, nota, notb
1490 // with
1491 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001492 instruction->ReplaceInput(left->InputAt(0), 0);
1493 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001494 left->GetBlock()->RemoveInstruction(left);
1495 right->GetBlock()->RemoveInstruction(right);
1496 RecordSimplification();
1497 return;
1498 }
1499
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001500 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001501}
1502
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001503void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1504 HInstruction* argument = instruction->InputAt(1);
1505 HInstruction* receiver = instruction->InputAt(0);
1506 if (receiver == argument) {
1507 // Because String.equals is an instance call, the receiver is
1508 // a null check if we don't know it's null. The argument however, will
1509 // be the actual object. So we cannot end up in a situation where both
1510 // are equal but could be null.
1511 DCHECK(CanEnsureNotNullAt(argument, instruction));
1512 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1513 instruction->GetBlock()->RemoveInstruction(instruction);
1514 } else {
1515 StringEqualsOptimizations optimizations(instruction);
1516 if (CanEnsureNotNullAt(argument, instruction)) {
1517 optimizations.SetArgumentNotNull();
1518 }
1519 ScopedObjectAccess soa(Thread::Current());
1520 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1521 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1522 optimizations.SetArgumentIsString();
1523 }
1524 }
1525}
1526
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001527void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1528 DCHECK(invoke->IsInvokeStaticOrDirect());
1529 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001530 HInstruction* value = invoke->InputAt(0);
1531 HInstruction* distance = invoke->InputAt(1);
1532 // Replace the invoke with an HRor.
1533 if (is_left) {
1534 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1535 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1536 }
1537 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1538 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1539 // Remove ClinitCheck and LoadClass, if possible.
1540 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1541 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1542 clinit->GetBlock()->RemoveInstruction(clinit);
1543 HInstruction* ldclass = clinit->InputAt(0);
1544 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1545 ldclass->GetBlock()->RemoveInstruction(ldclass);
1546 }
1547 }
1548}
1549
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001550static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1551 if (potential_length->IsArrayLength()) {
1552 return potential_length->InputAt(0) == potential_array;
1553 }
1554
1555 if (potential_array->IsNewArray()) {
1556 return potential_array->InputAt(0) == potential_length;
1557 }
1558
1559 return false;
1560}
1561
1562void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1563 HInstruction* source = instruction->InputAt(0);
1564 HInstruction* destination = instruction->InputAt(2);
1565 HInstruction* count = instruction->InputAt(4);
1566 SystemArrayCopyOptimizations optimizations(instruction);
1567 if (CanEnsureNotNullAt(source, instruction)) {
1568 optimizations.SetSourceIsNotNull();
1569 }
1570 if (CanEnsureNotNullAt(destination, instruction)) {
1571 optimizations.SetDestinationIsNotNull();
1572 }
1573 if (destination == source) {
1574 optimizations.SetDestinationIsSource();
1575 }
1576
1577 if (IsArrayLengthOf(count, source)) {
1578 optimizations.SetCountIsSourceLength();
1579 }
1580
1581 if (IsArrayLengthOf(count, destination)) {
1582 optimizations.SetCountIsDestinationLength();
1583 }
1584
1585 {
1586 ScopedObjectAccess soa(Thread::Current());
1587 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1588 if (destination_rti.IsValid()) {
1589 if (destination_rti.IsObjectArray()) {
1590 if (destination_rti.IsExact()) {
1591 optimizations.SetDoesNotNeedTypeCheck();
1592 }
1593 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001594 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001595 if (destination_rti.IsPrimitiveArrayClass()) {
1596 optimizations.SetDestinationIsPrimitiveArray();
1597 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1598 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001599 }
1600 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001601 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1602 if (source_rti.IsValid()) {
1603 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1604 optimizations.SetDoesNotNeedTypeCheck();
1605 }
1606 if (source_rti.IsPrimitiveArrayClass()) {
1607 optimizations.SetSourceIsPrimitiveArray();
1608 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1609 optimizations.SetSourceIsNonPrimitiveArray();
1610 }
1611 }
1612 }
1613}
1614
Aart Bika19616e2016-02-01 18:57:58 -08001615void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1616 DCHECK(invoke->IsInvokeStaticOrDirect());
1617 uint32_t dex_pc = invoke->GetDexPc();
1618 HInstruction* left = invoke->InputAt(0);
1619 HInstruction* right;
1620 Primitive::Type type = left->GetType();
1621 if (!is_signum) {
1622 right = invoke->InputAt(1);
1623 } else if (type == Primitive::kPrimLong) {
1624 right = GetGraph()->GetLongConstant(0);
1625 } else {
1626 right = GetGraph()->GetIntConstant(0);
1627 }
1628 HCompare* compare = new (GetGraph()->GetArena())
1629 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1630 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1631}
1632
Aart Bik75a38b22016-02-17 10:41:50 -08001633void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1634 DCHECK(invoke->IsInvokeStaticOrDirect());
1635 uint32_t dex_pc = invoke->GetDexPc();
1636 // IsNaN(x) is the same as x != x.
1637 HInstruction* x = invoke->InputAt(0);
1638 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001639 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001640 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1641}
1642
Aart Bik2a6aad92016-02-25 11:32:32 -08001643void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1644 DCHECK(invoke->IsInvokeStaticOrDirect());
1645 uint32_t dex_pc = invoke->GetDexPc();
1646 HInstruction* x = invoke->InputAt(0);
1647 Primitive::Type type = x->GetType();
1648 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1649 HInstruction* nan;
1650 if (type == Primitive::kPrimDouble) {
1651 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1652 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1653 kNeedsEnvironmentOrCache,
1654 kNoSideEffects,
1655 kNoThrow);
1656 } else {
1657 DCHECK_EQ(type, Primitive::kPrimFloat);
1658 nan = GetGraph()->GetIntConstant(0x7fc00000);
1659 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1660 kNeedsEnvironmentOrCache,
1661 kNoSideEffects,
1662 kNoThrow);
1663 }
1664 // Test IsNaN(x), which is the same as x != x.
1665 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1666 condition->SetBias(ComparisonBias::kLtBias);
1667 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1668 // Select between the two.
1669 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1670 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1671 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1672}
1673
Aart Bik11932592016-03-08 12:42:25 -08001674void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1675 uint32_t dex_pc = invoke->GetDexPc();
1676 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1677 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1678}
1679
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001680void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001681 switch (instruction->GetIntrinsic()) {
1682 case Intrinsics::kStringEquals:
1683 SimplifyStringEquals(instruction);
1684 break;
1685 case Intrinsics::kSystemArrayCopy:
1686 SimplifySystemArrayCopy(instruction);
1687 break;
1688 case Intrinsics::kIntegerRotateRight:
1689 case Intrinsics::kLongRotateRight:
1690 SimplifyRotate(instruction, false);
1691 break;
1692 case Intrinsics::kIntegerRotateLeft:
1693 case Intrinsics::kLongRotateLeft:
1694 SimplifyRotate(instruction, true);
1695 break;
1696 case Intrinsics::kIntegerCompare:
1697 case Intrinsics::kLongCompare:
1698 SimplifyCompare(instruction, /* is_signum */ false);
1699 break;
1700 case Intrinsics::kIntegerSignum:
1701 case Intrinsics::kLongSignum:
1702 SimplifyCompare(instruction, /* is_signum */ true);
1703 break;
1704 case Intrinsics::kFloatIsNaN:
1705 case Intrinsics::kDoubleIsNaN:
1706 SimplifyIsNaN(instruction);
1707 break;
1708 case Intrinsics::kFloatFloatToIntBits:
1709 case Intrinsics::kDoubleDoubleToLongBits:
1710 SimplifyFP2Int(instruction);
1711 break;
Aart Bik11932592016-03-08 12:42:25 -08001712 case Intrinsics::kUnsafeLoadFence:
1713 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1714 break;
1715 case Intrinsics::kUnsafeStoreFence:
1716 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1717 break;
1718 case Intrinsics::kUnsafeFullFence:
1719 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1720 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001721 default:
1722 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001723 }
1724}
1725
Aart Bikbb245d12015-10-19 11:05:03 -07001726void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1727 HInstruction* cond = deoptimize->InputAt(0);
1728 if (cond->IsConstant()) {
1729 if (cond->AsIntConstant()->IsZero()) {
1730 // Never deopt: instruction can be removed.
1731 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1732 } else {
1733 // Always deopt.
1734 }
1735 }
1736}
1737
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001738} // namespace art