blob: 439e3b66db34f3c95cf2ef4d0f9b0e1346858539 [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
Aart Bik71bf7b42016-11-16 10:17:46 -080019#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010020#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000021#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070022#include "scoped_thread_state_change-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000023
Nicolas Geoffray3c049742014-09-24 18:10:46 +010024namespace art {
25
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000027 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000028 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010029 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010030 stats_(stats) {}
31
32 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000033
34 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010035 void RecordSimplification() {
36 simplification_occurred_ = true;
37 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000038 MaybeRecordStat(kInstructionSimplifications);
39 }
40
41 void MaybeRecordStat(MethodCompilationStat stat) {
42 if (stats_ != nullptr) {
43 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010044 }
45 }
46
Scott Wakeling40a04bf2015-12-11 09:50:36 +000047 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
48 bool TryReplaceWithRotate(HBinaryOperation* instruction);
49 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
52
Alexandre Rames188d4312015-04-09 18:30:21 +010053 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000054 // `op` should be either HOr or HAnd.
55 // De Morgan's laws:
56 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
57 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010058 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
59 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
60
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000061 void VisitShift(HBinaryOperation* shift);
62
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000063 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010064 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
65 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010066 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
67 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000068 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000069 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000070 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080071 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000072 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000073 void VisitAdd(HAdd* instruction) OVERRIDE;
74 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040075 void VisitCondition(HCondition* instruction) OVERRIDE;
76 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
77 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
78 void VisitLessThan(HLessThan* condition) OVERRIDE;
79 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060080 void VisitBelow(HBelow* condition) OVERRIDE;
81 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
82 void VisitAbove(HAbove* condition) OVERRIDE;
83 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000084 void VisitDiv(HDiv* instruction) OVERRIDE;
85 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010086 void VisitNeg(HNeg* instruction) OVERRIDE;
87 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitOr(HOr* instruction) OVERRIDE;
89 void VisitShl(HShl* instruction) OVERRIDE;
90 void VisitShr(HShr* instruction) OVERRIDE;
91 void VisitSub(HSub* instruction) OVERRIDE;
92 void VisitUShr(HUShr* instruction) OVERRIDE;
93 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000094 void VisitSelect(HSelect* select) OVERRIDE;
95 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010096 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010097 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070098 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010099
100 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000101
Roland Levillain22c49222016-03-18 14:04:28 +0000102 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100103 void SimplifySystemArrayCopy(HInvoke* invoke);
104 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000105 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800106 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800107 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100108 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100109 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800110 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800111 void SimplifyReturnThis(HInvoke* invoke);
112 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800113 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100114
Calin Juravleacf735c2015-02-12 15:25:22 +0000115 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100116 bool simplification_occurred_ = false;
117 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700118 // We ensure we do not loop infinitely. The value should not be too high, since that
119 // would allow looping around the same basic block too many times. The value should
120 // not be too low either, however, since we want to allow revisiting a basic block
121 // with many statements and simplifications at least once.
122 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000123};
124
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100125void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000126 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100127 visitor.Run();
128}
129
130void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100131 // Iterate in reverse post order to open up more simplifications to users
132 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100133 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100134 // The simplification of an instruction to another instruction may yield
135 // possibilities for other simplifications. So although we perform a reverse
136 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100137 do {
138 simplification_occurred_ = false;
139 VisitBasicBlock(block);
140 } while (simplification_occurred_ &&
141 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100142 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100143 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100144}
145
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000146namespace {
147
148bool AreAllBitsSet(HConstant* constant) {
149 return Int64FromConstant(constant) == -1;
150}
151
152} // namespace
153
Alexandre Rames188d4312015-04-09 18:30:21 +0100154// Returns true if the code was simplified to use only one negation operation
155// after the binary operation instead of one on each of the inputs.
156bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
157 DCHECK(binop->IsAdd() || binop->IsSub());
158 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
159 HNeg* left_neg = binop->GetLeft()->AsNeg();
160 HNeg* right_neg = binop->GetRight()->AsNeg();
161 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
162 !right_neg->HasOnlyOneNonEnvironmentUse()) {
163 return false;
164 }
165 // Replace code looking like
166 // NEG tmp1, a
167 // NEG tmp2, b
168 // ADD dst, tmp1, tmp2
169 // with
170 // ADD tmp, a, b
171 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600172 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
173 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
174 // while the later yields `-0.0`.
175 if (!Primitive::IsIntegralType(binop->GetType())) {
176 return false;
177 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100178 binop->ReplaceInput(left_neg->GetInput(), 0);
179 binop->ReplaceInput(right_neg->GetInput(), 1);
180 left_neg->GetBlock()->RemoveInstruction(left_neg);
181 right_neg->GetBlock()->RemoveInstruction(right_neg);
182 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
183 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
184 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
185 RecordSimplification();
186 return true;
187}
188
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000189bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
190 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
191 Primitive::Type type = op->GetType();
192 HInstruction* left = op->GetLeft();
193 HInstruction* right = op->GetRight();
194
195 // We can apply De Morgan's laws if both inputs are Not's and are only used
196 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000197 if (((left->IsNot() && right->IsNot()) ||
198 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000199 left->HasOnlyOneNonEnvironmentUse() &&
200 right->HasOnlyOneNonEnvironmentUse()) {
201 // Replace code looking like
202 // NOT nota, a
203 // NOT notb, b
204 // AND dst, nota, notb (respectively OR)
205 // with
206 // OR or, a, b (respectively AND)
207 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000208 HInstruction* src_left = left->InputAt(0);
209 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000210 uint32_t dex_pc = op->GetDexPc();
211
212 // Remove the negations on the inputs.
213 left->ReplaceWith(src_left);
214 right->ReplaceWith(src_right);
215 left->GetBlock()->RemoveInstruction(left);
216 right->GetBlock()->RemoveInstruction(right);
217
218 // Replace the `HAnd` or `HOr`.
219 HBinaryOperation* hbin;
220 if (op->IsAnd()) {
221 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
222 } else {
223 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
224 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000225 HInstruction* hnot;
226 if (left->IsBooleanNot()) {
227 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
228 } else {
229 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
230 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000231
232 op->GetBlock()->InsertInstructionBefore(hbin, op);
233 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
234
235 RecordSimplification();
236 return true;
237 }
238
239 return false;
240}
241
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000242void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
243 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100244 HInstruction* shift_amount = instruction->GetRight();
245 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000246
Alexandre Rames50518442016-06-27 11:39:19 +0100247 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
248 ? kMaxLongShiftDistance
249 : kMaxIntShiftDistance;
250
251 if (shift_amount->IsConstant()) {
252 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
253 if ((cst & implicit_mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400254 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100255 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400256 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100257 // value
258 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400259 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100260 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100261 return;
262 }
263 }
264
265 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
266 // unnecessary explicit masking operations on the shift amount.
267 // Replace code looking like
268 // AND masked_shift, shift, <superset of implicit mask>
269 // SHL dst, value, masked_shift
270 // with
271 // SHL dst, value, shift
272 if (shift_amount->IsAnd()) {
273 HAnd* and_insn = shift_amount->AsAnd();
274 HConstant* mask = and_insn->GetConstantRight();
275 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
276 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
277 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400278 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000279 }
280}
281
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000282static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
283 return (sub->GetRight() == other &&
284 sub->GetLeft()->IsConstant() &&
285 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
286}
287
288bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
289 HUShr* ushr,
290 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000291 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
292 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000293 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
294 if (!ushr->HasUses()) {
295 ushr->GetBlock()->RemoveInstruction(ushr);
296 }
297 if (!ushr->GetRight()->HasUses()) {
298 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
299 }
300 if (!shl->HasUses()) {
301 shl->GetBlock()->RemoveInstruction(shl);
302 }
303 if (!shl->GetRight()->HasUses()) {
304 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
305 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100306 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000307 return true;
308}
309
310// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
311bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000312 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
313 HInstruction* left = op->GetLeft();
314 HInstruction* right = op->GetRight();
315 // If we have an UShr and a Shl (in either order).
316 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
317 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
318 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
319 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
320 if (ushr->GetType() == shl->GetType() &&
321 ushr->GetLeft() == shl->GetLeft()) {
322 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
323 // Shift distances are both constant, try replacing with Ror if they
324 // add up to the register size.
325 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
326 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
327 // Shift distances are potentially of the form x and (reg_size - x).
328 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
329 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
330 // Shift distances are potentially of the form d and -d.
331 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
332 }
333 }
334 }
335 return false;
336}
337
338// Try replacing code looking like (x >>> #rdist OP x << #ldist):
339// UShr dst, x, #rdist
340// Shl tmp, x, #ldist
341// OP dst, dst, tmp
342// or like (x >>> #rdist OP x << #-ldist):
343// UShr dst, x, #rdist
344// Shl tmp, x, #-ldist
345// OP dst, dst, tmp
346// with
347// Ror dst, x, #rdist
348bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
349 HUShr* ushr,
350 HShl* shl) {
351 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
352 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
353 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
354 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
355 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
356 ReplaceRotateWithRor(op, ushr, shl);
357 return true;
358 }
359 return false;
360}
361
362// Replace code looking like (x >>> -d OP x << d):
363// Neg neg, d
364// UShr dst, x, neg
365// Shl tmp, x, d
366// OP dst, dst, tmp
367// with
368// Neg neg, d
369// Ror dst, x, neg
370// *** OR ***
371// Replace code looking like (x >>> d OP x << -d):
372// UShr dst, x, d
373// Neg neg, d
374// Shl tmp, x, neg
375// OP dst, dst, tmp
376// with
377// Ror dst, x, d
378bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
379 HUShr* ushr,
380 HShl* shl) {
381 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
382 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
383 bool neg_is_left = shl->GetRight()->IsNeg();
384 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
385 // And the shift distance being negated is the distance being shifted the other way.
386 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
387 ReplaceRotateWithRor(op, ushr, shl);
388 }
389 return false;
390}
391
392// Try replacing code looking like (x >>> d OP x << (#bits - d)):
393// UShr dst, x, d
394// Sub ld, #bits, d
395// Shl tmp, x, ld
396// OP dst, dst, tmp
397// with
398// Ror dst, x, d
399// *** OR ***
400// Replace code looking like (x >>> (#bits - d) OP x << d):
401// Sub rd, #bits, d
402// UShr dst, x, rd
403// Shl tmp, x, d
404// OP dst, dst, tmp
405// with
406// Neg neg, d
407// Ror dst, x, neg
408bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
409 HUShr* ushr,
410 HShl* shl) {
411 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
412 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
413 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
414 HInstruction* shl_shift = shl->GetRight();
415 HInstruction* ushr_shift = ushr->GetRight();
416 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
417 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
418 return ReplaceRotateWithRor(op, ushr, shl);
419 }
420 return false;
421}
422
Calin Juravle10e244f2015-01-26 18:54:32 +0000423void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
424 HInstruction* obj = null_check->InputAt(0);
425 if (!obj->CanBeNull()) {
426 null_check->ReplaceWith(obj);
427 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000428 if (stats_ != nullptr) {
429 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
430 }
431 }
432}
433
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100434bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
435 if (!input->CanBeNull()) {
436 return true;
437 }
438
Vladimir Marko46817b82016-03-29 12:21:58 +0100439 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
440 HInstruction* user = use.GetUser();
441 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100442 return true;
443 }
444 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100445
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100446 return false;
447}
448
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100449// Returns whether doing a type test between the class of `object` against `klass` has
450// a statically known outcome. The result of the test is stored in `outcome`.
451static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000452 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
453 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
454 ScopedObjectAccess soa(Thread::Current());
455 if (!obj_rti.IsValid()) {
456 // We run the simplifier before the reference type propagation so type info might not be
457 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100458 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000459 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100460
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100461 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100462 if (!class_rti.IsValid()) {
463 // Happens when the loaded class is unresolved.
464 return false;
465 }
466 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000467 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100468 *outcome = true;
469 return true;
470 } else if (obj_rti.IsExact()) {
471 // The test failed at compile time so will also fail at runtime.
472 *outcome = false;
473 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100474 } else if (!class_rti.IsInterface()
475 && !obj_rti.IsInterface()
476 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100477 // Different type hierarchy. The test will fail.
478 *outcome = false;
479 return true;
480 }
481 return false;
482}
483
484void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
485 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100486 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
487 if (load_class->NeedsAccessCheck()) {
488 // If we need to perform an access check we cannot remove the instruction.
489 return;
490 }
491
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100492 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 check_cast->ClearMustDoNullCheck();
494 }
495
496 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000497 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000498 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100499 return;
500 }
501
Vladimir Markoa65ed302016-03-14 21:21:29 +0000502 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
503 // the return value check with the `outcome` check, b/27651442 .
504 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700505 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100506 if (outcome) {
507 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000508 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700509 if (!load_class->HasUses()) {
510 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
511 // However, here we know that it cannot because the checkcast was successfull, hence
512 // the class was already loaded.
513 load_class->GetBlock()->RemoveInstruction(load_class);
514 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100515 } else {
516 // Don't do anything for exceptional cases for now. Ideally we should remove
517 // all instructions and blocks this instruction dominates.
518 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000519 }
520}
521
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100522void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100523 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100524 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
525 if (load_class->NeedsAccessCheck()) {
526 // If we need to perform an access check we cannot remove the instruction.
527 return;
528 }
529
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100530 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100531 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100532 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100533 instruction->ClearMustDoNullCheck();
534 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100535
536 HGraph* graph = GetGraph();
537 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000538 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100539 instruction->ReplaceWith(graph->GetIntConstant(0));
540 instruction->GetBlock()->RemoveInstruction(instruction);
541 RecordSimplification();
542 return;
543 }
544
Vladimir Marko24bd8952016-03-15 10:40:33 +0000545 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
546 // the return value check with the `outcome` check, b/27651442 .
547 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700548 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000549 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100550 if (outcome && can_be_null) {
551 // Type test will succeed, we just need a null test.
552 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
553 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
554 instruction->ReplaceWith(test);
555 } else {
556 // We've statically determined the result of the instanceof.
557 instruction->ReplaceWith(graph->GetIntConstant(outcome));
558 }
559 RecordSimplification();
560 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700561 if (outcome && !load_class->HasUses()) {
562 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
563 // However, here we know that it cannot because the instanceof check was successfull, hence
564 // the class was already loaded.
565 load_class->GetBlock()->RemoveInstruction(load_class);
566 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100567 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100568}
569
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100570void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
571 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100572 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100573 instruction->ClearValueCanBeNull();
574 }
575}
576
577void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
578 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100579 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100580 instruction->ClearValueCanBeNull();
581 }
582}
583
Anton Shaminbdd79352016-02-15 12:48:36 +0600584static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
585 HInstruction *lhs = cond->InputAt(0);
586 HInstruction *rhs = cond->InputAt(1);
587 switch (cond->GetKind()) {
588 case HInstruction::kEqual:
589 return new (arena) HEqual(rhs, lhs);
590 case HInstruction::kNotEqual:
591 return new (arena) HNotEqual(rhs, lhs);
592 case HInstruction::kLessThan:
593 return new (arena) HGreaterThan(rhs, lhs);
594 case HInstruction::kLessThanOrEqual:
595 return new (arena) HGreaterThanOrEqual(rhs, lhs);
596 case HInstruction::kGreaterThan:
597 return new (arena) HLessThan(rhs, lhs);
598 case HInstruction::kGreaterThanOrEqual:
599 return new (arena) HLessThanOrEqual(rhs, lhs);
600 case HInstruction::kBelow:
601 return new (arena) HAbove(rhs, lhs);
602 case HInstruction::kBelowOrEqual:
603 return new (arena) HAboveOrEqual(rhs, lhs);
604 case HInstruction::kAbove:
605 return new (arena) HBelow(rhs, lhs);
606 case HInstruction::kAboveOrEqual:
607 return new (arena) HBelowOrEqual(rhs, lhs);
608 default:
609 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
610 }
611 return nullptr;
612}
613
Aart Bik2767f4b2016-10-28 15:03:53 -0700614static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
615 if (input->GetType() == Primitive::kPrimBoolean) {
616 return true; // input has direct boolean type
617 } else if (cmp->GetUses().HasExactlyOneElement()) {
618 // Comparison also has boolean type if both its input and the instruction
619 // itself feed into the same phi node.
620 HInstruction* user = cmp->GetUses().front().GetUser();
621 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
622 }
623 return false;
624}
625
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000626void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100627 HInstruction* input_const = equal->GetConstantRight();
628 if (input_const != nullptr) {
629 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700630 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100631 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100632 // We are comparing the boolean to a constant which is of type int and can
633 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000634 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100635 // Replace (bool_value == true) with bool_value
636 equal->ReplaceWith(input_value);
637 block->RemoveInstruction(equal);
638 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000639 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700640 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500641 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
642 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100643 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100644 } else {
645 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
646 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
647 block->RemoveInstruction(equal);
648 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100649 }
Mark Mendellc4701932015-04-10 13:18:51 -0400650 } else {
651 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100652 }
Mark Mendellc4701932015-04-10 13:18:51 -0400653 } else {
654 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100655 }
656}
657
David Brazdil0d13fee2015-04-17 14:52:19 +0100658void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
659 HInstruction* input_const = not_equal->GetConstantRight();
660 if (input_const != nullptr) {
661 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700662 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100663 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100664 // We are comparing the boolean to a constant which is of type int and can
665 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000666 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700667 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500668 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
669 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100670 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000671 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100672 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100673 not_equal->ReplaceWith(input_value);
674 block->RemoveInstruction(not_equal);
675 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100676 } else {
677 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
678 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
679 block->RemoveInstruction(not_equal);
680 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100681 }
Mark Mendellc4701932015-04-10 13:18:51 -0400682 } else {
683 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100684 }
Mark Mendellc4701932015-04-10 13:18:51 -0400685 } else {
686 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100687 }
688}
689
690void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000691 HInstruction* input = bool_not->InputAt(0);
692 HInstruction* replace_with = nullptr;
693
694 if (input->IsIntConstant()) {
695 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000696 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000697 replace_with = GetGraph()->GetIntConstant(0);
698 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000699 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000700 replace_with = GetGraph()->GetIntConstant(1);
701 }
702 } else if (input->IsBooleanNot()) {
703 // Replace (!(!bool_value)) with bool_value.
704 replace_with = input->InputAt(0);
705 } else if (input->IsCondition() &&
706 // Don't change FP compares. The definition of compares involving
707 // NaNs forces the compares to be done as written by the user.
708 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
709 // Replace condition with its opposite.
710 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
711 }
712
713 if (replace_with != nullptr) {
714 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100715 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000716 RecordSimplification();
717 }
718}
719
720void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
721 HInstruction* replace_with = nullptr;
722 HInstruction* condition = select->GetCondition();
723 HInstruction* true_value = select->GetTrueValue();
724 HInstruction* false_value = select->GetFalseValue();
725
726 if (condition->IsBooleanNot()) {
727 // Change ((!cond) ? x : y) to (cond ? y : x).
728 condition = condition->InputAt(0);
729 std::swap(true_value, false_value);
730 select->ReplaceInput(false_value, 0);
731 select->ReplaceInput(true_value, 1);
732 select->ReplaceInput(condition, 2);
733 RecordSimplification();
734 }
735
736 if (true_value == false_value) {
737 // Replace (cond ? x : x) with (x).
738 replace_with = true_value;
739 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000740 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000741 // Replace (true ? x : y) with (x).
742 replace_with = true_value;
743 } else {
744 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000745 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000746 replace_with = false_value;
747 }
748 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000749 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000750 // Replace (cond ? true : false) with (cond).
751 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000752 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000753 // Replace (cond ? false : true) with (!cond).
754 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
755 }
756 }
757
758 if (replace_with != nullptr) {
759 select->ReplaceWith(replace_with);
760 select->GetBlock()->RemoveInstruction(select);
761 RecordSimplification();
762 }
763}
764
765void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
766 HInstruction* condition = instruction->InputAt(0);
767 if (condition->IsBooleanNot()) {
768 // Swap successors if input is negated.
769 instruction->ReplaceInput(condition->InputAt(0), 0);
770 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100771 RecordSimplification();
772 }
773}
774
Mingyao Yang0304e182015-01-30 16:41:29 -0800775void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
776 HInstruction* input = instruction->InputAt(0);
777 // If the array is a NewArray with constant size, replace the array length
778 // with the constant instruction. This helps the bounds check elimination phase.
779 if (input->IsNewArray()) {
780 input = input->InputAt(0);
781 if (input->IsIntConstant()) {
782 instruction->ReplaceWith(input);
783 }
784 }
785}
786
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000787void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000788 HInstruction* value = instruction->GetValue();
789 if (value->GetType() != Primitive::kPrimNot) return;
790
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100791 if (CanEnsureNotNullAt(value, instruction)) {
792 instruction->ClearValueCanBeNull();
793 }
794
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000795 if (value->IsArrayGet()) {
796 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
797 // If the code is just swapping elements in the array, no need for a type check.
798 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100799 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000800 }
801 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100802
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100803 if (value->IsNullConstant()) {
804 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100805 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100806 }
807
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100808 ScopedObjectAccess soa(Thread::Current());
809 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
810 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
811 if (!array_rti.IsValid()) {
812 return;
813 }
814
815 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
816 instruction->ClearNeedsTypeCheck();
817 return;
818 }
819
820 if (array_rti.IsObjectArray()) {
821 if (array_rti.IsExact()) {
822 instruction->ClearNeedsTypeCheck();
823 return;
824 }
825 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100826 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000827}
828
Vladimir Markob52bbde2016-02-12 12:06:05 +0000829static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100830 // Invariant: We should never generate a conversion to a Boolean value.
831 DCHECK_NE(Primitive::kPrimBoolean, result_type);
832
Vladimir Markob52bbde2016-02-12 12:06:05 +0000833 // Besides conversion to the same type, widening integral conversions are implicit,
834 // excluding conversions to long and the byte->char conversion where we need to
835 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
836 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100837 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
838 input_type == Primitive::kPrimByte ||
839 input_type == Primitive::kPrimShort ||
840 input_type == Primitive::kPrimChar)) ||
841 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
842 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
843 input_type == Primitive::kPrimByte)) ||
844 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000845}
846
847static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
848 // The conversion to a larger type is loss-less with the exception of two cases,
849 // - conversion to char, the only unsigned type, where we may lose some bits, and
850 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
851 // For integral to FP conversions this holds because the FP mantissa is large enough.
852 DCHECK_NE(input_type, result_type);
853 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
854 result_type != Primitive::kPrimChar &&
855 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
856}
857
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000858void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000859 HInstruction* input = instruction->GetInput();
860 Primitive::Type input_type = input->GetType();
861 Primitive::Type result_type = instruction->GetResultType();
862 if (IsTypeConversionImplicit(input_type, result_type)) {
863 // Remove the implicit conversion; this includes conversion to the same type.
864 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000865 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000866 RecordSimplification();
867 return;
868 }
869
870 if (input->IsTypeConversion()) {
871 HTypeConversion* input_conversion = input->AsTypeConversion();
872 HInstruction* original_input = input_conversion->GetInput();
873 Primitive::Type original_type = original_input->GetType();
874
875 // When the first conversion is lossless, a direct conversion from the original type
876 // to the final type yields the same result, even for a lossy second conversion, for
877 // example float->double->int or int->double->float.
878 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
879
880 // For integral conversions, see if the first conversion loses only bits that the second
881 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
882 // conversion yields the same result, for example long->int->short or int->char->short.
883 bool integral_conversions_with_non_widening_second =
884 Primitive::IsIntegralType(input_type) &&
885 Primitive::IsIntegralType(original_type) &&
886 Primitive::IsIntegralType(result_type) &&
887 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
888
889 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
890 // If the merged conversion is implicit, do the simplification unconditionally.
891 if (IsTypeConversionImplicit(original_type, result_type)) {
892 instruction->ReplaceWith(original_input);
893 instruction->GetBlock()->RemoveInstruction(instruction);
894 if (!input_conversion->HasUses()) {
895 // Don't wait for DCE.
896 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
897 }
898 RecordSimplification();
899 return;
900 }
901 // Otherwise simplify only if the first conversion has no other use.
902 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
903 input_conversion->ReplaceWith(original_input);
904 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
905 RecordSimplification();
906 return;
907 }
908 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000909 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000910 DCHECK(Primitive::IsIntegralType(input_type));
911 HAnd* input_and = input->AsAnd();
912 HConstant* constant = input_and->GetConstantRight();
913 if (constant != nullptr) {
914 int64_t value = Int64FromConstant(constant);
915 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
916 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
917 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
918 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000919 HInstruction* original_input = input_and->GetLeastConstantLeft();
920 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
921 instruction->ReplaceWith(original_input);
922 instruction->GetBlock()->RemoveInstruction(instruction);
923 RecordSimplification();
924 return;
925 } else if (input->HasOnlyOneNonEnvironmentUse()) {
926 input_and->ReplaceWith(original_input);
927 input_and->GetBlock()->RemoveInstruction(input_and);
928 RecordSimplification();
929 return;
930 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000931 }
932 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000933 }
934}
935
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000936void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
937 HConstant* input_cst = instruction->GetConstantRight();
938 HInstruction* input_other = instruction->GetLeastConstantLeft();
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600939 bool integral_type = Primitive::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +0000940 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000941 // Replace code looking like
942 // ADD dst, src, 0
943 // with
944 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600945 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
946 // `x` is `-0.0`, the former expression yields `0.0`, while the later
947 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600948 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +0600949 instruction->ReplaceWith(input_other);
950 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100951 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600952 return;
953 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100954 }
955
956 HInstruction* left = instruction->GetLeft();
957 HInstruction* right = instruction->GetRight();
958 bool left_is_neg = left->IsNeg();
959 bool right_is_neg = right->IsNeg();
960
961 if (left_is_neg && right_is_neg) {
962 if (TryMoveNegOnInputsAfterBinop(instruction)) {
963 return;
964 }
965 }
966
967 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
968 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
969 // Replace code looking like
970 // NEG tmp, b
971 // ADD dst, a, tmp
972 // with
973 // SUB dst, a, b
974 // We do not perform the optimization if the input negation has environment
975 // uses or multiple non-environment uses as it could lead to worse code. In
976 // particular, we do not want the live range of `b` to be extended if we are
977 // not sure the initial 'NEG' instruction can be removed.
978 HInstruction* other = left_is_neg ? right : left;
979 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
980 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
981 RecordSimplification();
982 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000983 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000984 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000985
Anton Kirilove14dc862016-05-13 17:56:15 +0100986 if (TryReplaceWithRotate(instruction)) {
987 return;
988 }
989
990 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
991 // so no need to return.
992 TryHandleAssociativeAndCommutativeOperation(instruction);
993
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600994 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +0100995 TrySubtractionChainSimplification(instruction)) {
996 return;
997 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600998
999 if (integral_type) {
1000 // Replace code patterns looking like
1001 // SUB dst1, x, y SUB dst1, x, y
1002 // ADD dst2, dst1, y ADD dst2, y, dst1
1003 // with
1004 // SUB dst1, x, y
1005 // ADD instruction is not needed in this case, we may use
1006 // one of inputs of SUB instead.
1007 if (left->IsSub() && left->InputAt(1) == right) {
1008 instruction->ReplaceWith(left->InputAt(0));
1009 RecordSimplification();
1010 instruction->GetBlock()->RemoveInstruction(instruction);
1011 return;
1012 } else if (right->IsSub() && right->InputAt(1) == left) {
1013 instruction->ReplaceWith(right->InputAt(0));
1014 RecordSimplification();
1015 instruction->GetBlock()->RemoveInstruction(instruction);
1016 return;
1017 }
1018 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001019}
1020
1021void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1022 HConstant* input_cst = instruction->GetConstantRight();
1023 HInstruction* input_other = instruction->GetLeastConstantLeft();
1024
Vladimir Marko452c1b62015-09-25 14:44:17 +01001025 if (input_cst != nullptr) {
1026 int64_t value = Int64FromConstant(input_cst);
1027 if (value == -1) {
1028 // Replace code looking like
1029 // AND dst, src, 0xFFF...FF
1030 // with
1031 // src
1032 instruction->ReplaceWith(input_other);
1033 instruction->GetBlock()->RemoveInstruction(instruction);
1034 RecordSimplification();
1035 return;
1036 }
1037 // Eliminate And from UShr+And if the And-mask contains all the bits that
1038 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1039 // precisely clears the shifted-in sign bits.
1040 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1041 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1042 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1043 size_t num_tail_bits_set = CTZ(value + 1);
1044 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1045 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1046 instruction->ReplaceWith(input_other);
1047 instruction->GetBlock()->RemoveInstruction(instruction);
1048 RecordSimplification();
1049 return;
1050 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1051 input_other->HasOnlyOneNonEnvironmentUse()) {
1052 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1053 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1054 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1055 input_other->InputAt(0),
1056 input_other->InputAt(1),
1057 input_other->GetDexPc());
1058 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1059 input_other->GetBlock()->RemoveInstruction(input_other);
1060 RecordSimplification();
1061 return;
1062 }
1063 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001064 }
1065
1066 // We assume that GVN has run before, so we only perform a pointer comparison.
1067 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001068 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001069 if (instruction->GetLeft() == instruction->GetRight()) {
1070 // Replace code looking like
1071 // AND dst, src, src
1072 // with
1073 // src
1074 instruction->ReplaceWith(instruction->GetLeft());
1075 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001076 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001077 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001078 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001079
Anton Kirilove14dc862016-05-13 17:56:15 +01001080 if (TryDeMorganNegationFactoring(instruction)) {
1081 return;
1082 }
1083
1084 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1085 // so no need to return.
1086 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001087}
1088
Mark Mendellc4701932015-04-10 13:18:51 -04001089void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1090 VisitCondition(condition);
1091}
1092
1093void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1094 VisitCondition(condition);
1095}
1096
1097void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1098 VisitCondition(condition);
1099}
1100
1101void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1102 VisitCondition(condition);
1103}
1104
Anton Shaminbdd79352016-02-15 12:48:36 +06001105void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1106 VisitCondition(condition);
1107}
1108
1109void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1110 VisitCondition(condition);
1111}
1112
1113void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1114 VisitCondition(condition);
1115}
1116
1117void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1118 VisitCondition(condition);
1119}
Aart Bike9f37602015-10-09 11:15:55 -07001120
Mark Mendellc4701932015-04-10 13:18:51 -04001121void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001122 // Reverse condition if left is constant. Our code generators prefer constant
1123 // on the right hand side.
1124 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1125 HBasicBlock* block = condition->GetBlock();
1126 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1127 // If it is a fp we must set the opposite bias.
1128 if (replacement != nullptr) {
1129 if (condition->IsLtBias()) {
1130 replacement->SetBias(ComparisonBias::kGtBias);
1131 } else if (condition->IsGtBias()) {
1132 replacement->SetBias(ComparisonBias::kLtBias);
1133 }
1134 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1135 RecordSimplification();
1136
1137 condition = replacement;
1138 }
1139 }
Mark Mendellc4701932015-04-10 13:18:51 -04001140
Mark Mendellc4701932015-04-10 13:18:51 -04001141 HInstruction* left = condition->GetLeft();
1142 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001143
1144 // Try to fold an HCompare into this HCondition.
1145
Mark Mendellc4701932015-04-10 13:18:51 -04001146 // We can only replace an HCondition which compares a Compare to 0.
1147 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1148 // condition with a long, float or double comparison as input.
1149 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1150 // Conversion is not possible.
1151 return;
1152 }
1153
1154 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001155 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001156 // Someone else also wants the result of the compare.
1157 return;
1158 }
1159
Vladimir Marko46817b82016-03-29 12:21:58 +01001160 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001161 // There is a reference to the compare result in an environment. Do we really need it?
1162 if (GetGraph()->IsDebuggable()) {
1163 return;
1164 }
1165
1166 // We have to ensure that there are no deopt points in the sequence.
1167 if (left->HasAnyEnvironmentUseBefore(condition)) {
1168 return;
1169 }
1170 }
1171
1172 // Clean up any environment uses from the HCompare, if any.
1173 left->RemoveEnvironmentUsers();
1174
1175 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1176 condition->SetBias(left->AsCompare()->GetBias());
1177
1178 // Replace the operands of the HCondition.
1179 condition->ReplaceInput(left->InputAt(0), 0);
1180 condition->ReplaceInput(left->InputAt(1), 1);
1181
1182 // Remove the HCompare.
1183 left->GetBlock()->RemoveInstruction(left);
1184
1185 RecordSimplification();
1186}
1187
Andreas Gampe9186ced2016-12-12 14:28:21 -08001188// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1189static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1190 // True, if the most significant bits of divisor are 0.
1191 return ((divisor & 0x7fffff) == 0);
1192}
1193
1194// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1195static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1196 // True, if the most significant bits of divisor are 0.
1197 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1198}
1199
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001200void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1201 HConstant* input_cst = instruction->GetConstantRight();
1202 HInstruction* input_other = instruction->GetLeastConstantLeft();
1203 Primitive::Type type = instruction->GetType();
1204
1205 if ((input_cst != nullptr) && input_cst->IsOne()) {
1206 // Replace code looking like
1207 // DIV dst, src, 1
1208 // with
1209 // src
1210 instruction->ReplaceWith(input_other);
1211 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001212 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001213 return;
1214 }
1215
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001216 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001217 // Replace code looking like
1218 // DIV dst, src, -1
1219 // with
1220 // NEG dst, src
1221 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001222 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001223 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001224 return;
1225 }
1226
1227 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1228 // Try replacing code looking like
1229 // DIV dst, src, constant
1230 // with
1231 // MUL dst, src, 1 / constant
1232 HConstant* reciprocal = nullptr;
1233 if (type == Primitive::Primitive::kPrimDouble) {
1234 double value = input_cst->AsDoubleConstant()->GetValue();
1235 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1236 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1237 }
1238 } else {
1239 DCHECK_EQ(type, Primitive::kPrimFloat);
1240 float value = input_cst->AsFloatConstant()->GetValue();
1241 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1242 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1243 }
1244 }
1245
1246 if (reciprocal != nullptr) {
1247 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1248 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1249 RecordSimplification();
1250 return;
1251 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001252 }
1253}
1254
1255void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1256 HConstant* input_cst = instruction->GetConstantRight();
1257 HInstruction* input_other = instruction->GetLeastConstantLeft();
1258 Primitive::Type type = instruction->GetType();
1259 HBasicBlock* block = instruction->GetBlock();
1260 ArenaAllocator* allocator = GetGraph()->GetArena();
1261
1262 if (input_cst == nullptr) {
1263 return;
1264 }
1265
1266 if (input_cst->IsOne()) {
1267 // Replace code looking like
1268 // MUL dst, src, 1
1269 // with
1270 // src
1271 instruction->ReplaceWith(input_other);
1272 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001273 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001274 return;
1275 }
1276
1277 if (input_cst->IsMinusOne() &&
1278 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1279 // Replace code looking like
1280 // MUL dst, src, -1
1281 // with
1282 // NEG dst, src
1283 HNeg* neg = new (allocator) HNeg(type, input_other);
1284 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001285 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001286 return;
1287 }
1288
1289 if (Primitive::IsFloatingPointType(type) &&
1290 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1291 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1292 // Replace code looking like
1293 // FP_MUL dst, src, 2.0
1294 // with
1295 // FP_ADD dst, src, src
1296 // The 'int' and 'long' cases are handled below.
1297 block->ReplaceAndRemoveInstructionWith(instruction,
1298 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001299 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001300 return;
1301 }
1302
1303 if (Primitive::IsIntOrLongType(type)) {
1304 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001305 // Even though constant propagation also takes care of the zero case, other
1306 // optimizations can lead to having a zero multiplication.
1307 if (factor == 0) {
1308 // Replace code looking like
1309 // MUL dst, src, 0
1310 // with
1311 // 0
1312 instruction->ReplaceWith(input_cst);
1313 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001314 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001315 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001316 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001317 // Replace code looking like
1318 // MUL dst, src, pow_of_2
1319 // with
1320 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001321 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001322 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001323 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001324 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001325 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001326 } else if (IsPowerOfTwo(factor - 1)) {
1327 // Transform code looking like
1328 // MUL dst, src, (2^n + 1)
1329 // into
1330 // SHL tmp, src, n
1331 // ADD dst, src, tmp
1332 HShl* shl = new (allocator) HShl(type,
1333 input_other,
1334 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1335 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1336
1337 block->InsertInstructionBefore(shl, instruction);
1338 block->ReplaceAndRemoveInstructionWith(instruction, add);
1339 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001340 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001341 } else if (IsPowerOfTwo(factor + 1)) {
1342 // Transform code looking like
1343 // MUL dst, src, (2^n - 1)
1344 // into
1345 // SHL tmp, src, n
1346 // SUB dst, tmp, src
1347 HShl* shl = new (allocator) HShl(type,
1348 input_other,
1349 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1350 HSub* sub = new (allocator) HSub(type, shl, input_other);
1351
1352 block->InsertInstructionBefore(shl, instruction);
1353 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1354 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001355 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001356 }
1357 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001358
1359 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1360 // so no need to return.
1361 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001362}
1363
Alexandre Rames188d4312015-04-09 18:30:21 +01001364void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1365 HInstruction* input = instruction->GetInput();
1366 if (input->IsNeg()) {
1367 // Replace code looking like
1368 // NEG tmp, src
1369 // NEG dst, tmp
1370 // with
1371 // src
1372 HNeg* previous_neg = input->AsNeg();
1373 instruction->ReplaceWith(previous_neg->GetInput());
1374 instruction->GetBlock()->RemoveInstruction(instruction);
1375 // We perform the optimization even if the input negation has environment
1376 // uses since it allows removing the current instruction. But we only delete
1377 // the input negation only if it is does not have any uses left.
1378 if (!previous_neg->HasUses()) {
1379 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1380 }
1381 RecordSimplification();
1382 return;
1383 }
1384
Serguei Katkov339dfc22015-04-20 12:29:32 +06001385 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1386 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001387 // Replace code looking like
1388 // SUB tmp, a, b
1389 // NEG dst, tmp
1390 // with
1391 // SUB dst, b, a
1392 // We do not perform the optimization if the input subtraction has
1393 // environment uses or multiple non-environment uses as it could lead to
1394 // worse code. In particular, we do not want the live ranges of `a` and `b`
1395 // to be extended if we are not sure the initial 'SUB' instruction can be
1396 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001397 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001398 HSub* sub = input->AsSub();
1399 HSub* new_sub =
1400 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1401 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1402 if (!sub->HasUses()) {
1403 sub->GetBlock()->RemoveInstruction(sub);
1404 }
1405 RecordSimplification();
1406 }
1407}
1408
1409void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1410 HInstruction* input = instruction->GetInput();
1411 if (input->IsNot()) {
1412 // Replace code looking like
1413 // NOT tmp, src
1414 // NOT dst, tmp
1415 // with
1416 // src
1417 // We perform the optimization even if the input negation has environment
1418 // uses since it allows removing the current instruction. But we only delete
1419 // the input negation only if it is does not have any uses left.
1420 HNot* previous_not = input->AsNot();
1421 instruction->ReplaceWith(previous_not->GetInput());
1422 instruction->GetBlock()->RemoveInstruction(instruction);
1423 if (!previous_not->HasUses()) {
1424 previous_not->GetBlock()->RemoveInstruction(previous_not);
1425 }
1426 RecordSimplification();
1427 }
1428}
1429
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001430void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1431 HConstant* input_cst = instruction->GetConstantRight();
1432 HInstruction* input_other = instruction->GetLeastConstantLeft();
1433
Roland Levillain1a653882016-03-18 18:05:57 +00001434 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001435 // Replace code looking like
1436 // OR dst, src, 0
1437 // with
1438 // src
1439 instruction->ReplaceWith(input_other);
1440 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001441 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001442 return;
1443 }
1444
1445 // We assume that GVN has run before, so we only perform a pointer comparison.
1446 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001447 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001448 if (instruction->GetLeft() == instruction->GetRight()) {
1449 // Replace code looking like
1450 // OR dst, src, src
1451 // with
1452 // src
1453 instruction->ReplaceWith(instruction->GetLeft());
1454 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001455 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001456 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001457 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001458
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001459 if (TryDeMorganNegationFactoring(instruction)) return;
1460
Anton Kirilove14dc862016-05-13 17:56:15 +01001461 if (TryReplaceWithRotate(instruction)) {
1462 return;
1463 }
1464
1465 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1466 // so no need to return.
1467 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001468}
1469
1470void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1471 VisitShift(instruction);
1472}
1473
1474void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1475 VisitShift(instruction);
1476}
1477
1478void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1479 HConstant* input_cst = instruction->GetConstantRight();
1480 HInstruction* input_other = instruction->GetLeastConstantLeft();
1481
Serguei Katkov115b53f2015-08-05 17:03:30 +06001482 Primitive::Type type = instruction->GetType();
1483 if (Primitive::IsFloatingPointType(type)) {
1484 return;
1485 }
1486
Roland Levillain1a653882016-03-18 18:05:57 +00001487 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001488 // Replace code looking like
1489 // SUB dst, src, 0
1490 // with
1491 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001492 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1493 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1494 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001495 instruction->ReplaceWith(input_other);
1496 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001497 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001498 return;
1499 }
1500
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001501 HBasicBlock* block = instruction->GetBlock();
1502 ArenaAllocator* allocator = GetGraph()->GetArena();
1503
Alexandre Rames188d4312015-04-09 18:30:21 +01001504 HInstruction* left = instruction->GetLeft();
1505 HInstruction* right = instruction->GetRight();
1506 if (left->IsConstant()) {
1507 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001508 // Replace code looking like
1509 // SUB dst, 0, src
1510 // with
1511 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001512 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001513 // `x` is `0.0`, the former expression yields `0.0`, while the later
1514 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001515 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001516 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001517 RecordSimplification();
1518 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001519 }
1520 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001521
1522 if (left->IsNeg() && right->IsNeg()) {
1523 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1524 return;
1525 }
1526 }
1527
1528 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1529 // Replace code looking like
1530 // NEG tmp, b
1531 // SUB dst, a, tmp
1532 // with
1533 // ADD dst, a, b
1534 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1535 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1536 RecordSimplification();
1537 right->GetBlock()->RemoveInstruction(right);
1538 return;
1539 }
1540
1541 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1542 // Replace code looking like
1543 // NEG tmp, a
1544 // SUB dst, tmp, b
1545 // with
1546 // ADD tmp, a, b
1547 // NEG dst, tmp
1548 // The second version is not intrinsically better, but enables more
1549 // transformations.
1550 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1551 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1552 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1553 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1554 instruction->ReplaceWith(neg);
1555 instruction->GetBlock()->RemoveInstruction(instruction);
1556 RecordSimplification();
1557 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001558 return;
1559 }
1560
1561 if (TrySubtractionChainSimplification(instruction)) {
1562 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001563 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001564
1565 if (left->IsAdd()) {
1566 // Replace code patterns looking like
1567 // ADD dst1, x, y ADD dst1, x, y
1568 // SUB dst2, dst1, y SUB dst2, dst1, x
1569 // with
1570 // ADD dst1, x, y
1571 // SUB instruction is not needed in this case, we may use
1572 // one of inputs of ADD instead.
1573 // It is applicable to integral types only.
1574 DCHECK(Primitive::IsIntegralType(type));
1575 if (left->InputAt(1) == right) {
1576 instruction->ReplaceWith(left->InputAt(0));
1577 RecordSimplification();
1578 instruction->GetBlock()->RemoveInstruction(instruction);
1579 return;
1580 } else if (left->InputAt(0) == right) {
1581 instruction->ReplaceWith(left->InputAt(1));
1582 RecordSimplification();
1583 instruction->GetBlock()->RemoveInstruction(instruction);
1584 return;
1585 }
1586 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001587}
1588
1589void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1590 VisitShift(instruction);
1591}
1592
1593void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1594 HConstant* input_cst = instruction->GetConstantRight();
1595 HInstruction* input_other = instruction->GetLeastConstantLeft();
1596
Roland Levillain1a653882016-03-18 18:05:57 +00001597 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001598 // Replace code looking like
1599 // XOR dst, src, 0
1600 // with
1601 // src
1602 instruction->ReplaceWith(input_other);
1603 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001604 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001605 return;
1606 }
1607
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001608 if ((input_cst != nullptr) && input_cst->IsOne()
1609 && input_other->GetType() == Primitive::kPrimBoolean) {
1610 // Replace code looking like
1611 // XOR dst, src, 1
1612 // with
1613 // BOOLEAN_NOT dst, src
1614 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1615 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1616 RecordSimplification();
1617 return;
1618 }
1619
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001620 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1621 // Replace code looking like
1622 // XOR dst, src, 0xFFF...FF
1623 // with
1624 // NOT dst, src
1625 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1626 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001627 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001628 return;
1629 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001630
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001631 HInstruction* left = instruction->GetLeft();
1632 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001633 if (((left->IsNot() && right->IsNot()) ||
1634 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001635 left->HasOnlyOneNonEnvironmentUse() &&
1636 right->HasOnlyOneNonEnvironmentUse()) {
1637 // Replace code looking like
1638 // NOT nota, a
1639 // NOT notb, b
1640 // XOR dst, nota, notb
1641 // with
1642 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001643 instruction->ReplaceInput(left->InputAt(0), 0);
1644 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001645 left->GetBlock()->RemoveInstruction(left);
1646 right->GetBlock()->RemoveInstruction(right);
1647 RecordSimplification();
1648 return;
1649 }
1650
Anton Kirilove14dc862016-05-13 17:56:15 +01001651 if (TryReplaceWithRotate(instruction)) {
1652 return;
1653 }
1654
1655 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1656 // so no need to return.
1657 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001658}
1659
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001660void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1661 HInstruction* argument = instruction->InputAt(1);
1662 HInstruction* receiver = instruction->InputAt(0);
1663 if (receiver == argument) {
1664 // Because String.equals is an instance call, the receiver is
1665 // a null check if we don't know it's null. The argument however, will
1666 // be the actual object. So we cannot end up in a situation where both
1667 // are equal but could be null.
1668 DCHECK(CanEnsureNotNullAt(argument, instruction));
1669 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1670 instruction->GetBlock()->RemoveInstruction(instruction);
1671 } else {
1672 StringEqualsOptimizations optimizations(instruction);
1673 if (CanEnsureNotNullAt(argument, instruction)) {
1674 optimizations.SetArgumentNotNull();
1675 }
1676 ScopedObjectAccess soa(Thread::Current());
1677 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1678 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1679 optimizations.SetArgumentIsString();
1680 }
1681 }
1682}
1683
Roland Levillain22c49222016-03-18 14:04:28 +00001684void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1685 bool is_left,
1686 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001687 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001688 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001689 HInstruction* value = invoke->InputAt(0);
1690 HInstruction* distance = invoke->InputAt(1);
1691 // Replace the invoke with an HRor.
1692 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001693 // Unconditionally set the type of the negated distance to `int`,
1694 // as shift and rotate operations expect a 32-bit (or narrower)
1695 // value for their distance input.
1696 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001697 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1698 }
Roland Levillain22c49222016-03-18 14:04:28 +00001699 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001700 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1701 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001702 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001703 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1704 clinit->GetBlock()->RemoveInstruction(clinit);
1705 HInstruction* ldclass = clinit->InputAt(0);
1706 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1707 ldclass->GetBlock()->RemoveInstruction(ldclass);
1708 }
1709 }
1710}
1711
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001712static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1713 if (potential_length->IsArrayLength()) {
1714 return potential_length->InputAt(0) == potential_array;
1715 }
1716
1717 if (potential_array->IsNewArray()) {
1718 return potential_array->InputAt(0) == potential_length;
1719 }
1720
1721 return false;
1722}
1723
1724void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1725 HInstruction* source = instruction->InputAt(0);
1726 HInstruction* destination = instruction->InputAt(2);
1727 HInstruction* count = instruction->InputAt(4);
1728 SystemArrayCopyOptimizations optimizations(instruction);
1729 if (CanEnsureNotNullAt(source, instruction)) {
1730 optimizations.SetSourceIsNotNull();
1731 }
1732 if (CanEnsureNotNullAt(destination, instruction)) {
1733 optimizations.SetDestinationIsNotNull();
1734 }
1735 if (destination == source) {
1736 optimizations.SetDestinationIsSource();
1737 }
1738
1739 if (IsArrayLengthOf(count, source)) {
1740 optimizations.SetCountIsSourceLength();
1741 }
1742
1743 if (IsArrayLengthOf(count, destination)) {
1744 optimizations.SetCountIsDestinationLength();
1745 }
1746
1747 {
1748 ScopedObjectAccess soa(Thread::Current());
1749 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1750 if (destination_rti.IsValid()) {
1751 if (destination_rti.IsObjectArray()) {
1752 if (destination_rti.IsExact()) {
1753 optimizations.SetDoesNotNeedTypeCheck();
1754 }
1755 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001756 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001757 if (destination_rti.IsPrimitiveArrayClass()) {
1758 optimizations.SetDestinationIsPrimitiveArray();
1759 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1760 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001761 }
1762 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001763 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1764 if (source_rti.IsValid()) {
1765 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1766 optimizations.SetDoesNotNeedTypeCheck();
1767 }
1768 if (source_rti.IsPrimitiveArrayClass()) {
1769 optimizations.SetSourceIsPrimitiveArray();
1770 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1771 optimizations.SetSourceIsNonPrimitiveArray();
1772 }
1773 }
1774 }
1775}
1776
Roland Levillaina5c4a402016-03-15 15:02:50 +00001777void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1778 bool is_signum,
1779 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001780 DCHECK(invoke->IsInvokeStaticOrDirect());
1781 uint32_t dex_pc = invoke->GetDexPc();
1782 HInstruction* left = invoke->InputAt(0);
1783 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001784 if (!is_signum) {
1785 right = invoke->InputAt(1);
1786 } else if (type == Primitive::kPrimLong) {
1787 right = GetGraph()->GetLongConstant(0);
1788 } else {
1789 right = GetGraph()->GetIntConstant(0);
1790 }
1791 HCompare* compare = new (GetGraph()->GetArena())
1792 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1793 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1794}
1795
Aart Bik75a38b22016-02-17 10:41:50 -08001796void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1797 DCHECK(invoke->IsInvokeStaticOrDirect());
1798 uint32_t dex_pc = invoke->GetDexPc();
1799 // IsNaN(x) is the same as x != x.
1800 HInstruction* x = invoke->InputAt(0);
1801 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001802 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001803 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1804}
1805
Aart Bik2a6aad92016-02-25 11:32:32 -08001806void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1807 DCHECK(invoke->IsInvokeStaticOrDirect());
1808 uint32_t dex_pc = invoke->GetDexPc();
1809 HInstruction* x = invoke->InputAt(0);
1810 Primitive::Type type = x->GetType();
1811 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1812 HInstruction* nan;
1813 if (type == Primitive::kPrimDouble) {
1814 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1815 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1816 kNeedsEnvironmentOrCache,
1817 kNoSideEffects,
1818 kNoThrow);
1819 } else {
1820 DCHECK_EQ(type, Primitive::kPrimFloat);
1821 nan = GetGraph()->GetIntConstant(0x7fc00000);
1822 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1823 kNeedsEnvironmentOrCache,
1824 kNoSideEffects,
1825 kNoThrow);
1826 }
1827 // Test IsNaN(x), which is the same as x != x.
1828 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1829 condition->SetBias(ComparisonBias::kLtBias);
1830 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1831 // Select between the two.
1832 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1833 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1834 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1835}
1836
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001837void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1838 HInstruction* str = invoke->InputAt(0);
1839 HInstruction* index = invoke->InputAt(1);
1840 uint32_t dex_pc = invoke->GetDexPc();
1841 ArenaAllocator* arena = GetGraph()->GetArena();
1842 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1843 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1844 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1845 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1846 HBoundsCheck* bounds_check =
1847 new (arena) HBoundsCheck(index, length, dex_pc, invoke->GetDexMethodIndex());
1848 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
1849 HArrayGet* array_get =
1850 new (arena) HArrayGet(str, index, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
1851 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1852 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1853 GetGraph()->SetHasBoundsChecks(true);
1854}
1855
Vladimir Markodce016e2016-04-28 13:10:02 +01001856void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1857 HInstruction* str = invoke->InputAt(0);
1858 uint32_t dex_pc = invoke->GetDexPc();
1859 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1860 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001861 HArrayLength* length =
1862 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001863 HInstruction* replacement;
1864 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1865 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1866 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1867 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1868 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1869 replacement = equal;
1870 } else {
1871 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1872 replacement = length;
1873 }
1874 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1875}
1876
Aart Bikff7d89c2016-11-07 08:49:28 -08001877// This method should only be used on intrinsics whose sole way of throwing an
1878// exception is raising a NPE when the nth argument is null. If that argument
1879// is provably non-null, we can clear the flag.
1880void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
1881 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08001882 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08001883 invoke->SetCanThrow(false);
1884 }
1885}
1886
Aart Bik71bf7b42016-11-16 10:17:46 -08001887// Methods that return "this" can replace the returned value with the receiver.
1888void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
1889 if (invoke->HasUses()) {
1890 HInstruction* receiver = invoke->InputAt(0);
1891 invoke->ReplaceWith(receiver);
1892 RecordSimplification();
1893 }
1894}
1895
1896// Helper method for StringBuffer escape analysis.
1897static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
1898 if (user->IsInvokeStaticOrDirect()) {
1899 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08001900 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
1901 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08001902 user->InputAt(0) == reference;
1903 } else if (user->IsInvokeVirtual()) {
1904 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
1905 case Intrinsics::kStringBufferLength:
1906 case Intrinsics::kStringBufferToString:
1907 DCHECK_EQ(user->InputAt(0), reference);
1908 return true;
1909 case Intrinsics::kStringBufferAppend:
1910 // Returns "this", so only okay if no further uses.
1911 DCHECK_EQ(user->InputAt(0), reference);
1912 DCHECK_NE(user->InputAt(1), reference);
1913 return !user->HasUses();
1914 default:
1915 break;
1916 }
1917 }
1918 return false;
1919}
1920
1921// Certain allocation intrinsics are not removed by dead code elimination
1922// because of potentially throwing an OOM exception or other side effects.
1923// This method removes such intrinsics when special circumstances allow.
1924void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
1925 if (!invoke->HasUses()) {
1926 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
1927 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
1928 // call does not escape since only thread-local synchronization may be removed.
1929 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
1930 HInstruction* receiver = invoke->InputAt(0);
1931 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
1932 invoke->GetBlock()->RemoveInstruction(invoke);
1933 RecordSimplification();
1934 }
1935 }
1936}
1937
Aart Bik11932592016-03-08 12:42:25 -08001938void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1939 uint32_t dex_pc = invoke->GetDexPc();
1940 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1941 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1942}
1943
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001944void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001945 switch (instruction->GetIntrinsic()) {
1946 case Intrinsics::kStringEquals:
1947 SimplifyStringEquals(instruction);
1948 break;
1949 case Intrinsics::kSystemArrayCopy:
1950 SimplifySystemArrayCopy(instruction);
1951 break;
1952 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001953 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1954 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001955 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001956 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001957 break;
1958 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001959 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1960 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001961 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001962 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001963 break;
1964 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001965 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1966 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001967 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001968 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001969 break;
1970 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001971 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1972 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001973 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001974 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001975 break;
1976 case Intrinsics::kFloatIsNaN:
1977 case Intrinsics::kDoubleIsNaN:
1978 SimplifyIsNaN(instruction);
1979 break;
1980 case Intrinsics::kFloatFloatToIntBits:
1981 case Intrinsics::kDoubleDoubleToLongBits:
1982 SimplifyFP2Int(instruction);
1983 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001984 case Intrinsics::kStringCharAt:
1985 SimplifyStringCharAt(instruction);
1986 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01001987 case Intrinsics::kStringIsEmpty:
1988 case Intrinsics::kStringLength:
1989 SimplifyStringIsEmptyOrLength(instruction);
1990 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08001991 case Intrinsics::kStringStringIndexOf:
1992 case Intrinsics::kStringStringIndexOfAfter:
1993 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
1994 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08001995 case Intrinsics::kStringBufferAppend:
1996 case Intrinsics::kStringBuilderAppend:
1997 SimplifyReturnThis(instruction);
1998 break;
1999 case Intrinsics::kStringBufferToString:
2000 case Intrinsics::kStringBuilderToString:
2001 SimplifyAllocationIntrinsic(instruction);
2002 break;
Aart Bik11932592016-03-08 12:42:25 -08002003 case Intrinsics::kUnsafeLoadFence:
2004 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2005 break;
2006 case Intrinsics::kUnsafeStoreFence:
2007 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2008 break;
2009 case Intrinsics::kUnsafeFullFence:
2010 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2011 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002012 default:
2013 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002014 }
2015}
2016
Aart Bikbb245d12015-10-19 11:05:03 -07002017void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2018 HInstruction* cond = deoptimize->InputAt(0);
2019 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002020 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002021 // Never deopt: instruction can be removed.
2022 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2023 } else {
2024 // Always deopt.
2025 }
2026 }
2027}
2028
Anton Kirilove14dc862016-05-13 17:56:15 +01002029// Replace code looking like
2030// OP y, x, const1
2031// OP z, y, const2
2032// with
2033// OP z, x, const3
2034// where OP is both an associative and a commutative operation.
2035bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2036 HBinaryOperation* instruction) {
2037 DCHECK(instruction->IsCommutative());
2038
2039 if (!Primitive::IsIntegralType(instruction->GetType())) {
2040 return false;
2041 }
2042
2043 HInstruction* left = instruction->GetLeft();
2044 HInstruction* right = instruction->GetRight();
2045 // Variable names as described above.
2046 HConstant* const2;
2047 HBinaryOperation* y;
2048
2049 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2050 const2 = right->AsConstant();
2051 y = left->AsBinaryOperation();
2052 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2053 const2 = left->AsConstant();
2054 y = right->AsBinaryOperation();
2055 } else {
2056 // The node does not match the pattern.
2057 return false;
2058 }
2059
2060 // If `y` has more than one use, we do not perform the optimization
2061 // because it might increase code size (e.g. if the new constant is
2062 // no longer encodable as an immediate operand in the target ISA).
2063 if (!y->HasOnlyOneNonEnvironmentUse()) {
2064 return false;
2065 }
2066
2067 // GetConstantRight() can return both left and right constants
2068 // for commutative operations.
2069 HConstant* const1 = y->GetConstantRight();
2070 if (const1 == nullptr) {
2071 return false;
2072 }
2073
2074 instruction->ReplaceInput(const1, 0);
2075 instruction->ReplaceInput(const2, 1);
2076 HConstant* const3 = instruction->TryStaticEvaluation();
2077 DCHECK(const3 != nullptr);
2078 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2079 instruction->ReplaceInput(const3, 1);
2080 RecordSimplification();
2081 return true;
2082}
2083
2084static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2085 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2086}
2087
2088// Helper function that performs addition statically, considering the result type.
2089static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
2090 // Use the Compute() method for consistency with TryStaticEvaluation().
2091 if (type == Primitive::kPrimInt) {
2092 return HAdd::Compute<int32_t>(x, y);
2093 } else {
2094 DCHECK_EQ(type, Primitive::kPrimLong);
2095 return HAdd::Compute<int64_t>(x, y);
2096 }
2097}
2098
2099// Helper function that handles the child classes of HConstant
2100// and returns an integer with the appropriate sign.
2101static int64_t GetValue(HConstant* constant, bool is_negated) {
2102 int64_t ret = Int64FromConstant(constant);
2103 return is_negated ? -ret : ret;
2104}
2105
2106// Replace code looking like
2107// OP1 y, x, const1
2108// OP2 z, y, const2
2109// with
2110// OP3 z, x, const3
2111// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2112bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2113 HBinaryOperation* instruction) {
2114 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2115
2116 Primitive::Type type = instruction->GetType();
2117 if (!Primitive::IsIntegralType(type)) {
2118 return false;
2119 }
2120
2121 HInstruction* left = instruction->GetLeft();
2122 HInstruction* right = instruction->GetRight();
2123 // Variable names as described above.
2124 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2125 if (const2 == nullptr) {
2126 return false;
2127 }
2128
2129 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2130 ? left->AsBinaryOperation()
2131 : AsAddOrSub(right);
2132 // If y has more than one use, we do not perform the optimization because
2133 // it might increase code size (e.g. if the new constant is no longer
2134 // encodable as an immediate operand in the target ISA).
2135 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2136 return false;
2137 }
2138
2139 left = y->GetLeft();
2140 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2141 if (const1 == nullptr) {
2142 return false;
2143 }
2144
2145 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2146 // If both inputs are constants, let the constant folding pass deal with it.
2147 if (x->IsConstant()) {
2148 return false;
2149 }
2150
2151 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2152 int64_t const2_val = GetValue(const2, is_const2_negated);
2153 bool is_y_negated = (y == right) && instruction->IsSub();
2154 right = y->GetRight();
2155 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2156 int64_t const1_val = GetValue(const1, is_const1_negated);
2157 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2158 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2159 HBasicBlock* block = instruction->GetBlock();
2160 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2161 ArenaAllocator* arena = instruction->GetArena();
2162 HInstruction* z;
2163
2164 if (is_x_negated) {
2165 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2166 } else {
2167 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2168 }
2169
2170 block->ReplaceAndRemoveInstructionWith(instruction, z);
2171 RecordSimplification();
2172 return true;
2173}
2174
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002175} // namespace art