blob: 60790e5b841d0b3fb9bc3071075ced7787a73c3e [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"
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000022#include "sharpening.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070023#include "scoped_thread_state_change-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024
Nicolas Geoffray3c049742014-09-24 18:10:46 +010025namespace art {
26
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000028 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000029 InstructionSimplifierVisitor(HGraph* graph,
30 CodeGenerator* codegen,
31 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010032 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000033 codegen_(codegen),
Alexandre Rames188d4312015-04-09 18:30:21 +010034 stats_(stats) {}
35
36 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000037
38 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010039 void RecordSimplification() {
40 simplification_occurred_ = true;
41 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000042 MaybeRecordStat(kInstructionSimplifications);
43 }
44
45 void MaybeRecordStat(MethodCompilationStat stat) {
46 if (stats_ != nullptr) {
47 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010048 }
49 }
50
Scott Wakeling40a04bf2015-12-11 09:50:36 +000051 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
52 bool TryReplaceWithRotate(HBinaryOperation* instruction);
53 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
56
Alexandre Rames188d4312015-04-09 18:30:21 +010057 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000058 // `op` should be either HOr or HAnd.
59 // De Morgan's laws:
60 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
61 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010062 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
63 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
64
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000065 void VisitShift(HBinaryOperation* shift);
66
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010068 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
69 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010070 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
71 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000072 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000073 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000074 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080075 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000076 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitAdd(HAdd* instruction) OVERRIDE;
78 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040079 void VisitCondition(HCondition* instruction) OVERRIDE;
80 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
81 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
82 void VisitLessThan(HLessThan* condition) OVERRIDE;
83 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060084 void VisitBelow(HBelow* condition) OVERRIDE;
85 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
86 void VisitAbove(HAbove* condition) OVERRIDE;
87 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitDiv(HDiv* instruction) OVERRIDE;
89 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010090 void VisitNeg(HNeg* instruction) OVERRIDE;
91 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitOr(HOr* instruction) OVERRIDE;
93 void VisitShl(HShl* instruction) OVERRIDE;
94 void VisitShr(HShr* instruction) OVERRIDE;
95 void VisitSub(HSub* instruction) OVERRIDE;
96 void VisitUShr(HUShr* instruction) OVERRIDE;
97 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000098 void VisitSelect(HSelect* select) OVERRIDE;
99 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100100 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100101 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700102 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100103
104 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000105
Roland Levillain22c49222016-03-18 14:04:28 +0000106 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100107 void SimplifySystemArrayCopy(HInvoke* invoke);
108 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000109 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800110 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800111 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100112 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100113 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800114 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800115 void SimplifyReturnThis(HInvoke* invoke);
116 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800117 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100118
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000119 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000120 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100121 bool simplification_occurred_ = false;
122 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700123 // We ensure we do not loop infinitely. The value should not be too high, since that
124 // would allow looping around the same basic block too many times. The value should
125 // not be too low either, however, since we want to allow revisiting a basic block
126 // with many statements and simplifications at least once.
127 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000128};
129
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100130void InstructionSimplifier::Run() {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000131 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100132 visitor.Run();
133}
134
135void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100136 // Iterate in reverse post order to open up more simplifications to users
137 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100138 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100139 // The simplification of an instruction to another instruction may yield
140 // possibilities for other simplifications. So although we perform a reverse
141 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100142 do {
143 simplification_occurred_ = false;
144 VisitBasicBlock(block);
145 } while (simplification_occurred_ &&
146 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100147 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100148 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100149}
150
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000151namespace {
152
153bool AreAllBitsSet(HConstant* constant) {
154 return Int64FromConstant(constant) == -1;
155}
156
157} // namespace
158
Alexandre Rames188d4312015-04-09 18:30:21 +0100159// Returns true if the code was simplified to use only one negation operation
160// after the binary operation instead of one on each of the inputs.
161bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
162 DCHECK(binop->IsAdd() || binop->IsSub());
163 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
164 HNeg* left_neg = binop->GetLeft()->AsNeg();
165 HNeg* right_neg = binop->GetRight()->AsNeg();
166 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
167 !right_neg->HasOnlyOneNonEnvironmentUse()) {
168 return false;
169 }
170 // Replace code looking like
171 // NEG tmp1, a
172 // NEG tmp2, b
173 // ADD dst, tmp1, tmp2
174 // with
175 // ADD tmp, a, b
176 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600177 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
178 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
179 // while the later yields `-0.0`.
180 if (!Primitive::IsIntegralType(binop->GetType())) {
181 return false;
182 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100183 binop->ReplaceInput(left_neg->GetInput(), 0);
184 binop->ReplaceInput(right_neg->GetInput(), 1);
185 left_neg->GetBlock()->RemoveInstruction(left_neg);
186 right_neg->GetBlock()->RemoveInstruction(right_neg);
187 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
188 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
189 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
190 RecordSimplification();
191 return true;
192}
193
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000194bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
195 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
196 Primitive::Type type = op->GetType();
197 HInstruction* left = op->GetLeft();
198 HInstruction* right = op->GetRight();
199
200 // We can apply De Morgan's laws if both inputs are Not's and are only used
201 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000202 if (((left->IsNot() && right->IsNot()) ||
203 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000204 left->HasOnlyOneNonEnvironmentUse() &&
205 right->HasOnlyOneNonEnvironmentUse()) {
206 // Replace code looking like
207 // NOT nota, a
208 // NOT notb, b
209 // AND dst, nota, notb (respectively OR)
210 // with
211 // OR or, a, b (respectively AND)
212 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000213 HInstruction* src_left = left->InputAt(0);
214 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000215 uint32_t dex_pc = op->GetDexPc();
216
217 // Remove the negations on the inputs.
218 left->ReplaceWith(src_left);
219 right->ReplaceWith(src_right);
220 left->GetBlock()->RemoveInstruction(left);
221 right->GetBlock()->RemoveInstruction(right);
222
223 // Replace the `HAnd` or `HOr`.
224 HBinaryOperation* hbin;
225 if (op->IsAnd()) {
226 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
227 } else {
228 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
229 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000230 HInstruction* hnot;
231 if (left->IsBooleanNot()) {
232 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
233 } else {
234 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
235 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000236
237 op->GetBlock()->InsertInstructionBefore(hbin, op);
238 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
239
240 RecordSimplification();
241 return true;
242 }
243
244 return false;
245}
246
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000247void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
248 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100249 HInstruction* shift_amount = instruction->GetRight();
250 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000251
Alexandre Rames50518442016-06-27 11:39:19 +0100252 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
253 ? kMaxLongShiftDistance
254 : kMaxIntShiftDistance;
255
256 if (shift_amount->IsConstant()) {
257 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
258 if ((cst & implicit_mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400259 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100260 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400261 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100262 // value
263 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400264 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100265 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100266 return;
267 }
268 }
269
270 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
271 // unnecessary explicit masking operations on the shift amount.
272 // Replace code looking like
273 // AND masked_shift, shift, <superset of implicit mask>
274 // SHL dst, value, masked_shift
275 // with
276 // SHL dst, value, shift
277 if (shift_amount->IsAnd()) {
278 HAnd* and_insn = shift_amount->AsAnd();
279 HConstant* mask = and_insn->GetConstantRight();
280 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
281 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
282 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400283 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000284 }
285}
286
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000287static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
288 return (sub->GetRight() == other &&
289 sub->GetLeft()->IsConstant() &&
290 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
291}
292
293bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
294 HUShr* ushr,
295 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000296 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
297 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000298 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
299 if (!ushr->HasUses()) {
300 ushr->GetBlock()->RemoveInstruction(ushr);
301 }
302 if (!ushr->GetRight()->HasUses()) {
303 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
304 }
305 if (!shl->HasUses()) {
306 shl->GetBlock()->RemoveInstruction(shl);
307 }
308 if (!shl->GetRight()->HasUses()) {
309 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
310 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100311 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000312 return true;
313}
314
315// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
316bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000317 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
318 HInstruction* left = op->GetLeft();
319 HInstruction* right = op->GetRight();
320 // If we have an UShr and a Shl (in either order).
321 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
322 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
323 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
324 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
325 if (ushr->GetType() == shl->GetType() &&
326 ushr->GetLeft() == shl->GetLeft()) {
327 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
328 // Shift distances are both constant, try replacing with Ror if they
329 // add up to the register size.
330 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
331 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
332 // Shift distances are potentially of the form x and (reg_size - x).
333 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
334 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
335 // Shift distances are potentially of the form d and -d.
336 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
337 }
338 }
339 }
340 return false;
341}
342
343// Try replacing code looking like (x >>> #rdist OP x << #ldist):
344// UShr dst, x, #rdist
345// Shl tmp, x, #ldist
346// OP dst, dst, tmp
347// or like (x >>> #rdist OP x << #-ldist):
348// UShr dst, x, #rdist
349// Shl tmp, x, #-ldist
350// OP dst, dst, tmp
351// with
352// Ror dst, x, #rdist
353bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
354 HUShr* ushr,
355 HShl* shl) {
356 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
357 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
358 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
359 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
360 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
361 ReplaceRotateWithRor(op, ushr, shl);
362 return true;
363 }
364 return false;
365}
366
367// Replace code looking like (x >>> -d OP x << d):
368// Neg neg, d
369// UShr dst, x, neg
370// Shl tmp, x, d
371// OP dst, dst, tmp
372// with
373// Neg neg, d
374// Ror dst, x, neg
375// *** OR ***
376// Replace code looking like (x >>> d OP x << -d):
377// UShr dst, x, d
378// Neg neg, d
379// Shl tmp, x, neg
380// OP dst, dst, tmp
381// with
382// Ror dst, x, d
383bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
384 HUShr* ushr,
385 HShl* shl) {
386 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
387 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
388 bool neg_is_left = shl->GetRight()->IsNeg();
389 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
390 // And the shift distance being negated is the distance being shifted the other way.
391 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
392 ReplaceRotateWithRor(op, ushr, shl);
393 }
394 return false;
395}
396
397// Try replacing code looking like (x >>> d OP x << (#bits - d)):
398// UShr dst, x, d
399// Sub ld, #bits, d
400// Shl tmp, x, ld
401// OP dst, dst, tmp
402// with
403// Ror dst, x, d
404// *** OR ***
405// Replace code looking like (x >>> (#bits - d) OP x << d):
406// Sub rd, #bits, d
407// UShr dst, x, rd
408// Shl tmp, x, d
409// OP dst, dst, tmp
410// with
411// Neg neg, d
412// Ror dst, x, neg
413bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
414 HUShr* ushr,
415 HShl* shl) {
416 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
417 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
418 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
419 HInstruction* shl_shift = shl->GetRight();
420 HInstruction* ushr_shift = ushr->GetRight();
421 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
422 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
423 return ReplaceRotateWithRor(op, ushr, shl);
424 }
425 return false;
426}
427
Calin Juravle10e244f2015-01-26 18:54:32 +0000428void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
429 HInstruction* obj = null_check->InputAt(0);
430 if (!obj->CanBeNull()) {
431 null_check->ReplaceWith(obj);
432 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000433 if (stats_ != nullptr) {
434 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
435 }
436 }
437}
438
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100439bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
440 if (!input->CanBeNull()) {
441 return true;
442 }
443
Vladimir Marko46817b82016-03-29 12:21:58 +0100444 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
445 HInstruction* user = use.GetUser();
446 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100447 return true;
448 }
449 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100450
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100451 return false;
452}
453
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100454// Returns whether doing a type test between the class of `object` against `klass` has
455// a statically known outcome. The result of the test is stored in `outcome`.
456static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000457 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
458 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
459 ScopedObjectAccess soa(Thread::Current());
460 if (!obj_rti.IsValid()) {
461 // We run the simplifier before the reference type propagation so type info might not be
462 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100463 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000464 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100465
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100466 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100467 if (!class_rti.IsValid()) {
468 // Happens when the loaded class is unresolved.
469 return false;
470 }
471 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000472 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100473 *outcome = true;
474 return true;
475 } else if (obj_rti.IsExact()) {
476 // The test failed at compile time so will also fail at runtime.
477 *outcome = false;
478 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100479 } else if (!class_rti.IsInterface()
480 && !obj_rti.IsInterface()
481 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100482 // Different type hierarchy. The test will fail.
483 *outcome = false;
484 return true;
485 }
486 return false;
487}
488
489void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
490 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100491 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
492 if (load_class->NeedsAccessCheck()) {
493 // If we need to perform an access check we cannot remove the instruction.
494 return;
495 }
496
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100497 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100498 check_cast->ClearMustDoNullCheck();
499 }
500
501 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000502 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000503 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100504 return;
505 }
506
Vladimir Markoa65ed302016-03-14 21:21:29 +0000507 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
508 // the return value check with the `outcome` check, b/27651442 .
509 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700510 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100511 if (outcome) {
512 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000513 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700514 if (!load_class->HasUses()) {
515 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
516 // However, here we know that it cannot because the checkcast was successfull, hence
517 // the class was already loaded.
518 load_class->GetBlock()->RemoveInstruction(load_class);
519 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100520 } else {
521 // Don't do anything for exceptional cases for now. Ideally we should remove
522 // all instructions and blocks this instruction dominates.
523 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000524 }
525}
526
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100527void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100528 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100529 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
530 if (load_class->NeedsAccessCheck()) {
531 // If we need to perform an access check we cannot remove the instruction.
532 return;
533 }
534
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100535 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100536 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100537 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100538 instruction->ClearMustDoNullCheck();
539 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100540
541 HGraph* graph = GetGraph();
542 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000543 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100544 instruction->ReplaceWith(graph->GetIntConstant(0));
545 instruction->GetBlock()->RemoveInstruction(instruction);
546 RecordSimplification();
547 return;
548 }
549
Vladimir Marko24bd8952016-03-15 10:40:33 +0000550 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
551 // the return value check with the `outcome` check, b/27651442 .
552 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700553 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000554 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100555 if (outcome && can_be_null) {
556 // Type test will succeed, we just need a null test.
557 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
558 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
559 instruction->ReplaceWith(test);
560 } else {
561 // We've statically determined the result of the instanceof.
562 instruction->ReplaceWith(graph->GetIntConstant(outcome));
563 }
564 RecordSimplification();
565 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700566 if (outcome && !load_class->HasUses()) {
567 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
568 // However, here we know that it cannot because the instanceof check was successfull, hence
569 // the class was already loaded.
570 load_class->GetBlock()->RemoveInstruction(load_class);
571 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100572 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100573}
574
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100575void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
576 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100577 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100578 instruction->ClearValueCanBeNull();
579 }
580}
581
582void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
583 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100584 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100585 instruction->ClearValueCanBeNull();
586 }
587}
588
Anton Shaminbdd79352016-02-15 12:48:36 +0600589static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
590 HInstruction *lhs = cond->InputAt(0);
591 HInstruction *rhs = cond->InputAt(1);
592 switch (cond->GetKind()) {
593 case HInstruction::kEqual:
594 return new (arena) HEqual(rhs, lhs);
595 case HInstruction::kNotEqual:
596 return new (arena) HNotEqual(rhs, lhs);
597 case HInstruction::kLessThan:
598 return new (arena) HGreaterThan(rhs, lhs);
599 case HInstruction::kLessThanOrEqual:
600 return new (arena) HGreaterThanOrEqual(rhs, lhs);
601 case HInstruction::kGreaterThan:
602 return new (arena) HLessThan(rhs, lhs);
603 case HInstruction::kGreaterThanOrEqual:
604 return new (arena) HLessThanOrEqual(rhs, lhs);
605 case HInstruction::kBelow:
606 return new (arena) HAbove(rhs, lhs);
607 case HInstruction::kBelowOrEqual:
608 return new (arena) HAboveOrEqual(rhs, lhs);
609 case HInstruction::kAbove:
610 return new (arena) HBelow(rhs, lhs);
611 case HInstruction::kAboveOrEqual:
612 return new (arena) HBelowOrEqual(rhs, lhs);
613 default:
614 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
615 }
616 return nullptr;
617}
618
Aart Bik2767f4b2016-10-28 15:03:53 -0700619static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
620 if (input->GetType() == Primitive::kPrimBoolean) {
621 return true; // input has direct boolean type
622 } else if (cmp->GetUses().HasExactlyOneElement()) {
623 // Comparison also has boolean type if both its input and the instruction
624 // itself feed into the same phi node.
625 HInstruction* user = cmp->GetUses().front().GetUser();
626 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
627 }
628 return false;
629}
630
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000631void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100632 HInstruction* input_const = equal->GetConstantRight();
633 if (input_const != nullptr) {
634 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700635 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100636 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100637 // We are comparing the boolean to a constant which is of type int and can
638 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000639 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100640 // Replace (bool_value == true) with bool_value
641 equal->ReplaceWith(input_value);
642 block->RemoveInstruction(equal);
643 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000644 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700645 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500646 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
647 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100648 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100649 } else {
650 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
651 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
652 block->RemoveInstruction(equal);
653 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100654 }
Mark Mendellc4701932015-04-10 13:18:51 -0400655 } else {
656 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100657 }
Mark Mendellc4701932015-04-10 13:18:51 -0400658 } else {
659 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100660 }
661}
662
David Brazdil0d13fee2015-04-17 14:52:19 +0100663void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
664 HInstruction* input_const = not_equal->GetConstantRight();
665 if (input_const != nullptr) {
666 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700667 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100668 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100669 // We are comparing the boolean to a constant which is of type int and can
670 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000671 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700672 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500673 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
674 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100675 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000676 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100677 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100678 not_equal->ReplaceWith(input_value);
679 block->RemoveInstruction(not_equal);
680 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100681 } else {
682 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
683 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
684 block->RemoveInstruction(not_equal);
685 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100686 }
Mark Mendellc4701932015-04-10 13:18:51 -0400687 } else {
688 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100689 }
Mark Mendellc4701932015-04-10 13:18:51 -0400690 } else {
691 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100692 }
693}
694
695void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000696 HInstruction* input = bool_not->InputAt(0);
697 HInstruction* replace_with = nullptr;
698
699 if (input->IsIntConstant()) {
700 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000701 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000702 replace_with = GetGraph()->GetIntConstant(0);
703 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000704 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000705 replace_with = GetGraph()->GetIntConstant(1);
706 }
707 } else if (input->IsBooleanNot()) {
708 // Replace (!(!bool_value)) with bool_value.
709 replace_with = input->InputAt(0);
710 } else if (input->IsCondition() &&
711 // Don't change FP compares. The definition of compares involving
712 // NaNs forces the compares to be done as written by the user.
713 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
714 // Replace condition with its opposite.
715 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
716 }
717
718 if (replace_with != nullptr) {
719 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100720 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000721 RecordSimplification();
722 }
723}
724
725void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
726 HInstruction* replace_with = nullptr;
727 HInstruction* condition = select->GetCondition();
728 HInstruction* true_value = select->GetTrueValue();
729 HInstruction* false_value = select->GetFalseValue();
730
731 if (condition->IsBooleanNot()) {
732 // Change ((!cond) ? x : y) to (cond ? y : x).
733 condition = condition->InputAt(0);
734 std::swap(true_value, false_value);
735 select->ReplaceInput(false_value, 0);
736 select->ReplaceInput(true_value, 1);
737 select->ReplaceInput(condition, 2);
738 RecordSimplification();
739 }
740
741 if (true_value == false_value) {
742 // Replace (cond ? x : x) with (x).
743 replace_with = true_value;
744 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000745 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000746 // Replace (true ? x : y) with (x).
747 replace_with = true_value;
748 } else {
749 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000750 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000751 replace_with = false_value;
752 }
753 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000754 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000755 // Replace (cond ? true : false) with (cond).
756 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000757 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000758 // Replace (cond ? false : true) with (!cond).
759 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
760 }
761 }
762
763 if (replace_with != nullptr) {
764 select->ReplaceWith(replace_with);
765 select->GetBlock()->RemoveInstruction(select);
766 RecordSimplification();
767 }
768}
769
770void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
771 HInstruction* condition = instruction->InputAt(0);
772 if (condition->IsBooleanNot()) {
773 // Swap successors if input is negated.
774 instruction->ReplaceInput(condition->InputAt(0), 0);
775 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100776 RecordSimplification();
777 }
778}
779
Mingyao Yang0304e182015-01-30 16:41:29 -0800780void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
781 HInstruction* input = instruction->InputAt(0);
782 // If the array is a NewArray with constant size, replace the array length
783 // with the constant instruction. This helps the bounds check elimination phase.
784 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000785 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800786 if (input->IsIntConstant()) {
787 instruction->ReplaceWith(input);
788 }
789 }
790}
791
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000792void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000793 HInstruction* value = instruction->GetValue();
794 if (value->GetType() != Primitive::kPrimNot) return;
795
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100796 if (CanEnsureNotNullAt(value, instruction)) {
797 instruction->ClearValueCanBeNull();
798 }
799
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000800 if (value->IsArrayGet()) {
801 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
802 // If the code is just swapping elements in the array, no need for a type check.
803 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100804 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000805 }
806 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100807
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100808 if (value->IsNullConstant()) {
809 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100810 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100811 }
812
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100813 ScopedObjectAccess soa(Thread::Current());
814 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
815 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
816 if (!array_rti.IsValid()) {
817 return;
818 }
819
820 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
821 instruction->ClearNeedsTypeCheck();
822 return;
823 }
824
825 if (array_rti.IsObjectArray()) {
826 if (array_rti.IsExact()) {
827 instruction->ClearNeedsTypeCheck();
828 return;
829 }
830 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100831 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000832}
833
Vladimir Markob52bbde2016-02-12 12:06:05 +0000834static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100835 // Invariant: We should never generate a conversion to a Boolean value.
836 DCHECK_NE(Primitive::kPrimBoolean, result_type);
837
Vladimir Markob52bbde2016-02-12 12:06:05 +0000838 // Besides conversion to the same type, widening integral conversions are implicit,
839 // excluding conversions to long and the byte->char conversion where we need to
840 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
841 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100842 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
843 input_type == Primitive::kPrimByte ||
844 input_type == Primitive::kPrimShort ||
845 input_type == Primitive::kPrimChar)) ||
846 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
847 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
848 input_type == Primitive::kPrimByte)) ||
849 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000850}
851
852static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
853 // The conversion to a larger type is loss-less with the exception of two cases,
854 // - conversion to char, the only unsigned type, where we may lose some bits, and
855 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
856 // For integral to FP conversions this holds because the FP mantissa is large enough.
857 DCHECK_NE(input_type, result_type);
858 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
859 result_type != Primitive::kPrimChar &&
860 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
861}
862
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000863void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000864 HInstruction* input = instruction->GetInput();
865 Primitive::Type input_type = input->GetType();
866 Primitive::Type result_type = instruction->GetResultType();
867 if (IsTypeConversionImplicit(input_type, result_type)) {
868 // Remove the implicit conversion; this includes conversion to the same type.
869 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000870 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000871 RecordSimplification();
872 return;
873 }
874
875 if (input->IsTypeConversion()) {
876 HTypeConversion* input_conversion = input->AsTypeConversion();
877 HInstruction* original_input = input_conversion->GetInput();
878 Primitive::Type original_type = original_input->GetType();
879
880 // When the first conversion is lossless, a direct conversion from the original type
881 // to the final type yields the same result, even for a lossy second conversion, for
882 // example float->double->int or int->double->float.
883 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
884
885 // For integral conversions, see if the first conversion loses only bits that the second
886 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
887 // conversion yields the same result, for example long->int->short or int->char->short.
888 bool integral_conversions_with_non_widening_second =
889 Primitive::IsIntegralType(input_type) &&
890 Primitive::IsIntegralType(original_type) &&
891 Primitive::IsIntegralType(result_type) &&
892 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
893
894 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
895 // If the merged conversion is implicit, do the simplification unconditionally.
896 if (IsTypeConversionImplicit(original_type, result_type)) {
897 instruction->ReplaceWith(original_input);
898 instruction->GetBlock()->RemoveInstruction(instruction);
899 if (!input_conversion->HasUses()) {
900 // Don't wait for DCE.
901 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
902 }
903 RecordSimplification();
904 return;
905 }
906 // Otherwise simplify only if the first conversion has no other use.
907 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
908 input_conversion->ReplaceWith(original_input);
909 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
910 RecordSimplification();
911 return;
912 }
913 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000914 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000915 DCHECK(Primitive::IsIntegralType(input_type));
916 HAnd* input_and = input->AsAnd();
917 HConstant* constant = input_and->GetConstantRight();
918 if (constant != nullptr) {
919 int64_t value = Int64FromConstant(constant);
920 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
921 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
922 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
923 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000924 HInstruction* original_input = input_and->GetLeastConstantLeft();
925 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
926 instruction->ReplaceWith(original_input);
927 instruction->GetBlock()->RemoveInstruction(instruction);
928 RecordSimplification();
929 return;
930 } else if (input->HasOnlyOneNonEnvironmentUse()) {
931 input_and->ReplaceWith(original_input);
932 input_and->GetBlock()->RemoveInstruction(input_and);
933 RecordSimplification();
934 return;
935 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000936 }
937 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000938 }
939}
940
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000941void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
942 HConstant* input_cst = instruction->GetConstantRight();
943 HInstruction* input_other = instruction->GetLeastConstantLeft();
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600944 bool integral_type = Primitive::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +0000945 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000946 // Replace code looking like
947 // ADD dst, src, 0
948 // with
949 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600950 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
951 // `x` is `-0.0`, the former expression yields `0.0`, while the later
952 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600953 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +0600954 instruction->ReplaceWith(input_other);
955 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100956 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600957 return;
958 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100959 }
960
961 HInstruction* left = instruction->GetLeft();
962 HInstruction* right = instruction->GetRight();
963 bool left_is_neg = left->IsNeg();
964 bool right_is_neg = right->IsNeg();
965
966 if (left_is_neg && right_is_neg) {
967 if (TryMoveNegOnInputsAfterBinop(instruction)) {
968 return;
969 }
970 }
971
972 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
973 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
974 // Replace code looking like
975 // NEG tmp, b
976 // ADD dst, a, tmp
977 // with
978 // SUB dst, a, b
979 // We do not perform the optimization if the input negation has environment
980 // uses or multiple non-environment uses as it could lead to worse code. In
981 // particular, we do not want the live range of `b` to be extended if we are
982 // not sure the initial 'NEG' instruction can be removed.
983 HInstruction* other = left_is_neg ? right : left;
984 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
985 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
986 RecordSimplification();
987 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000988 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000989 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000990
Anton Kirilove14dc862016-05-13 17:56:15 +0100991 if (TryReplaceWithRotate(instruction)) {
992 return;
993 }
994
995 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
996 // so no need to return.
997 TryHandleAssociativeAndCommutativeOperation(instruction);
998
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600999 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001000 TrySubtractionChainSimplification(instruction)) {
1001 return;
1002 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001003
1004 if (integral_type) {
1005 // Replace code patterns looking like
1006 // SUB dst1, x, y SUB dst1, x, y
1007 // ADD dst2, dst1, y ADD dst2, y, dst1
1008 // with
1009 // SUB dst1, x, y
1010 // ADD instruction is not needed in this case, we may use
1011 // one of inputs of SUB instead.
1012 if (left->IsSub() && left->InputAt(1) == right) {
1013 instruction->ReplaceWith(left->InputAt(0));
1014 RecordSimplification();
1015 instruction->GetBlock()->RemoveInstruction(instruction);
1016 return;
1017 } else if (right->IsSub() && right->InputAt(1) == left) {
1018 instruction->ReplaceWith(right->InputAt(0));
1019 RecordSimplification();
1020 instruction->GetBlock()->RemoveInstruction(instruction);
1021 return;
1022 }
1023 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001024}
1025
1026void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1027 HConstant* input_cst = instruction->GetConstantRight();
1028 HInstruction* input_other = instruction->GetLeastConstantLeft();
1029
Vladimir Marko452c1b62015-09-25 14:44:17 +01001030 if (input_cst != nullptr) {
1031 int64_t value = Int64FromConstant(input_cst);
1032 if (value == -1) {
1033 // Replace code looking like
1034 // AND dst, src, 0xFFF...FF
1035 // with
1036 // src
1037 instruction->ReplaceWith(input_other);
1038 instruction->GetBlock()->RemoveInstruction(instruction);
1039 RecordSimplification();
1040 return;
1041 }
1042 // Eliminate And from UShr+And if the And-mask contains all the bits that
1043 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1044 // precisely clears the shifted-in sign bits.
1045 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1046 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1047 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1048 size_t num_tail_bits_set = CTZ(value + 1);
1049 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1050 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1051 instruction->ReplaceWith(input_other);
1052 instruction->GetBlock()->RemoveInstruction(instruction);
1053 RecordSimplification();
1054 return;
1055 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1056 input_other->HasOnlyOneNonEnvironmentUse()) {
1057 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1058 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1059 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1060 input_other->InputAt(0),
1061 input_other->InputAt(1),
1062 input_other->GetDexPc());
1063 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1064 input_other->GetBlock()->RemoveInstruction(input_other);
1065 RecordSimplification();
1066 return;
1067 }
1068 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001069 }
1070
1071 // We assume that GVN has run before, so we only perform a pointer comparison.
1072 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001073 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001074 if (instruction->GetLeft() == instruction->GetRight()) {
1075 // Replace code looking like
1076 // AND dst, src, src
1077 // with
1078 // src
1079 instruction->ReplaceWith(instruction->GetLeft());
1080 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001081 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001082 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001083 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001084
Anton Kirilove14dc862016-05-13 17:56:15 +01001085 if (TryDeMorganNegationFactoring(instruction)) {
1086 return;
1087 }
1088
1089 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1090 // so no need to return.
1091 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001092}
1093
Mark Mendellc4701932015-04-10 13:18:51 -04001094void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1095 VisitCondition(condition);
1096}
1097
1098void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1099 VisitCondition(condition);
1100}
1101
1102void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1103 VisitCondition(condition);
1104}
1105
1106void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1107 VisitCondition(condition);
1108}
1109
Anton Shaminbdd79352016-02-15 12:48:36 +06001110void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1111 VisitCondition(condition);
1112}
1113
1114void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1115 VisitCondition(condition);
1116}
1117
1118void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1119 VisitCondition(condition);
1120}
1121
1122void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1123 VisitCondition(condition);
1124}
Aart Bike9f37602015-10-09 11:15:55 -07001125
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001126// Recognize the following pattern:
1127// obj.getClass() ==/!= Foo.class
1128// And replace it with a constant value if the type of `obj` is statically known.
1129static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1130 HInstruction* input_one = condition->InputAt(0);
1131 HInstruction* input_two = condition->InputAt(1);
1132 HLoadClass* load_class = input_one->IsLoadClass()
1133 ? input_one->AsLoadClass()
1134 : input_two->AsLoadClass();
1135 if (load_class == nullptr) {
1136 return false;
1137 }
1138
1139 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1140 if (!class_rti.IsValid()) {
1141 // Unresolved class.
1142 return false;
1143 }
1144
1145 HInstanceFieldGet* field_get = (load_class == input_one)
1146 ? input_two->AsInstanceFieldGet()
1147 : input_one->AsInstanceFieldGet();
1148 if (field_get == nullptr) {
1149 return false;
1150 }
1151
1152 HInstruction* receiver = field_get->InputAt(0);
1153 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1154 if (!receiver_type.IsExact()) {
1155 return false;
1156 }
1157
1158 {
1159 ScopedObjectAccess soa(Thread::Current());
1160 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1161 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1162 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1163 if (field_get->GetFieldInfo().GetField() != field) {
1164 return false;
1165 }
1166
1167 // We can replace the compare.
1168 int value = 0;
1169 if (receiver_type.IsEqual(class_rti)) {
1170 value = condition->IsEqual() ? 1 : 0;
1171 } else {
1172 value = condition->IsNotEqual() ? 1 : 0;
1173 }
1174 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1175 return true;
1176 }
1177}
1178
Mark Mendellc4701932015-04-10 13:18:51 -04001179void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001180 if (condition->IsEqual() || condition->IsNotEqual()) {
1181 if (RecognizeAndSimplifyClassCheck(condition)) {
1182 return;
1183 }
1184 }
1185
Anton Shaminbdd79352016-02-15 12:48:36 +06001186 // Reverse condition if left is constant. Our code generators prefer constant
1187 // on the right hand side.
1188 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1189 HBasicBlock* block = condition->GetBlock();
1190 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1191 // If it is a fp we must set the opposite bias.
1192 if (replacement != nullptr) {
1193 if (condition->IsLtBias()) {
1194 replacement->SetBias(ComparisonBias::kGtBias);
1195 } else if (condition->IsGtBias()) {
1196 replacement->SetBias(ComparisonBias::kLtBias);
1197 }
1198 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1199 RecordSimplification();
1200
1201 condition = replacement;
1202 }
1203 }
Mark Mendellc4701932015-04-10 13:18:51 -04001204
Mark Mendellc4701932015-04-10 13:18:51 -04001205 HInstruction* left = condition->GetLeft();
1206 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001207
1208 // Try to fold an HCompare into this HCondition.
1209
Mark Mendellc4701932015-04-10 13:18:51 -04001210 // We can only replace an HCondition which compares a Compare to 0.
1211 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1212 // condition with a long, float or double comparison as input.
1213 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1214 // Conversion is not possible.
1215 return;
1216 }
1217
1218 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001219 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001220 // Someone else also wants the result of the compare.
1221 return;
1222 }
1223
Vladimir Marko46817b82016-03-29 12:21:58 +01001224 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001225 // There is a reference to the compare result in an environment. Do we really need it?
1226 if (GetGraph()->IsDebuggable()) {
1227 return;
1228 }
1229
1230 // We have to ensure that there are no deopt points in the sequence.
1231 if (left->HasAnyEnvironmentUseBefore(condition)) {
1232 return;
1233 }
1234 }
1235
1236 // Clean up any environment uses from the HCompare, if any.
1237 left->RemoveEnvironmentUsers();
1238
1239 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1240 condition->SetBias(left->AsCompare()->GetBias());
1241
1242 // Replace the operands of the HCondition.
1243 condition->ReplaceInput(left->InputAt(0), 0);
1244 condition->ReplaceInput(left->InputAt(1), 1);
1245
1246 // Remove the HCompare.
1247 left->GetBlock()->RemoveInstruction(left);
1248
1249 RecordSimplification();
1250}
1251
Andreas Gampe9186ced2016-12-12 14:28:21 -08001252// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1253static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1254 // True, if the most significant bits of divisor are 0.
1255 return ((divisor & 0x7fffff) == 0);
1256}
1257
1258// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1259static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1260 // True, if the most significant bits of divisor are 0.
1261 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1262}
1263
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001264void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1265 HConstant* input_cst = instruction->GetConstantRight();
1266 HInstruction* input_other = instruction->GetLeastConstantLeft();
1267 Primitive::Type type = instruction->GetType();
1268
1269 if ((input_cst != nullptr) && input_cst->IsOne()) {
1270 // Replace code looking like
1271 // DIV dst, src, 1
1272 // with
1273 // src
1274 instruction->ReplaceWith(input_other);
1275 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001276 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001277 return;
1278 }
1279
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001280 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001281 // Replace code looking like
1282 // DIV dst, src, -1
1283 // with
1284 // NEG dst, src
1285 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001286 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001287 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001288 return;
1289 }
1290
1291 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1292 // Try replacing code looking like
1293 // DIV dst, src, constant
1294 // with
1295 // MUL dst, src, 1 / constant
1296 HConstant* reciprocal = nullptr;
1297 if (type == Primitive::Primitive::kPrimDouble) {
1298 double value = input_cst->AsDoubleConstant()->GetValue();
1299 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1300 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1301 }
1302 } else {
1303 DCHECK_EQ(type, Primitive::kPrimFloat);
1304 float value = input_cst->AsFloatConstant()->GetValue();
1305 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1306 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1307 }
1308 }
1309
1310 if (reciprocal != nullptr) {
1311 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1312 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1313 RecordSimplification();
1314 return;
1315 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001316 }
1317}
1318
1319void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1320 HConstant* input_cst = instruction->GetConstantRight();
1321 HInstruction* input_other = instruction->GetLeastConstantLeft();
1322 Primitive::Type type = instruction->GetType();
1323 HBasicBlock* block = instruction->GetBlock();
1324 ArenaAllocator* allocator = GetGraph()->GetArena();
1325
1326 if (input_cst == nullptr) {
1327 return;
1328 }
1329
1330 if (input_cst->IsOne()) {
1331 // Replace code looking like
1332 // MUL dst, src, 1
1333 // with
1334 // src
1335 instruction->ReplaceWith(input_other);
1336 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001337 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001338 return;
1339 }
1340
1341 if (input_cst->IsMinusOne() &&
1342 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1343 // Replace code looking like
1344 // MUL dst, src, -1
1345 // with
1346 // NEG dst, src
1347 HNeg* neg = new (allocator) HNeg(type, input_other);
1348 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001349 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001350 return;
1351 }
1352
1353 if (Primitive::IsFloatingPointType(type) &&
1354 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1355 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1356 // Replace code looking like
1357 // FP_MUL dst, src, 2.0
1358 // with
1359 // FP_ADD dst, src, src
1360 // The 'int' and 'long' cases are handled below.
1361 block->ReplaceAndRemoveInstructionWith(instruction,
1362 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001363 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001364 return;
1365 }
1366
1367 if (Primitive::IsIntOrLongType(type)) {
1368 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001369 // Even though constant propagation also takes care of the zero case, other
1370 // optimizations can lead to having a zero multiplication.
1371 if (factor == 0) {
1372 // Replace code looking like
1373 // MUL dst, src, 0
1374 // with
1375 // 0
1376 instruction->ReplaceWith(input_cst);
1377 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001378 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001379 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001380 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001381 // Replace code looking like
1382 // MUL dst, src, pow_of_2
1383 // with
1384 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001385 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001386 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001387 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001388 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001389 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001390 } else if (IsPowerOfTwo(factor - 1)) {
1391 // Transform code looking like
1392 // MUL dst, src, (2^n + 1)
1393 // into
1394 // SHL tmp, src, n
1395 // ADD dst, src, tmp
1396 HShl* shl = new (allocator) HShl(type,
1397 input_other,
1398 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1399 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1400
1401 block->InsertInstructionBefore(shl, instruction);
1402 block->ReplaceAndRemoveInstructionWith(instruction, add);
1403 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001404 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001405 } else if (IsPowerOfTwo(factor + 1)) {
1406 // Transform code looking like
1407 // MUL dst, src, (2^n - 1)
1408 // into
1409 // SHL tmp, src, n
1410 // SUB dst, tmp, src
1411 HShl* shl = new (allocator) HShl(type,
1412 input_other,
1413 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1414 HSub* sub = new (allocator) HSub(type, shl, input_other);
1415
1416 block->InsertInstructionBefore(shl, instruction);
1417 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1418 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001419 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001420 }
1421 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001422
1423 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1424 // so no need to return.
1425 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001426}
1427
Alexandre Rames188d4312015-04-09 18:30:21 +01001428void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1429 HInstruction* input = instruction->GetInput();
1430 if (input->IsNeg()) {
1431 // Replace code looking like
1432 // NEG tmp, src
1433 // NEG dst, tmp
1434 // with
1435 // src
1436 HNeg* previous_neg = input->AsNeg();
1437 instruction->ReplaceWith(previous_neg->GetInput());
1438 instruction->GetBlock()->RemoveInstruction(instruction);
1439 // We perform the optimization even if the input negation has environment
1440 // uses since it allows removing the current instruction. But we only delete
1441 // the input negation only if it is does not have any uses left.
1442 if (!previous_neg->HasUses()) {
1443 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1444 }
1445 RecordSimplification();
1446 return;
1447 }
1448
Serguei Katkov339dfc22015-04-20 12:29:32 +06001449 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1450 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001451 // Replace code looking like
1452 // SUB tmp, a, b
1453 // NEG dst, tmp
1454 // with
1455 // SUB dst, b, a
1456 // We do not perform the optimization if the input subtraction has
1457 // environment uses or multiple non-environment uses as it could lead to
1458 // worse code. In particular, we do not want the live ranges of `a` and `b`
1459 // to be extended if we are not sure the initial 'SUB' instruction can be
1460 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001461 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001462 HSub* sub = input->AsSub();
1463 HSub* new_sub =
1464 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1465 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1466 if (!sub->HasUses()) {
1467 sub->GetBlock()->RemoveInstruction(sub);
1468 }
1469 RecordSimplification();
1470 }
1471}
1472
1473void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1474 HInstruction* input = instruction->GetInput();
1475 if (input->IsNot()) {
1476 // Replace code looking like
1477 // NOT tmp, src
1478 // NOT dst, tmp
1479 // with
1480 // src
1481 // We perform the optimization even if the input negation has environment
1482 // uses since it allows removing the current instruction. But we only delete
1483 // the input negation only if it is does not have any uses left.
1484 HNot* previous_not = input->AsNot();
1485 instruction->ReplaceWith(previous_not->GetInput());
1486 instruction->GetBlock()->RemoveInstruction(instruction);
1487 if (!previous_not->HasUses()) {
1488 previous_not->GetBlock()->RemoveInstruction(previous_not);
1489 }
1490 RecordSimplification();
1491 }
1492}
1493
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001494void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1495 HConstant* input_cst = instruction->GetConstantRight();
1496 HInstruction* input_other = instruction->GetLeastConstantLeft();
1497
Roland Levillain1a653882016-03-18 18:05:57 +00001498 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001499 // Replace code looking like
1500 // OR dst, src, 0
1501 // with
1502 // src
1503 instruction->ReplaceWith(input_other);
1504 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001505 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001506 return;
1507 }
1508
1509 // We assume that GVN has run before, so we only perform a pointer comparison.
1510 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001511 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001512 if (instruction->GetLeft() == instruction->GetRight()) {
1513 // Replace code looking like
1514 // OR dst, src, src
1515 // with
1516 // src
1517 instruction->ReplaceWith(instruction->GetLeft());
1518 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001519 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001520 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001521 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001522
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001523 if (TryDeMorganNegationFactoring(instruction)) return;
1524
Anton Kirilove14dc862016-05-13 17:56:15 +01001525 if (TryReplaceWithRotate(instruction)) {
1526 return;
1527 }
1528
1529 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1530 // so no need to return.
1531 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001532}
1533
1534void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1535 VisitShift(instruction);
1536}
1537
1538void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1539 VisitShift(instruction);
1540}
1541
1542void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1543 HConstant* input_cst = instruction->GetConstantRight();
1544 HInstruction* input_other = instruction->GetLeastConstantLeft();
1545
Serguei Katkov115b53f2015-08-05 17:03:30 +06001546 Primitive::Type type = instruction->GetType();
1547 if (Primitive::IsFloatingPointType(type)) {
1548 return;
1549 }
1550
Roland Levillain1a653882016-03-18 18:05:57 +00001551 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001552 // Replace code looking like
1553 // SUB dst, src, 0
1554 // with
1555 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001556 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1557 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1558 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001559 instruction->ReplaceWith(input_other);
1560 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001561 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001562 return;
1563 }
1564
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001565 HBasicBlock* block = instruction->GetBlock();
1566 ArenaAllocator* allocator = GetGraph()->GetArena();
1567
Alexandre Rames188d4312015-04-09 18:30:21 +01001568 HInstruction* left = instruction->GetLeft();
1569 HInstruction* right = instruction->GetRight();
1570 if (left->IsConstant()) {
1571 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001572 // Replace code looking like
1573 // SUB dst, 0, src
1574 // with
1575 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001576 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001577 // `x` is `0.0`, the former expression yields `0.0`, while the later
1578 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001579 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001580 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001581 RecordSimplification();
1582 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001583 }
1584 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001585
1586 if (left->IsNeg() && right->IsNeg()) {
1587 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1588 return;
1589 }
1590 }
1591
1592 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1593 // Replace code looking like
1594 // NEG tmp, b
1595 // SUB dst, a, tmp
1596 // with
1597 // ADD dst, a, b
1598 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1599 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1600 RecordSimplification();
1601 right->GetBlock()->RemoveInstruction(right);
1602 return;
1603 }
1604
1605 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1606 // Replace code looking like
1607 // NEG tmp, a
1608 // SUB dst, tmp, b
1609 // with
1610 // ADD tmp, a, b
1611 // NEG dst, tmp
1612 // The second version is not intrinsically better, but enables more
1613 // transformations.
1614 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1615 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1616 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1617 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1618 instruction->ReplaceWith(neg);
1619 instruction->GetBlock()->RemoveInstruction(instruction);
1620 RecordSimplification();
1621 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001622 return;
1623 }
1624
1625 if (TrySubtractionChainSimplification(instruction)) {
1626 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001627 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001628
1629 if (left->IsAdd()) {
1630 // Replace code patterns looking like
1631 // ADD dst1, x, y ADD dst1, x, y
1632 // SUB dst2, dst1, y SUB dst2, dst1, x
1633 // with
1634 // ADD dst1, x, y
1635 // SUB instruction is not needed in this case, we may use
1636 // one of inputs of ADD instead.
1637 // It is applicable to integral types only.
1638 DCHECK(Primitive::IsIntegralType(type));
1639 if (left->InputAt(1) == right) {
1640 instruction->ReplaceWith(left->InputAt(0));
1641 RecordSimplification();
1642 instruction->GetBlock()->RemoveInstruction(instruction);
1643 return;
1644 } else if (left->InputAt(0) == right) {
1645 instruction->ReplaceWith(left->InputAt(1));
1646 RecordSimplification();
1647 instruction->GetBlock()->RemoveInstruction(instruction);
1648 return;
1649 }
1650 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001651}
1652
1653void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1654 VisitShift(instruction);
1655}
1656
1657void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1658 HConstant* input_cst = instruction->GetConstantRight();
1659 HInstruction* input_other = instruction->GetLeastConstantLeft();
1660
Roland Levillain1a653882016-03-18 18:05:57 +00001661 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001662 // Replace code looking like
1663 // XOR dst, src, 0
1664 // with
1665 // src
1666 instruction->ReplaceWith(input_other);
1667 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001668 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001669 return;
1670 }
1671
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001672 if ((input_cst != nullptr) && input_cst->IsOne()
1673 && input_other->GetType() == Primitive::kPrimBoolean) {
1674 // Replace code looking like
1675 // XOR dst, src, 1
1676 // with
1677 // BOOLEAN_NOT dst, src
1678 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1679 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1680 RecordSimplification();
1681 return;
1682 }
1683
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001684 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1685 // Replace code looking like
1686 // XOR dst, src, 0xFFF...FF
1687 // with
1688 // NOT dst, src
1689 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1690 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001691 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001692 return;
1693 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001694
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001695 HInstruction* left = instruction->GetLeft();
1696 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001697 if (((left->IsNot() && right->IsNot()) ||
1698 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001699 left->HasOnlyOneNonEnvironmentUse() &&
1700 right->HasOnlyOneNonEnvironmentUse()) {
1701 // Replace code looking like
1702 // NOT nota, a
1703 // NOT notb, b
1704 // XOR dst, nota, notb
1705 // with
1706 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001707 instruction->ReplaceInput(left->InputAt(0), 0);
1708 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001709 left->GetBlock()->RemoveInstruction(left);
1710 right->GetBlock()->RemoveInstruction(right);
1711 RecordSimplification();
1712 return;
1713 }
1714
Anton Kirilove14dc862016-05-13 17:56:15 +01001715 if (TryReplaceWithRotate(instruction)) {
1716 return;
1717 }
1718
1719 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1720 // so no need to return.
1721 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001722}
1723
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001724void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1725 HInstruction* argument = instruction->InputAt(1);
1726 HInstruction* receiver = instruction->InputAt(0);
1727 if (receiver == argument) {
1728 // Because String.equals is an instance call, the receiver is
1729 // a null check if we don't know it's null. The argument however, will
1730 // be the actual object. So we cannot end up in a situation where both
1731 // are equal but could be null.
1732 DCHECK(CanEnsureNotNullAt(argument, instruction));
1733 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1734 instruction->GetBlock()->RemoveInstruction(instruction);
1735 } else {
1736 StringEqualsOptimizations optimizations(instruction);
1737 if (CanEnsureNotNullAt(argument, instruction)) {
1738 optimizations.SetArgumentNotNull();
1739 }
1740 ScopedObjectAccess soa(Thread::Current());
1741 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1742 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1743 optimizations.SetArgumentIsString();
1744 }
1745 }
1746}
1747
Roland Levillain22c49222016-03-18 14:04:28 +00001748void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1749 bool is_left,
1750 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001751 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001752 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001753 HInstruction* value = invoke->InputAt(0);
1754 HInstruction* distance = invoke->InputAt(1);
1755 // Replace the invoke with an HRor.
1756 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001757 // Unconditionally set the type of the negated distance to `int`,
1758 // as shift and rotate operations expect a 32-bit (or narrower)
1759 // value for their distance input.
1760 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001761 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1762 }
Roland Levillain22c49222016-03-18 14:04:28 +00001763 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001764 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1765 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001766 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001767 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1768 clinit->GetBlock()->RemoveInstruction(clinit);
1769 HInstruction* ldclass = clinit->InputAt(0);
1770 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1771 ldclass->GetBlock()->RemoveInstruction(ldclass);
1772 }
1773 }
1774}
1775
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001776static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1777 if (potential_length->IsArrayLength()) {
1778 return potential_length->InputAt(0) == potential_array;
1779 }
1780
1781 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001782 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001783 }
1784
1785 return false;
1786}
1787
1788void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1789 HInstruction* source = instruction->InputAt(0);
1790 HInstruction* destination = instruction->InputAt(2);
1791 HInstruction* count = instruction->InputAt(4);
1792 SystemArrayCopyOptimizations optimizations(instruction);
1793 if (CanEnsureNotNullAt(source, instruction)) {
1794 optimizations.SetSourceIsNotNull();
1795 }
1796 if (CanEnsureNotNullAt(destination, instruction)) {
1797 optimizations.SetDestinationIsNotNull();
1798 }
1799 if (destination == source) {
1800 optimizations.SetDestinationIsSource();
1801 }
1802
1803 if (IsArrayLengthOf(count, source)) {
1804 optimizations.SetCountIsSourceLength();
1805 }
1806
1807 if (IsArrayLengthOf(count, destination)) {
1808 optimizations.SetCountIsDestinationLength();
1809 }
1810
1811 {
1812 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001813 Primitive::Type source_component_type = Primitive::kPrimVoid;
1814 Primitive::Type destination_component_type = Primitive::kPrimVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001815 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1816 if (destination_rti.IsValid()) {
1817 if (destination_rti.IsObjectArray()) {
1818 if (destination_rti.IsExact()) {
1819 optimizations.SetDoesNotNeedTypeCheck();
1820 }
1821 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001822 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001823 if (destination_rti.IsPrimitiveArrayClass()) {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001824 destination_component_type =
1825 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001826 optimizations.SetDestinationIsPrimitiveArray();
1827 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1828 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001829 }
1830 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001831 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1832 if (source_rti.IsValid()) {
1833 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1834 optimizations.SetDoesNotNeedTypeCheck();
1835 }
1836 if (source_rti.IsPrimitiveArrayClass()) {
1837 optimizations.SetSourceIsPrimitiveArray();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001838 source_component_type = source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001839 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1840 optimizations.SetSourceIsNonPrimitiveArray();
1841 }
1842 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001843 // For primitive arrays, use their optimized ArtMethod implementations.
1844 if ((source_component_type != Primitive::kPrimVoid) &&
1845 (source_component_type == destination_component_type)) {
1846 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1847 PointerSize image_size = class_linker->GetImagePointerSize();
1848 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1849 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
1850 ArtMethod* method = nullptr;
1851 switch (source_component_type) {
1852 case Primitive::kPrimBoolean:
1853 method = system->FindDeclaredDirectMethod("arraycopy", "([ZI[ZII)V", image_size);
1854 break;
1855 case Primitive::kPrimByte:
1856 method = system->FindDeclaredDirectMethod("arraycopy", "([BI[BII)V", image_size);
1857 break;
1858 case Primitive::kPrimChar:
1859 method = system->FindDeclaredDirectMethod("arraycopy", "([CI[CII)V", image_size);
1860 break;
1861 case Primitive::kPrimShort:
1862 method = system->FindDeclaredDirectMethod("arraycopy", "([SI[SII)V", image_size);
1863 break;
1864 case Primitive::kPrimInt:
1865 method = system->FindDeclaredDirectMethod("arraycopy", "([II[III)V", image_size);
1866 break;
1867 case Primitive::kPrimFloat:
1868 method = system->FindDeclaredDirectMethod("arraycopy", "([FI[FII)V", image_size);
1869 break;
1870 case Primitive::kPrimLong:
1871 method = system->FindDeclaredDirectMethod("arraycopy", "([JI[JII)V", image_size);
1872 break;
1873 case Primitive::kPrimDouble:
1874 method = system->FindDeclaredDirectMethod("arraycopy", "([DI[DII)V", image_size);
1875 break;
1876 default:
1877 LOG(FATAL) << "Unreachable";
1878 }
1879 DCHECK(method != nullptr);
1880 invoke->SetResolvedMethod(method);
1881 // Sharpen the new invoke. Note that we do not update the dex method index of
1882 // the invoke, as we would need to look it up in the current dex file, and it
1883 // is unlikely that it exists. The most usual situation for such typed
1884 // arraycopy methods is a direct pointer to the boot image.
1885 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_);
1886 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001887 }
1888}
1889
Roland Levillaina5c4a402016-03-15 15:02:50 +00001890void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1891 bool is_signum,
1892 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001893 DCHECK(invoke->IsInvokeStaticOrDirect());
1894 uint32_t dex_pc = invoke->GetDexPc();
1895 HInstruction* left = invoke->InputAt(0);
1896 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001897 if (!is_signum) {
1898 right = invoke->InputAt(1);
1899 } else if (type == Primitive::kPrimLong) {
1900 right = GetGraph()->GetLongConstant(0);
1901 } else {
1902 right = GetGraph()->GetIntConstant(0);
1903 }
1904 HCompare* compare = new (GetGraph()->GetArena())
1905 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1906 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1907}
1908
Aart Bik75a38b22016-02-17 10:41:50 -08001909void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1910 DCHECK(invoke->IsInvokeStaticOrDirect());
1911 uint32_t dex_pc = invoke->GetDexPc();
1912 // IsNaN(x) is the same as x != x.
1913 HInstruction* x = invoke->InputAt(0);
1914 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001915 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001916 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1917}
1918
Aart Bik2a6aad92016-02-25 11:32:32 -08001919void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1920 DCHECK(invoke->IsInvokeStaticOrDirect());
1921 uint32_t dex_pc = invoke->GetDexPc();
1922 HInstruction* x = invoke->InputAt(0);
1923 Primitive::Type type = x->GetType();
1924 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1925 HInstruction* nan;
1926 if (type == Primitive::kPrimDouble) {
1927 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1928 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1929 kNeedsEnvironmentOrCache,
1930 kNoSideEffects,
1931 kNoThrow);
1932 } else {
1933 DCHECK_EQ(type, Primitive::kPrimFloat);
1934 nan = GetGraph()->GetIntConstant(0x7fc00000);
1935 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1936 kNeedsEnvironmentOrCache,
1937 kNoSideEffects,
1938 kNoThrow);
1939 }
1940 // Test IsNaN(x), which is the same as x != x.
1941 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1942 condition->SetBias(ComparisonBias::kLtBias);
1943 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1944 // Select between the two.
1945 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1946 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1947 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1948}
1949
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001950void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1951 HInstruction* str = invoke->InputAt(0);
1952 HInstruction* index = invoke->InputAt(1);
1953 uint32_t dex_pc = invoke->GetDexPc();
1954 ArenaAllocator* arena = GetGraph()->GetArena();
1955 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1956 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1957 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1958 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00001959 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
1960 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001961 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00001962 HArrayGet* array_get = new (arena) HArrayGet(
1963 str, bounds_check, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001964 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1965 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1966 GetGraph()->SetHasBoundsChecks(true);
1967}
1968
Vladimir Markodce016e2016-04-28 13:10:02 +01001969void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1970 HInstruction* str = invoke->InputAt(0);
1971 uint32_t dex_pc = invoke->GetDexPc();
1972 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1973 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001974 HArrayLength* length =
1975 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001976 HInstruction* replacement;
1977 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1978 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1979 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1980 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1981 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1982 replacement = equal;
1983 } else {
1984 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1985 replacement = length;
1986 }
1987 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1988}
1989
Aart Bikff7d89c2016-11-07 08:49:28 -08001990// This method should only be used on intrinsics whose sole way of throwing an
1991// exception is raising a NPE when the nth argument is null. If that argument
1992// is provably non-null, we can clear the flag.
1993void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
1994 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08001995 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08001996 invoke->SetCanThrow(false);
1997 }
1998}
1999
Aart Bik71bf7b42016-11-16 10:17:46 -08002000// Methods that return "this" can replace the returned value with the receiver.
2001void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2002 if (invoke->HasUses()) {
2003 HInstruction* receiver = invoke->InputAt(0);
2004 invoke->ReplaceWith(receiver);
2005 RecordSimplification();
2006 }
2007}
2008
2009// Helper method for StringBuffer escape analysis.
2010static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2011 if (user->IsInvokeStaticOrDirect()) {
2012 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002013 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2014 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002015 user->InputAt(0) == reference;
2016 } else if (user->IsInvokeVirtual()) {
2017 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2018 case Intrinsics::kStringBufferLength:
2019 case Intrinsics::kStringBufferToString:
2020 DCHECK_EQ(user->InputAt(0), reference);
2021 return true;
2022 case Intrinsics::kStringBufferAppend:
2023 // Returns "this", so only okay if no further uses.
2024 DCHECK_EQ(user->InputAt(0), reference);
2025 DCHECK_NE(user->InputAt(1), reference);
2026 return !user->HasUses();
2027 default:
2028 break;
2029 }
2030 }
2031 return false;
2032}
2033
2034// Certain allocation intrinsics are not removed by dead code elimination
2035// because of potentially throwing an OOM exception or other side effects.
2036// This method removes such intrinsics when special circumstances allow.
2037void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2038 if (!invoke->HasUses()) {
2039 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2040 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2041 // call does not escape since only thread-local synchronization may be removed.
2042 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2043 HInstruction* receiver = invoke->InputAt(0);
2044 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2045 invoke->GetBlock()->RemoveInstruction(invoke);
2046 RecordSimplification();
2047 }
2048 }
2049}
2050
Aart Bik11932592016-03-08 12:42:25 -08002051void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2052 uint32_t dex_pc = invoke->GetDexPc();
2053 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2054 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2055}
2056
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002057void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002058 switch (instruction->GetIntrinsic()) {
2059 case Intrinsics::kStringEquals:
2060 SimplifyStringEquals(instruction);
2061 break;
2062 case Intrinsics::kSystemArrayCopy:
2063 SimplifySystemArrayCopy(instruction);
2064 break;
2065 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002066 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
2067 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002068 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002069 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002070 break;
2071 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002072 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
2073 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002074 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002075 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002076 break;
2077 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002078 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
2079 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002080 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002081 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002082 break;
2083 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002084 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
2085 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002086 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002087 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002088 break;
2089 case Intrinsics::kFloatIsNaN:
2090 case Intrinsics::kDoubleIsNaN:
2091 SimplifyIsNaN(instruction);
2092 break;
2093 case Intrinsics::kFloatFloatToIntBits:
2094 case Intrinsics::kDoubleDoubleToLongBits:
2095 SimplifyFP2Int(instruction);
2096 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002097 case Intrinsics::kStringCharAt:
2098 SimplifyStringCharAt(instruction);
2099 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002100 case Intrinsics::kStringIsEmpty:
2101 case Intrinsics::kStringLength:
2102 SimplifyStringIsEmptyOrLength(instruction);
2103 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002104 case Intrinsics::kStringStringIndexOf:
2105 case Intrinsics::kStringStringIndexOfAfter:
2106 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2107 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002108 case Intrinsics::kStringBufferAppend:
2109 case Intrinsics::kStringBuilderAppend:
2110 SimplifyReturnThis(instruction);
2111 break;
2112 case Intrinsics::kStringBufferToString:
2113 case Intrinsics::kStringBuilderToString:
2114 SimplifyAllocationIntrinsic(instruction);
2115 break;
Aart Bik11932592016-03-08 12:42:25 -08002116 case Intrinsics::kUnsafeLoadFence:
2117 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2118 break;
2119 case Intrinsics::kUnsafeStoreFence:
2120 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2121 break;
2122 case Intrinsics::kUnsafeFullFence:
2123 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2124 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002125 default:
2126 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002127 }
2128}
2129
Aart Bikbb245d12015-10-19 11:05:03 -07002130void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2131 HInstruction* cond = deoptimize->InputAt(0);
2132 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002133 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002134 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002135 if (deoptimize->GuardsAnInput()) {
2136 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2137 }
Aart Bikbb245d12015-10-19 11:05:03 -07002138 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2139 } else {
2140 // Always deopt.
2141 }
2142 }
2143}
2144
Anton Kirilove14dc862016-05-13 17:56:15 +01002145// Replace code looking like
2146// OP y, x, const1
2147// OP z, y, const2
2148// with
2149// OP z, x, const3
2150// where OP is both an associative and a commutative operation.
2151bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2152 HBinaryOperation* instruction) {
2153 DCHECK(instruction->IsCommutative());
2154
2155 if (!Primitive::IsIntegralType(instruction->GetType())) {
2156 return false;
2157 }
2158
2159 HInstruction* left = instruction->GetLeft();
2160 HInstruction* right = instruction->GetRight();
2161 // Variable names as described above.
2162 HConstant* const2;
2163 HBinaryOperation* y;
2164
2165 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2166 const2 = right->AsConstant();
2167 y = left->AsBinaryOperation();
2168 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2169 const2 = left->AsConstant();
2170 y = right->AsBinaryOperation();
2171 } else {
2172 // The node does not match the pattern.
2173 return false;
2174 }
2175
2176 // If `y` has more than one use, we do not perform the optimization
2177 // because it might increase code size (e.g. if the new constant is
2178 // no longer encodable as an immediate operand in the target ISA).
2179 if (!y->HasOnlyOneNonEnvironmentUse()) {
2180 return false;
2181 }
2182
2183 // GetConstantRight() can return both left and right constants
2184 // for commutative operations.
2185 HConstant* const1 = y->GetConstantRight();
2186 if (const1 == nullptr) {
2187 return false;
2188 }
2189
2190 instruction->ReplaceInput(const1, 0);
2191 instruction->ReplaceInput(const2, 1);
2192 HConstant* const3 = instruction->TryStaticEvaluation();
2193 DCHECK(const3 != nullptr);
2194 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2195 instruction->ReplaceInput(const3, 1);
2196 RecordSimplification();
2197 return true;
2198}
2199
2200static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2201 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2202}
2203
2204// Helper function that performs addition statically, considering the result type.
2205static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
2206 // Use the Compute() method for consistency with TryStaticEvaluation().
2207 if (type == Primitive::kPrimInt) {
2208 return HAdd::Compute<int32_t>(x, y);
2209 } else {
2210 DCHECK_EQ(type, Primitive::kPrimLong);
2211 return HAdd::Compute<int64_t>(x, y);
2212 }
2213}
2214
2215// Helper function that handles the child classes of HConstant
2216// and returns an integer with the appropriate sign.
2217static int64_t GetValue(HConstant* constant, bool is_negated) {
2218 int64_t ret = Int64FromConstant(constant);
2219 return is_negated ? -ret : ret;
2220}
2221
2222// Replace code looking like
2223// OP1 y, x, const1
2224// OP2 z, y, const2
2225// with
2226// OP3 z, x, const3
2227// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2228bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2229 HBinaryOperation* instruction) {
2230 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2231
2232 Primitive::Type type = instruction->GetType();
2233 if (!Primitive::IsIntegralType(type)) {
2234 return false;
2235 }
2236
2237 HInstruction* left = instruction->GetLeft();
2238 HInstruction* right = instruction->GetRight();
2239 // Variable names as described above.
2240 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2241 if (const2 == nullptr) {
2242 return false;
2243 }
2244
2245 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2246 ? left->AsBinaryOperation()
2247 : AsAddOrSub(right);
2248 // If y has more than one use, we do not perform the optimization because
2249 // it might increase code size (e.g. if the new constant is no longer
2250 // encodable as an immediate operand in the target ISA).
2251 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2252 return false;
2253 }
2254
2255 left = y->GetLeft();
2256 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2257 if (const1 == nullptr) {
2258 return false;
2259 }
2260
2261 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2262 // If both inputs are constants, let the constant folding pass deal with it.
2263 if (x->IsConstant()) {
2264 return false;
2265 }
2266
2267 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2268 int64_t const2_val = GetValue(const2, is_const2_negated);
2269 bool is_y_negated = (y == right) && instruction->IsSub();
2270 right = y->GetRight();
2271 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2272 int64_t const1_val = GetValue(const1, is_const1_negated);
2273 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2274 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2275 HBasicBlock* block = instruction->GetBlock();
2276 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2277 ArenaAllocator* arena = instruction->GetArena();
2278 HInstruction* z;
2279
2280 if (is_x_negated) {
2281 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2282 } else {
2283 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2284 }
2285
2286 block->ReplaceAndRemoveInstructionWith(instruction, z);
2287 RecordSimplification();
2288 return true;
2289}
2290
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002291} // namespace art