blob: e0410dcdb23c39be186bf95cb6e6f0c6f2236ac9 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000037 MaybeRecordStat(kInstructionSimplifications);
38 }
39
40 void MaybeRecordStat(MethodCompilationStat stat) {
41 if (stats_ != nullptr) {
42 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010043 }
44 }
45
Scott Wakeling40a04bf2015-12-11 09:50:36 +000046 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47 bool TryReplaceWithRotate(HBinaryOperation* instruction);
48 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
49 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51
Alexandre Rames188d4312015-04-09 18:30:21 +010052 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000053 // `op` should be either HOr or HAnd.
54 // De Morgan's laws:
55 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
56 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010057 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
58 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
59
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000060 void VisitShift(HBinaryOperation* shift);
61
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000062 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010063 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
64 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010065 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
66 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000068 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000069 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080070 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000071 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000072 void VisitAdd(HAdd* instruction) OVERRIDE;
73 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040074 void VisitCondition(HCondition* instruction) OVERRIDE;
75 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
76 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
77 void VisitLessThan(HLessThan* condition) OVERRIDE;
78 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060079 void VisitBelow(HBelow* condition) OVERRIDE;
80 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
81 void VisitAbove(HAbove* condition) OVERRIDE;
82 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000083 void VisitDiv(HDiv* instruction) OVERRIDE;
84 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010085 void VisitNeg(HNeg* instruction) OVERRIDE;
86 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000087 void VisitOr(HOr* instruction) OVERRIDE;
88 void VisitShl(HShl* instruction) OVERRIDE;
89 void VisitShr(HShr* instruction) OVERRIDE;
90 void VisitSub(HSub* instruction) OVERRIDE;
91 void VisitUShr(HUShr* instruction) OVERRIDE;
92 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000093 void VisitSelect(HSelect* select) OVERRIDE;
94 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010095 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010096 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070097 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010098
99 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000100
Roland Levillain22c49222016-03-18 14:04:28 +0000101 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100102 void SimplifySystemArrayCopy(HInvoke* invoke);
103 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000104 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800105 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800106 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100107 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100108 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800109 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100110
Calin Juravleacf735c2015-02-12 15:25:22 +0000111 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100112 bool simplification_occurred_ = false;
113 int simplifications_at_current_position_ = 0;
114 // We ensure we do not loop infinitely. The value is a finger in the air guess
115 // that should allow enough simplification.
116 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000117};
118
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100119void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000120 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100121 visitor.Run();
122}
123
124void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100125 // Iterate in reverse post order to open up more simplifications to users
126 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100127 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
128 // The simplification of an instruction to another instruction may yield
129 // possibilities for other simplifications. So although we perform a reverse
130 // post order visit, we sometimes need to revisit an instruction index.
131 simplification_occurred_ = false;
132 VisitBasicBlock(it.Current());
133 if (simplification_occurred_ &&
134 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
135 // New simplifications may be applicable to the instruction at the
136 // current index, so don't advance the iterator.
137 continue;
138 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100139 simplifications_at_current_position_ = 0;
140 it.Advance();
141 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100142}
143
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000144namespace {
145
146bool AreAllBitsSet(HConstant* constant) {
147 return Int64FromConstant(constant) == -1;
148}
149
150} // namespace
151
Alexandre Rames188d4312015-04-09 18:30:21 +0100152// Returns true if the code was simplified to use only one negation operation
153// after the binary operation instead of one on each of the inputs.
154bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
155 DCHECK(binop->IsAdd() || binop->IsSub());
156 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
157 HNeg* left_neg = binop->GetLeft()->AsNeg();
158 HNeg* right_neg = binop->GetRight()->AsNeg();
159 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
160 !right_neg->HasOnlyOneNonEnvironmentUse()) {
161 return false;
162 }
163 // Replace code looking like
164 // NEG tmp1, a
165 // NEG tmp2, b
166 // ADD dst, tmp1, tmp2
167 // with
168 // ADD tmp, a, b
169 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600170 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
171 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
172 // while the later yields `-0.0`.
173 if (!Primitive::IsIntegralType(binop->GetType())) {
174 return false;
175 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100176 binop->ReplaceInput(left_neg->GetInput(), 0);
177 binop->ReplaceInput(right_neg->GetInput(), 1);
178 left_neg->GetBlock()->RemoveInstruction(left_neg);
179 right_neg->GetBlock()->RemoveInstruction(right_neg);
180 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
181 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
182 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
183 RecordSimplification();
184 return true;
185}
186
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000187bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
188 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
189 Primitive::Type type = op->GetType();
190 HInstruction* left = op->GetLeft();
191 HInstruction* right = op->GetRight();
192
193 // We can apply De Morgan's laws if both inputs are Not's and are only used
194 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000195 if (((left->IsNot() && right->IsNot()) ||
196 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000197 left->HasOnlyOneNonEnvironmentUse() &&
198 right->HasOnlyOneNonEnvironmentUse()) {
199 // Replace code looking like
200 // NOT nota, a
201 // NOT notb, b
202 // AND dst, nota, notb (respectively OR)
203 // with
204 // OR or, a, b (respectively AND)
205 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000206 HInstruction* src_left = left->InputAt(0);
207 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000208 uint32_t dex_pc = op->GetDexPc();
209
210 // Remove the negations on the inputs.
211 left->ReplaceWith(src_left);
212 right->ReplaceWith(src_right);
213 left->GetBlock()->RemoveInstruction(left);
214 right->GetBlock()->RemoveInstruction(right);
215
216 // Replace the `HAnd` or `HOr`.
217 HBinaryOperation* hbin;
218 if (op->IsAnd()) {
219 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
220 } else {
221 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
222 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000223 HInstruction* hnot;
224 if (left->IsBooleanNot()) {
225 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
226 } else {
227 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
228 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000229
230 op->GetBlock()->InsertInstructionBefore(hbin, op);
231 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
232
233 RecordSimplification();
234 return true;
235 }
236
237 return false;
238}
239
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000240void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
241 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100242 HInstruction* shift_amount = instruction->GetRight();
243 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000244
Alexandre Rames50518442016-06-27 11:39:19 +0100245 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
246 ? kMaxLongShiftDistance
247 : kMaxIntShiftDistance;
248
249 if (shift_amount->IsConstant()) {
250 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
251 if ((cst & implicit_mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400252 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100253 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400254 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100255 // value
256 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400257 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100258 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100259 return;
260 }
261 }
262
263 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
264 // unnecessary explicit masking operations on the shift amount.
265 // Replace code looking like
266 // AND masked_shift, shift, <superset of implicit mask>
267 // SHL dst, value, masked_shift
268 // with
269 // SHL dst, value, shift
270 if (shift_amount->IsAnd()) {
271 HAnd* and_insn = shift_amount->AsAnd();
272 HConstant* mask = and_insn->GetConstantRight();
273 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
274 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
275 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400276 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000277 }
278}
279
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000280static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
281 return (sub->GetRight() == other &&
282 sub->GetLeft()->IsConstant() &&
283 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
284}
285
286bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
287 HUShr* ushr,
288 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000289 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
290 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000291 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
292 if (!ushr->HasUses()) {
293 ushr->GetBlock()->RemoveInstruction(ushr);
294 }
295 if (!ushr->GetRight()->HasUses()) {
296 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
297 }
298 if (!shl->HasUses()) {
299 shl->GetBlock()->RemoveInstruction(shl);
300 }
301 if (!shl->GetRight()->HasUses()) {
302 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
303 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100304 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000305 return true;
306}
307
308// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
309bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000310 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
311 HInstruction* left = op->GetLeft();
312 HInstruction* right = op->GetRight();
313 // If we have an UShr and a Shl (in either order).
314 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
315 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
316 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
317 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
318 if (ushr->GetType() == shl->GetType() &&
319 ushr->GetLeft() == shl->GetLeft()) {
320 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
321 // Shift distances are both constant, try replacing with Ror if they
322 // add up to the register size.
323 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
324 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
325 // Shift distances are potentially of the form x and (reg_size - x).
326 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
327 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
328 // Shift distances are potentially of the form d and -d.
329 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
330 }
331 }
332 }
333 return false;
334}
335
336// Try replacing code looking like (x >>> #rdist OP x << #ldist):
337// UShr dst, x, #rdist
338// Shl tmp, x, #ldist
339// OP dst, dst, tmp
340// or like (x >>> #rdist OP x << #-ldist):
341// UShr dst, x, #rdist
342// Shl tmp, x, #-ldist
343// OP dst, dst, tmp
344// with
345// Ror dst, x, #rdist
346bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
347 HUShr* ushr,
348 HShl* shl) {
349 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
350 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
351 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
352 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
353 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
354 ReplaceRotateWithRor(op, ushr, shl);
355 return true;
356 }
357 return false;
358}
359
360// Replace code looking like (x >>> -d OP x << d):
361// Neg neg, d
362// UShr dst, x, neg
363// Shl tmp, x, d
364// OP dst, dst, tmp
365// with
366// Neg neg, d
367// Ror dst, x, neg
368// *** OR ***
369// Replace code looking like (x >>> d OP x << -d):
370// UShr dst, x, d
371// Neg neg, d
372// Shl tmp, x, neg
373// OP dst, dst, tmp
374// with
375// Ror dst, x, d
376bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
377 HUShr* ushr,
378 HShl* shl) {
379 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
380 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
381 bool neg_is_left = shl->GetRight()->IsNeg();
382 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
383 // And the shift distance being negated is the distance being shifted the other way.
384 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
385 ReplaceRotateWithRor(op, ushr, shl);
386 }
387 return false;
388}
389
390// Try replacing code looking like (x >>> d OP x << (#bits - d)):
391// UShr dst, x, d
392// Sub ld, #bits, d
393// Shl tmp, x, ld
394// OP dst, dst, tmp
395// with
396// Ror dst, x, d
397// *** OR ***
398// Replace code looking like (x >>> (#bits - d) OP x << d):
399// Sub rd, #bits, d
400// UShr dst, x, rd
401// Shl tmp, x, d
402// OP dst, dst, tmp
403// with
404// Neg neg, d
405// Ror dst, x, neg
406bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
407 HUShr* ushr,
408 HShl* shl) {
409 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
410 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
411 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
412 HInstruction* shl_shift = shl->GetRight();
413 HInstruction* ushr_shift = ushr->GetRight();
414 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
415 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
416 return ReplaceRotateWithRor(op, ushr, shl);
417 }
418 return false;
419}
420
Calin Juravle10e244f2015-01-26 18:54:32 +0000421void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
422 HInstruction* obj = null_check->InputAt(0);
423 if (!obj->CanBeNull()) {
424 null_check->ReplaceWith(obj);
425 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000426 if (stats_ != nullptr) {
427 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
428 }
429 }
430}
431
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100432bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
433 if (!input->CanBeNull()) {
434 return true;
435 }
436
Vladimir Marko46817b82016-03-29 12:21:58 +0100437 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
438 HInstruction* user = use.GetUser();
439 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100440 return true;
441 }
442 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100443
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100444 return false;
445}
446
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100447// Returns whether doing a type test between the class of `object` against `klass` has
448// a statically known outcome. The result of the test is stored in `outcome`.
449static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000450 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
451 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
452 ScopedObjectAccess soa(Thread::Current());
453 if (!obj_rti.IsValid()) {
454 // We run the simplifier before the reference type propagation so type info might not be
455 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100456 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000457 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100458
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100459 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100460 if (!class_rti.IsValid()) {
461 // Happens when the loaded class is unresolved.
462 return false;
463 }
464 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000465 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100466 *outcome = true;
467 return true;
468 } else if (obj_rti.IsExact()) {
469 // The test failed at compile time so will also fail at runtime.
470 *outcome = false;
471 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100472 } else if (!class_rti.IsInterface()
473 && !obj_rti.IsInterface()
474 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100475 // Different type hierarchy. The test will fail.
476 *outcome = false;
477 return true;
478 }
479 return false;
480}
481
482void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
483 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100484 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
485 if (load_class->NeedsAccessCheck()) {
486 // If we need to perform an access check we cannot remove the instruction.
487 return;
488 }
489
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100490 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100491 check_cast->ClearMustDoNullCheck();
492 }
493
494 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000495 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000496 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100497 return;
498 }
499
Vladimir Markoa65ed302016-03-14 21:21:29 +0000500 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
501 // the return value check with the `outcome` check, b/27651442 .
502 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700503 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100504 if (outcome) {
505 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000506 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700507 if (!load_class->HasUses()) {
508 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
509 // However, here we know that it cannot because the checkcast was successfull, hence
510 // the class was already loaded.
511 load_class->GetBlock()->RemoveInstruction(load_class);
512 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100513 } else {
514 // Don't do anything for exceptional cases for now. Ideally we should remove
515 // all instructions and blocks this instruction dominates.
516 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000517 }
518}
519
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100520void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100521 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100522 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
523 if (load_class->NeedsAccessCheck()) {
524 // If we need to perform an access check we cannot remove the instruction.
525 return;
526 }
527
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100528 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100529 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100530 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100531 instruction->ClearMustDoNullCheck();
532 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100533
534 HGraph* graph = GetGraph();
535 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000536 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100537 instruction->ReplaceWith(graph->GetIntConstant(0));
538 instruction->GetBlock()->RemoveInstruction(instruction);
539 RecordSimplification();
540 return;
541 }
542
Vladimir Marko24bd8952016-03-15 10:40:33 +0000543 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
544 // the return value check with the `outcome` check, b/27651442 .
545 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700546 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000547 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100548 if (outcome && can_be_null) {
549 // Type test will succeed, we just need a null test.
550 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
551 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
552 instruction->ReplaceWith(test);
553 } else {
554 // We've statically determined the result of the instanceof.
555 instruction->ReplaceWith(graph->GetIntConstant(outcome));
556 }
557 RecordSimplification();
558 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700559 if (outcome && !load_class->HasUses()) {
560 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
561 // However, here we know that it cannot because the instanceof check was successfull, hence
562 // the class was already loaded.
563 load_class->GetBlock()->RemoveInstruction(load_class);
564 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100565 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100566}
567
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100568void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
569 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100570 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100571 instruction->ClearValueCanBeNull();
572 }
573}
574
575void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* 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
Anton Shaminbdd79352016-02-15 12:48:36 +0600582static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
583 HInstruction *lhs = cond->InputAt(0);
584 HInstruction *rhs = cond->InputAt(1);
585 switch (cond->GetKind()) {
586 case HInstruction::kEqual:
587 return new (arena) HEqual(rhs, lhs);
588 case HInstruction::kNotEqual:
589 return new (arena) HNotEqual(rhs, lhs);
590 case HInstruction::kLessThan:
591 return new (arena) HGreaterThan(rhs, lhs);
592 case HInstruction::kLessThanOrEqual:
593 return new (arena) HGreaterThanOrEqual(rhs, lhs);
594 case HInstruction::kGreaterThan:
595 return new (arena) HLessThan(rhs, lhs);
596 case HInstruction::kGreaterThanOrEqual:
597 return new (arena) HLessThanOrEqual(rhs, lhs);
598 case HInstruction::kBelow:
599 return new (arena) HAbove(rhs, lhs);
600 case HInstruction::kBelowOrEqual:
601 return new (arena) HAboveOrEqual(rhs, lhs);
602 case HInstruction::kAbove:
603 return new (arena) HBelow(rhs, lhs);
604 case HInstruction::kAboveOrEqual:
605 return new (arena) HBelowOrEqual(rhs, lhs);
606 default:
607 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
608 }
609 return nullptr;
610}
611
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000612void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100613 HInstruction* input_const = equal->GetConstantRight();
614 if (input_const != nullptr) {
615 HInstruction* input_value = equal->GetLeastConstantLeft();
616 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
617 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100618 // We are comparing the boolean to a constant which is of type int and can
619 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000620 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100621 // Replace (bool_value == true) with bool_value
622 equal->ReplaceWith(input_value);
623 block->RemoveInstruction(equal);
624 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000625 } else if (input_const->AsIntConstant()->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500626 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
627 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100628 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100629 } else {
630 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
631 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
632 block->RemoveInstruction(equal);
633 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100634 }
Mark Mendellc4701932015-04-10 13:18:51 -0400635 } else {
636 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100637 }
Mark Mendellc4701932015-04-10 13:18:51 -0400638 } else {
639 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100640 }
641}
642
David Brazdil0d13fee2015-04-17 14:52:19 +0100643void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
644 HInstruction* input_const = not_equal->GetConstantRight();
645 if (input_const != nullptr) {
646 HInstruction* input_value = not_equal->GetLeastConstantLeft();
647 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
648 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100649 // We are comparing the boolean to a constant which is of type int and can
650 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000651 if (input_const->AsIntConstant()->IsTrue()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500652 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
653 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100654 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000655 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100656 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100657 not_equal->ReplaceWith(input_value);
658 block->RemoveInstruction(not_equal);
659 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100660 } else {
661 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
662 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
663 block->RemoveInstruction(not_equal);
664 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100665 }
Mark Mendellc4701932015-04-10 13:18:51 -0400666 } else {
667 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100668 }
Mark Mendellc4701932015-04-10 13:18:51 -0400669 } else {
670 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100671 }
672}
673
674void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000675 HInstruction* input = bool_not->InputAt(0);
676 HInstruction* replace_with = nullptr;
677
678 if (input->IsIntConstant()) {
679 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000680 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000681 replace_with = GetGraph()->GetIntConstant(0);
682 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000683 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000684 replace_with = GetGraph()->GetIntConstant(1);
685 }
686 } else if (input->IsBooleanNot()) {
687 // Replace (!(!bool_value)) with bool_value.
688 replace_with = input->InputAt(0);
689 } else if (input->IsCondition() &&
690 // Don't change FP compares. The definition of compares involving
691 // NaNs forces the compares to be done as written by the user.
692 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
693 // Replace condition with its opposite.
694 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
695 }
696
697 if (replace_with != nullptr) {
698 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100699 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000700 RecordSimplification();
701 }
702}
703
704void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
705 HInstruction* replace_with = nullptr;
706 HInstruction* condition = select->GetCondition();
707 HInstruction* true_value = select->GetTrueValue();
708 HInstruction* false_value = select->GetFalseValue();
709
710 if (condition->IsBooleanNot()) {
711 // Change ((!cond) ? x : y) to (cond ? y : x).
712 condition = condition->InputAt(0);
713 std::swap(true_value, false_value);
714 select->ReplaceInput(false_value, 0);
715 select->ReplaceInput(true_value, 1);
716 select->ReplaceInput(condition, 2);
717 RecordSimplification();
718 }
719
720 if (true_value == false_value) {
721 // Replace (cond ? x : x) with (x).
722 replace_with = true_value;
723 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000724 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000725 // Replace (true ? x : y) with (x).
726 replace_with = true_value;
727 } else {
728 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000729 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000730 replace_with = false_value;
731 }
732 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000733 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000734 // Replace (cond ? true : false) with (cond).
735 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000736 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000737 // Replace (cond ? false : true) with (!cond).
738 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
739 }
740 }
741
742 if (replace_with != nullptr) {
743 select->ReplaceWith(replace_with);
744 select->GetBlock()->RemoveInstruction(select);
745 RecordSimplification();
746 }
747}
748
749void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
750 HInstruction* condition = instruction->InputAt(0);
751 if (condition->IsBooleanNot()) {
752 // Swap successors if input is negated.
753 instruction->ReplaceInput(condition->InputAt(0), 0);
754 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100755 RecordSimplification();
756 }
757}
758
Mingyao Yang0304e182015-01-30 16:41:29 -0800759void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
760 HInstruction* input = instruction->InputAt(0);
761 // If the array is a NewArray with constant size, replace the array length
762 // with the constant instruction. This helps the bounds check elimination phase.
763 if (input->IsNewArray()) {
764 input = input->InputAt(0);
765 if (input->IsIntConstant()) {
766 instruction->ReplaceWith(input);
767 }
768 }
769}
770
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000771void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000772 HInstruction* value = instruction->GetValue();
773 if (value->GetType() != Primitive::kPrimNot) return;
774
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100775 if (CanEnsureNotNullAt(value, instruction)) {
776 instruction->ClearValueCanBeNull();
777 }
778
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000779 if (value->IsArrayGet()) {
780 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
781 // If the code is just swapping elements in the array, no need for a type check.
782 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100783 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000784 }
785 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100786
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100787 if (value->IsNullConstant()) {
788 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100789 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100790 }
791
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100792 ScopedObjectAccess soa(Thread::Current());
793 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
794 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
795 if (!array_rti.IsValid()) {
796 return;
797 }
798
799 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
800 instruction->ClearNeedsTypeCheck();
801 return;
802 }
803
804 if (array_rti.IsObjectArray()) {
805 if (array_rti.IsExact()) {
806 instruction->ClearNeedsTypeCheck();
807 return;
808 }
809 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100810 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000811}
812
Vladimir Markob52bbde2016-02-12 12:06:05 +0000813static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100814 // Invariant: We should never generate a conversion to a Boolean value.
815 DCHECK_NE(Primitive::kPrimBoolean, result_type);
816
Vladimir Markob52bbde2016-02-12 12:06:05 +0000817 // Besides conversion to the same type, widening integral conversions are implicit,
818 // excluding conversions to long and the byte->char conversion where we need to
819 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
820 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100821 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
822 input_type == Primitive::kPrimByte ||
823 input_type == Primitive::kPrimShort ||
824 input_type == Primitive::kPrimChar)) ||
825 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
826 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
827 input_type == Primitive::kPrimByte)) ||
828 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000829}
830
831static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
832 // The conversion to a larger type is loss-less with the exception of two cases,
833 // - conversion to char, the only unsigned type, where we may lose some bits, and
834 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
835 // For integral to FP conversions this holds because the FP mantissa is large enough.
836 DCHECK_NE(input_type, result_type);
837 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
838 result_type != Primitive::kPrimChar &&
839 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
840}
841
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000842void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000843 HInstruction* input = instruction->GetInput();
844 Primitive::Type input_type = input->GetType();
845 Primitive::Type result_type = instruction->GetResultType();
846 if (IsTypeConversionImplicit(input_type, result_type)) {
847 // Remove the implicit conversion; this includes conversion to the same type.
848 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000849 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000850 RecordSimplification();
851 return;
852 }
853
854 if (input->IsTypeConversion()) {
855 HTypeConversion* input_conversion = input->AsTypeConversion();
856 HInstruction* original_input = input_conversion->GetInput();
857 Primitive::Type original_type = original_input->GetType();
858
859 // When the first conversion is lossless, a direct conversion from the original type
860 // to the final type yields the same result, even for a lossy second conversion, for
861 // example float->double->int or int->double->float.
862 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
863
864 // For integral conversions, see if the first conversion loses only bits that the second
865 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
866 // conversion yields the same result, for example long->int->short or int->char->short.
867 bool integral_conversions_with_non_widening_second =
868 Primitive::IsIntegralType(input_type) &&
869 Primitive::IsIntegralType(original_type) &&
870 Primitive::IsIntegralType(result_type) &&
871 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
872
873 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
874 // If the merged conversion is implicit, do the simplification unconditionally.
875 if (IsTypeConversionImplicit(original_type, result_type)) {
876 instruction->ReplaceWith(original_input);
877 instruction->GetBlock()->RemoveInstruction(instruction);
878 if (!input_conversion->HasUses()) {
879 // Don't wait for DCE.
880 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
881 }
882 RecordSimplification();
883 return;
884 }
885 // Otherwise simplify only if the first conversion has no other use.
886 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
887 input_conversion->ReplaceWith(original_input);
888 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
889 RecordSimplification();
890 return;
891 }
892 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000893 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000894 DCHECK(Primitive::IsIntegralType(input_type));
895 HAnd* input_and = input->AsAnd();
896 HConstant* constant = input_and->GetConstantRight();
897 if (constant != nullptr) {
898 int64_t value = Int64FromConstant(constant);
899 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
900 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
901 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
902 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000903 HInstruction* original_input = input_and->GetLeastConstantLeft();
904 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
905 instruction->ReplaceWith(original_input);
906 instruction->GetBlock()->RemoveInstruction(instruction);
907 RecordSimplification();
908 return;
909 } else if (input->HasOnlyOneNonEnvironmentUse()) {
910 input_and->ReplaceWith(original_input);
911 input_and->GetBlock()->RemoveInstruction(input_and);
912 RecordSimplification();
913 return;
914 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000915 }
916 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000917 }
918}
919
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000920void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
921 HConstant* input_cst = instruction->GetConstantRight();
922 HInstruction* input_other = instruction->GetLeastConstantLeft();
Roland Levillain1a653882016-03-18 18:05:57 +0000923 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000924 // Replace code looking like
925 // ADD dst, src, 0
926 // with
927 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600928 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
929 // `x` is `-0.0`, the former expression yields `0.0`, while the later
930 // yields `-0.0`.
931 if (Primitive::IsIntegralType(instruction->GetType())) {
932 instruction->ReplaceWith(input_other);
933 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100934 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600935 return;
936 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100937 }
938
939 HInstruction* left = instruction->GetLeft();
940 HInstruction* right = instruction->GetRight();
941 bool left_is_neg = left->IsNeg();
942 bool right_is_neg = right->IsNeg();
943
944 if (left_is_neg && right_is_neg) {
945 if (TryMoveNegOnInputsAfterBinop(instruction)) {
946 return;
947 }
948 }
949
950 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
951 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
952 // Replace code looking like
953 // NEG tmp, b
954 // ADD dst, a, tmp
955 // with
956 // SUB dst, a, b
957 // We do not perform the optimization if the input negation has environment
958 // uses or multiple non-environment uses as it could lead to worse code. In
959 // particular, we do not want the live range of `b` to be extended if we are
960 // not sure the initial 'NEG' instruction can be removed.
961 HInstruction* other = left_is_neg ? right : left;
962 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
963 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
964 RecordSimplification();
965 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000966 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000967 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000968
Anton Kirilove14dc862016-05-13 17:56:15 +0100969 if (TryReplaceWithRotate(instruction)) {
970 return;
971 }
972
973 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
974 // so no need to return.
975 TryHandleAssociativeAndCommutativeOperation(instruction);
976
977 if ((instruction->GetLeft()->IsSub() || instruction->GetRight()->IsSub()) &&
978 TrySubtractionChainSimplification(instruction)) {
979 return;
980 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000981}
982
983void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
984 HConstant* input_cst = instruction->GetConstantRight();
985 HInstruction* input_other = instruction->GetLeastConstantLeft();
986
Vladimir Marko452c1b62015-09-25 14:44:17 +0100987 if (input_cst != nullptr) {
988 int64_t value = Int64FromConstant(input_cst);
989 if (value == -1) {
990 // Replace code looking like
991 // AND dst, src, 0xFFF...FF
992 // with
993 // src
994 instruction->ReplaceWith(input_other);
995 instruction->GetBlock()->RemoveInstruction(instruction);
996 RecordSimplification();
997 return;
998 }
999 // Eliminate And from UShr+And if the And-mask contains all the bits that
1000 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1001 // precisely clears the shifted-in sign bits.
1002 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1003 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1004 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1005 size_t num_tail_bits_set = CTZ(value + 1);
1006 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1007 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1008 instruction->ReplaceWith(input_other);
1009 instruction->GetBlock()->RemoveInstruction(instruction);
1010 RecordSimplification();
1011 return;
1012 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1013 input_other->HasOnlyOneNonEnvironmentUse()) {
1014 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1015 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1016 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1017 input_other->InputAt(0),
1018 input_other->InputAt(1),
1019 input_other->GetDexPc());
1020 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1021 input_other->GetBlock()->RemoveInstruction(input_other);
1022 RecordSimplification();
1023 return;
1024 }
1025 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001026 }
1027
1028 // We assume that GVN has run before, so we only perform a pointer comparison.
1029 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001030 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001031 if (instruction->GetLeft() == instruction->GetRight()) {
1032 // Replace code looking like
1033 // AND dst, src, src
1034 // with
1035 // src
1036 instruction->ReplaceWith(instruction->GetLeft());
1037 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001038 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001039 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001040 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001041
Anton Kirilove14dc862016-05-13 17:56:15 +01001042 if (TryDeMorganNegationFactoring(instruction)) {
1043 return;
1044 }
1045
1046 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1047 // so no need to return.
1048 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001049}
1050
Mark Mendellc4701932015-04-10 13:18:51 -04001051void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1052 VisitCondition(condition);
1053}
1054
1055void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1056 VisitCondition(condition);
1057}
1058
1059void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1060 VisitCondition(condition);
1061}
1062
1063void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1064 VisitCondition(condition);
1065}
1066
Anton Shaminbdd79352016-02-15 12:48:36 +06001067void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1068 VisitCondition(condition);
1069}
1070
1071void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1072 VisitCondition(condition);
1073}
1074
1075void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1076 VisitCondition(condition);
1077}
1078
1079void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1080 VisitCondition(condition);
1081}
Aart Bike9f37602015-10-09 11:15:55 -07001082
Mark Mendellc4701932015-04-10 13:18:51 -04001083void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001084 // Reverse condition if left is constant. Our code generators prefer constant
1085 // on the right hand side.
1086 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1087 HBasicBlock* block = condition->GetBlock();
1088 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1089 // If it is a fp we must set the opposite bias.
1090 if (replacement != nullptr) {
1091 if (condition->IsLtBias()) {
1092 replacement->SetBias(ComparisonBias::kGtBias);
1093 } else if (condition->IsGtBias()) {
1094 replacement->SetBias(ComparisonBias::kLtBias);
1095 }
1096 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1097 RecordSimplification();
1098
1099 condition = replacement;
1100 }
1101 }
Mark Mendellc4701932015-04-10 13:18:51 -04001102
Mark Mendellc4701932015-04-10 13:18:51 -04001103 HInstruction* left = condition->GetLeft();
1104 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001105
1106 // Try to fold an HCompare into this HCondition.
1107
Mark Mendellc4701932015-04-10 13:18:51 -04001108 // We can only replace an HCondition which compares a Compare to 0.
1109 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1110 // condition with a long, float or double comparison as input.
1111 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1112 // Conversion is not possible.
1113 return;
1114 }
1115
1116 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001117 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001118 // Someone else also wants the result of the compare.
1119 return;
1120 }
1121
Vladimir Marko46817b82016-03-29 12:21:58 +01001122 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001123 // There is a reference to the compare result in an environment. Do we really need it?
1124 if (GetGraph()->IsDebuggable()) {
1125 return;
1126 }
1127
1128 // We have to ensure that there are no deopt points in the sequence.
1129 if (left->HasAnyEnvironmentUseBefore(condition)) {
1130 return;
1131 }
1132 }
1133
1134 // Clean up any environment uses from the HCompare, if any.
1135 left->RemoveEnvironmentUsers();
1136
1137 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1138 condition->SetBias(left->AsCompare()->GetBias());
1139
1140 // Replace the operands of the HCondition.
1141 condition->ReplaceInput(left->InputAt(0), 0);
1142 condition->ReplaceInput(left->InputAt(1), 1);
1143
1144 // Remove the HCompare.
1145 left->GetBlock()->RemoveInstruction(left);
1146
1147 RecordSimplification();
1148}
1149
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001150void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1151 HConstant* input_cst = instruction->GetConstantRight();
1152 HInstruction* input_other = instruction->GetLeastConstantLeft();
1153 Primitive::Type type = instruction->GetType();
1154
1155 if ((input_cst != nullptr) && input_cst->IsOne()) {
1156 // Replace code looking like
1157 // DIV dst, src, 1
1158 // with
1159 // src
1160 instruction->ReplaceWith(input_other);
1161 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001162 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001163 return;
1164 }
1165
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001166 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001167 // Replace code looking like
1168 // DIV dst, src, -1
1169 // with
1170 // NEG dst, src
1171 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001172 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001173 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001174 return;
1175 }
1176
1177 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1178 // Try replacing code looking like
1179 // DIV dst, src, constant
1180 // with
1181 // MUL dst, src, 1 / constant
1182 HConstant* reciprocal = nullptr;
1183 if (type == Primitive::Primitive::kPrimDouble) {
1184 double value = input_cst->AsDoubleConstant()->GetValue();
1185 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1186 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1187 }
1188 } else {
1189 DCHECK_EQ(type, Primitive::kPrimFloat);
1190 float value = input_cst->AsFloatConstant()->GetValue();
1191 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1192 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1193 }
1194 }
1195
1196 if (reciprocal != nullptr) {
1197 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1198 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1199 RecordSimplification();
1200 return;
1201 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001202 }
1203}
1204
1205void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1206 HConstant* input_cst = instruction->GetConstantRight();
1207 HInstruction* input_other = instruction->GetLeastConstantLeft();
1208 Primitive::Type type = instruction->GetType();
1209 HBasicBlock* block = instruction->GetBlock();
1210 ArenaAllocator* allocator = GetGraph()->GetArena();
1211
1212 if (input_cst == nullptr) {
1213 return;
1214 }
1215
1216 if (input_cst->IsOne()) {
1217 // Replace code looking like
1218 // MUL dst, src, 1
1219 // with
1220 // src
1221 instruction->ReplaceWith(input_other);
1222 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001223 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001224 return;
1225 }
1226
1227 if (input_cst->IsMinusOne() &&
1228 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1229 // Replace code looking like
1230 // MUL dst, src, -1
1231 // with
1232 // NEG dst, src
1233 HNeg* neg = new (allocator) HNeg(type, input_other);
1234 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001235 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001236 return;
1237 }
1238
1239 if (Primitive::IsFloatingPointType(type) &&
1240 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1241 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1242 // Replace code looking like
1243 // FP_MUL dst, src, 2.0
1244 // with
1245 // FP_ADD dst, src, src
1246 // The 'int' and 'long' cases are handled below.
1247 block->ReplaceAndRemoveInstructionWith(instruction,
1248 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001249 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001250 return;
1251 }
1252
1253 if (Primitive::IsIntOrLongType(type)) {
1254 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001255 // Even though constant propagation also takes care of the zero case, other
1256 // optimizations can lead to having a zero multiplication.
1257 if (factor == 0) {
1258 // Replace code looking like
1259 // MUL dst, src, 0
1260 // with
1261 // 0
1262 instruction->ReplaceWith(input_cst);
1263 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001264 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001265 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001266 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001267 // Replace code looking like
1268 // MUL dst, src, pow_of_2
1269 // with
1270 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001271 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001272 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001273 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001274 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001275 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001276 } else if (IsPowerOfTwo(factor - 1)) {
1277 // Transform code looking like
1278 // MUL dst, src, (2^n + 1)
1279 // into
1280 // SHL tmp, src, n
1281 // ADD dst, src, tmp
1282 HShl* shl = new (allocator) HShl(type,
1283 input_other,
1284 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1285 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1286
1287 block->InsertInstructionBefore(shl, instruction);
1288 block->ReplaceAndRemoveInstructionWith(instruction, add);
1289 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001290 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001291 } else if (IsPowerOfTwo(factor + 1)) {
1292 // Transform code looking like
1293 // MUL dst, src, (2^n - 1)
1294 // into
1295 // SHL tmp, src, n
1296 // SUB dst, tmp, src
1297 HShl* shl = new (allocator) HShl(type,
1298 input_other,
1299 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1300 HSub* sub = new (allocator) HSub(type, shl, input_other);
1301
1302 block->InsertInstructionBefore(shl, instruction);
1303 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1304 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001305 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001306 }
1307 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001308
1309 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1310 // so no need to return.
1311 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001312}
1313
Alexandre Rames188d4312015-04-09 18:30:21 +01001314void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1315 HInstruction* input = instruction->GetInput();
1316 if (input->IsNeg()) {
1317 // Replace code looking like
1318 // NEG tmp, src
1319 // NEG dst, tmp
1320 // with
1321 // src
1322 HNeg* previous_neg = input->AsNeg();
1323 instruction->ReplaceWith(previous_neg->GetInput());
1324 instruction->GetBlock()->RemoveInstruction(instruction);
1325 // We perform the optimization even if the input negation has environment
1326 // uses since it allows removing the current instruction. But we only delete
1327 // the input negation only if it is does not have any uses left.
1328 if (!previous_neg->HasUses()) {
1329 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1330 }
1331 RecordSimplification();
1332 return;
1333 }
1334
Serguei Katkov339dfc22015-04-20 12:29:32 +06001335 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1336 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001337 // Replace code looking like
1338 // SUB tmp, a, b
1339 // NEG dst, tmp
1340 // with
1341 // SUB dst, b, a
1342 // We do not perform the optimization if the input subtraction has
1343 // environment uses or multiple non-environment uses as it could lead to
1344 // worse code. In particular, we do not want the live ranges of `a` and `b`
1345 // to be extended if we are not sure the initial 'SUB' instruction can be
1346 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001347 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001348 HSub* sub = input->AsSub();
1349 HSub* new_sub =
1350 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1351 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1352 if (!sub->HasUses()) {
1353 sub->GetBlock()->RemoveInstruction(sub);
1354 }
1355 RecordSimplification();
1356 }
1357}
1358
1359void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1360 HInstruction* input = instruction->GetInput();
1361 if (input->IsNot()) {
1362 // Replace code looking like
1363 // NOT tmp, src
1364 // NOT dst, tmp
1365 // with
1366 // src
1367 // We perform the optimization even if the input negation has environment
1368 // uses since it allows removing the current instruction. But we only delete
1369 // the input negation only if it is does not have any uses left.
1370 HNot* previous_not = input->AsNot();
1371 instruction->ReplaceWith(previous_not->GetInput());
1372 instruction->GetBlock()->RemoveInstruction(instruction);
1373 if (!previous_not->HasUses()) {
1374 previous_not->GetBlock()->RemoveInstruction(previous_not);
1375 }
1376 RecordSimplification();
1377 }
1378}
1379
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001380void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1381 HConstant* input_cst = instruction->GetConstantRight();
1382 HInstruction* input_other = instruction->GetLeastConstantLeft();
1383
Roland Levillain1a653882016-03-18 18:05:57 +00001384 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001385 // Replace code looking like
1386 // OR dst, src, 0
1387 // with
1388 // src
1389 instruction->ReplaceWith(input_other);
1390 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001391 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001392 return;
1393 }
1394
1395 // We assume that GVN has run before, so we only perform a pointer comparison.
1396 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001397 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001398 if (instruction->GetLeft() == instruction->GetRight()) {
1399 // Replace code looking like
1400 // OR dst, src, src
1401 // with
1402 // src
1403 instruction->ReplaceWith(instruction->GetLeft());
1404 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001405 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001406 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001407 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001408
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001409 if (TryDeMorganNegationFactoring(instruction)) return;
1410
Anton Kirilove14dc862016-05-13 17:56:15 +01001411 if (TryReplaceWithRotate(instruction)) {
1412 return;
1413 }
1414
1415 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1416 // so no need to return.
1417 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001418}
1419
1420void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1421 VisitShift(instruction);
1422}
1423
1424void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1425 VisitShift(instruction);
1426}
1427
1428void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1429 HConstant* input_cst = instruction->GetConstantRight();
1430 HInstruction* input_other = instruction->GetLeastConstantLeft();
1431
Serguei Katkov115b53f2015-08-05 17:03:30 +06001432 Primitive::Type type = instruction->GetType();
1433 if (Primitive::IsFloatingPointType(type)) {
1434 return;
1435 }
1436
Roland Levillain1a653882016-03-18 18:05:57 +00001437 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001438 // Replace code looking like
1439 // SUB dst, src, 0
1440 // with
1441 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001442 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1443 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1444 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001445 instruction->ReplaceWith(input_other);
1446 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001447 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001448 return;
1449 }
1450
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001451 HBasicBlock* block = instruction->GetBlock();
1452 ArenaAllocator* allocator = GetGraph()->GetArena();
1453
Alexandre Rames188d4312015-04-09 18:30:21 +01001454 HInstruction* left = instruction->GetLeft();
1455 HInstruction* right = instruction->GetRight();
1456 if (left->IsConstant()) {
1457 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001458 // Replace code looking like
1459 // SUB dst, 0, src
1460 // with
1461 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001462 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001463 // `x` is `0.0`, the former expression yields `0.0`, while the later
1464 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001465 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001466 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001467 RecordSimplification();
1468 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001469 }
1470 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001471
1472 if (left->IsNeg() && right->IsNeg()) {
1473 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1474 return;
1475 }
1476 }
1477
1478 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1479 // Replace code looking like
1480 // NEG tmp, b
1481 // SUB dst, a, tmp
1482 // with
1483 // ADD dst, a, b
1484 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1485 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1486 RecordSimplification();
1487 right->GetBlock()->RemoveInstruction(right);
1488 return;
1489 }
1490
1491 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1492 // Replace code looking like
1493 // NEG tmp, a
1494 // SUB dst, tmp, b
1495 // with
1496 // ADD tmp, a, b
1497 // NEG dst, tmp
1498 // The second version is not intrinsically better, but enables more
1499 // transformations.
1500 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1501 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1502 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1503 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1504 instruction->ReplaceWith(neg);
1505 instruction->GetBlock()->RemoveInstruction(instruction);
1506 RecordSimplification();
1507 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001508 return;
1509 }
1510
1511 if (TrySubtractionChainSimplification(instruction)) {
1512 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001513 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001514}
1515
1516void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1517 VisitShift(instruction);
1518}
1519
1520void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1521 HConstant* input_cst = instruction->GetConstantRight();
1522 HInstruction* input_other = instruction->GetLeastConstantLeft();
1523
Roland Levillain1a653882016-03-18 18:05:57 +00001524 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001525 // Replace code looking like
1526 // XOR dst, src, 0
1527 // with
1528 // src
1529 instruction->ReplaceWith(input_other);
1530 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001531 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001532 return;
1533 }
1534
1535 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1536 // Replace code looking like
1537 // XOR dst, src, 0xFFF...FF
1538 // with
1539 // NOT dst, src
1540 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1541 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001542 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001543 return;
1544 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001545
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001546 HInstruction* left = instruction->GetLeft();
1547 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001548 if (((left->IsNot() && right->IsNot()) ||
1549 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001550 left->HasOnlyOneNonEnvironmentUse() &&
1551 right->HasOnlyOneNonEnvironmentUse()) {
1552 // Replace code looking like
1553 // NOT nota, a
1554 // NOT notb, b
1555 // XOR dst, nota, notb
1556 // with
1557 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001558 instruction->ReplaceInput(left->InputAt(0), 0);
1559 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001560 left->GetBlock()->RemoveInstruction(left);
1561 right->GetBlock()->RemoveInstruction(right);
1562 RecordSimplification();
1563 return;
1564 }
1565
Anton Kirilove14dc862016-05-13 17:56:15 +01001566 if (TryReplaceWithRotate(instruction)) {
1567 return;
1568 }
1569
1570 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1571 // so no need to return.
1572 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001573}
1574
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001575void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1576 HInstruction* argument = instruction->InputAt(1);
1577 HInstruction* receiver = instruction->InputAt(0);
1578 if (receiver == argument) {
1579 // Because String.equals is an instance call, the receiver is
1580 // a null check if we don't know it's null. The argument however, will
1581 // be the actual object. So we cannot end up in a situation where both
1582 // are equal but could be null.
1583 DCHECK(CanEnsureNotNullAt(argument, instruction));
1584 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1585 instruction->GetBlock()->RemoveInstruction(instruction);
1586 } else {
1587 StringEqualsOptimizations optimizations(instruction);
1588 if (CanEnsureNotNullAt(argument, instruction)) {
1589 optimizations.SetArgumentNotNull();
1590 }
1591 ScopedObjectAccess soa(Thread::Current());
1592 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1593 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1594 optimizations.SetArgumentIsString();
1595 }
1596 }
1597}
1598
Roland Levillain22c49222016-03-18 14:04:28 +00001599void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1600 bool is_left,
1601 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001602 DCHECK(invoke->IsInvokeStaticOrDirect());
1603 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001604 HInstruction* value = invoke->InputAt(0);
1605 HInstruction* distance = invoke->InputAt(1);
1606 // Replace the invoke with an HRor.
1607 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001608 // Unconditionally set the type of the negated distance to `int`,
1609 // as shift and rotate operations expect a 32-bit (or narrower)
1610 // value for their distance input.
1611 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001612 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1613 }
Roland Levillain22c49222016-03-18 14:04:28 +00001614 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001615 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1616 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001617 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001618 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1619 clinit->GetBlock()->RemoveInstruction(clinit);
1620 HInstruction* ldclass = clinit->InputAt(0);
1621 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1622 ldclass->GetBlock()->RemoveInstruction(ldclass);
1623 }
1624 }
1625}
1626
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001627static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1628 if (potential_length->IsArrayLength()) {
1629 return potential_length->InputAt(0) == potential_array;
1630 }
1631
1632 if (potential_array->IsNewArray()) {
1633 return potential_array->InputAt(0) == potential_length;
1634 }
1635
1636 return false;
1637}
1638
1639void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1640 HInstruction* source = instruction->InputAt(0);
1641 HInstruction* destination = instruction->InputAt(2);
1642 HInstruction* count = instruction->InputAt(4);
1643 SystemArrayCopyOptimizations optimizations(instruction);
1644 if (CanEnsureNotNullAt(source, instruction)) {
1645 optimizations.SetSourceIsNotNull();
1646 }
1647 if (CanEnsureNotNullAt(destination, instruction)) {
1648 optimizations.SetDestinationIsNotNull();
1649 }
1650 if (destination == source) {
1651 optimizations.SetDestinationIsSource();
1652 }
1653
1654 if (IsArrayLengthOf(count, source)) {
1655 optimizations.SetCountIsSourceLength();
1656 }
1657
1658 if (IsArrayLengthOf(count, destination)) {
1659 optimizations.SetCountIsDestinationLength();
1660 }
1661
1662 {
1663 ScopedObjectAccess soa(Thread::Current());
1664 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1665 if (destination_rti.IsValid()) {
1666 if (destination_rti.IsObjectArray()) {
1667 if (destination_rti.IsExact()) {
1668 optimizations.SetDoesNotNeedTypeCheck();
1669 }
1670 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001671 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001672 if (destination_rti.IsPrimitiveArrayClass()) {
1673 optimizations.SetDestinationIsPrimitiveArray();
1674 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1675 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001676 }
1677 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001678 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1679 if (source_rti.IsValid()) {
1680 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1681 optimizations.SetDoesNotNeedTypeCheck();
1682 }
1683 if (source_rti.IsPrimitiveArrayClass()) {
1684 optimizations.SetSourceIsPrimitiveArray();
1685 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1686 optimizations.SetSourceIsNonPrimitiveArray();
1687 }
1688 }
1689 }
1690}
1691
Roland Levillaina5c4a402016-03-15 15:02:50 +00001692void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1693 bool is_signum,
1694 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001695 DCHECK(invoke->IsInvokeStaticOrDirect());
1696 uint32_t dex_pc = invoke->GetDexPc();
1697 HInstruction* left = invoke->InputAt(0);
1698 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001699 if (!is_signum) {
1700 right = invoke->InputAt(1);
1701 } else if (type == Primitive::kPrimLong) {
1702 right = GetGraph()->GetLongConstant(0);
1703 } else {
1704 right = GetGraph()->GetIntConstant(0);
1705 }
1706 HCompare* compare = new (GetGraph()->GetArena())
1707 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1708 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1709}
1710
Aart Bik75a38b22016-02-17 10:41:50 -08001711void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1712 DCHECK(invoke->IsInvokeStaticOrDirect());
1713 uint32_t dex_pc = invoke->GetDexPc();
1714 // IsNaN(x) is the same as x != x.
1715 HInstruction* x = invoke->InputAt(0);
1716 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001717 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001718 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1719}
1720
Aart Bik2a6aad92016-02-25 11:32:32 -08001721void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1722 DCHECK(invoke->IsInvokeStaticOrDirect());
1723 uint32_t dex_pc = invoke->GetDexPc();
1724 HInstruction* x = invoke->InputAt(0);
1725 Primitive::Type type = x->GetType();
1726 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1727 HInstruction* nan;
1728 if (type == Primitive::kPrimDouble) {
1729 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1730 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1731 kNeedsEnvironmentOrCache,
1732 kNoSideEffects,
1733 kNoThrow);
1734 } else {
1735 DCHECK_EQ(type, Primitive::kPrimFloat);
1736 nan = GetGraph()->GetIntConstant(0x7fc00000);
1737 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1738 kNeedsEnvironmentOrCache,
1739 kNoSideEffects,
1740 kNoThrow);
1741 }
1742 // Test IsNaN(x), which is the same as x != x.
1743 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1744 condition->SetBias(ComparisonBias::kLtBias);
1745 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1746 // Select between the two.
1747 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1748 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1749 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1750}
1751
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001752void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1753 HInstruction* str = invoke->InputAt(0);
1754 HInstruction* index = invoke->InputAt(1);
1755 uint32_t dex_pc = invoke->GetDexPc();
1756 ArenaAllocator* arena = GetGraph()->GetArena();
1757 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1758 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1759 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1760 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1761 HBoundsCheck* bounds_check =
1762 new (arena) HBoundsCheck(index, length, dex_pc, invoke->GetDexMethodIndex());
1763 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
1764 HArrayGet* array_get =
1765 new (arena) HArrayGet(str, index, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
1766 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1767 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1768 GetGraph()->SetHasBoundsChecks(true);
1769}
1770
Vladimir Markodce016e2016-04-28 13:10:02 +01001771void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1772 HInstruction* str = invoke->InputAt(0);
1773 uint32_t dex_pc = invoke->GetDexPc();
1774 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1775 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001776 HArrayLength* length =
1777 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001778 HInstruction* replacement;
1779 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1780 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1781 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1782 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1783 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1784 replacement = equal;
1785 } else {
1786 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1787 replacement = length;
1788 }
1789 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1790}
1791
Aart Bik11932592016-03-08 12:42:25 -08001792void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1793 uint32_t dex_pc = invoke->GetDexPc();
1794 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1795 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1796}
1797
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001798void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001799 switch (instruction->GetIntrinsic()) {
1800 case Intrinsics::kStringEquals:
1801 SimplifyStringEquals(instruction);
1802 break;
1803 case Intrinsics::kSystemArrayCopy:
1804 SimplifySystemArrayCopy(instruction);
1805 break;
1806 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001807 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1808 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001809 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001810 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001811 break;
1812 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001813 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1814 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001815 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001816 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001817 break;
1818 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001819 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1820 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001821 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001822 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001823 break;
1824 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001825 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1826 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001827 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001828 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001829 break;
1830 case Intrinsics::kFloatIsNaN:
1831 case Intrinsics::kDoubleIsNaN:
1832 SimplifyIsNaN(instruction);
1833 break;
1834 case Intrinsics::kFloatFloatToIntBits:
1835 case Intrinsics::kDoubleDoubleToLongBits:
1836 SimplifyFP2Int(instruction);
1837 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001838 case Intrinsics::kStringCharAt:
1839 SimplifyStringCharAt(instruction);
1840 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01001841 case Intrinsics::kStringIsEmpty:
1842 case Intrinsics::kStringLength:
1843 SimplifyStringIsEmptyOrLength(instruction);
1844 break;
Aart Bik11932592016-03-08 12:42:25 -08001845 case Intrinsics::kUnsafeLoadFence:
1846 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1847 break;
1848 case Intrinsics::kUnsafeStoreFence:
1849 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1850 break;
1851 case Intrinsics::kUnsafeFullFence:
1852 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1853 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001854 default:
1855 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001856 }
1857}
1858
Aart Bikbb245d12015-10-19 11:05:03 -07001859void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1860 HInstruction* cond = deoptimize->InputAt(0);
1861 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001862 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07001863 // Never deopt: instruction can be removed.
1864 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1865 } else {
1866 // Always deopt.
1867 }
1868 }
1869}
1870
Anton Kirilove14dc862016-05-13 17:56:15 +01001871// Replace code looking like
1872// OP y, x, const1
1873// OP z, y, const2
1874// with
1875// OP z, x, const3
1876// where OP is both an associative and a commutative operation.
1877bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
1878 HBinaryOperation* instruction) {
1879 DCHECK(instruction->IsCommutative());
1880
1881 if (!Primitive::IsIntegralType(instruction->GetType())) {
1882 return false;
1883 }
1884
1885 HInstruction* left = instruction->GetLeft();
1886 HInstruction* right = instruction->GetRight();
1887 // Variable names as described above.
1888 HConstant* const2;
1889 HBinaryOperation* y;
1890
1891 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
1892 const2 = right->AsConstant();
1893 y = left->AsBinaryOperation();
1894 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
1895 const2 = left->AsConstant();
1896 y = right->AsBinaryOperation();
1897 } else {
1898 // The node does not match the pattern.
1899 return false;
1900 }
1901
1902 // If `y` has more than one use, we do not perform the optimization
1903 // because it might increase code size (e.g. if the new constant is
1904 // no longer encodable as an immediate operand in the target ISA).
1905 if (!y->HasOnlyOneNonEnvironmentUse()) {
1906 return false;
1907 }
1908
1909 // GetConstantRight() can return both left and right constants
1910 // for commutative operations.
1911 HConstant* const1 = y->GetConstantRight();
1912 if (const1 == nullptr) {
1913 return false;
1914 }
1915
1916 instruction->ReplaceInput(const1, 0);
1917 instruction->ReplaceInput(const2, 1);
1918 HConstant* const3 = instruction->TryStaticEvaluation();
1919 DCHECK(const3 != nullptr);
1920 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
1921 instruction->ReplaceInput(const3, 1);
1922 RecordSimplification();
1923 return true;
1924}
1925
1926static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
1927 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
1928}
1929
1930// Helper function that performs addition statically, considering the result type.
1931static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
1932 // Use the Compute() method for consistency with TryStaticEvaluation().
1933 if (type == Primitive::kPrimInt) {
1934 return HAdd::Compute<int32_t>(x, y);
1935 } else {
1936 DCHECK_EQ(type, Primitive::kPrimLong);
1937 return HAdd::Compute<int64_t>(x, y);
1938 }
1939}
1940
1941// Helper function that handles the child classes of HConstant
1942// and returns an integer with the appropriate sign.
1943static int64_t GetValue(HConstant* constant, bool is_negated) {
1944 int64_t ret = Int64FromConstant(constant);
1945 return is_negated ? -ret : ret;
1946}
1947
1948// Replace code looking like
1949// OP1 y, x, const1
1950// OP2 z, y, const2
1951// with
1952// OP3 z, x, const3
1953// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
1954bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
1955 HBinaryOperation* instruction) {
1956 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
1957
1958 Primitive::Type type = instruction->GetType();
1959 if (!Primitive::IsIntegralType(type)) {
1960 return false;
1961 }
1962
1963 HInstruction* left = instruction->GetLeft();
1964 HInstruction* right = instruction->GetRight();
1965 // Variable names as described above.
1966 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
1967 if (const2 == nullptr) {
1968 return false;
1969 }
1970
1971 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
1972 ? left->AsBinaryOperation()
1973 : AsAddOrSub(right);
1974 // If y has more than one use, we do not perform the optimization because
1975 // it might increase code size (e.g. if the new constant is no longer
1976 // encodable as an immediate operand in the target ISA).
1977 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
1978 return false;
1979 }
1980
1981 left = y->GetLeft();
1982 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
1983 if (const1 == nullptr) {
1984 return false;
1985 }
1986
1987 HInstruction* x = (const1 == left) ? y->GetRight() : left;
1988 // If both inputs are constants, let the constant folding pass deal with it.
1989 if (x->IsConstant()) {
1990 return false;
1991 }
1992
1993 bool is_const2_negated = (const2 == right) && instruction->IsSub();
1994 int64_t const2_val = GetValue(const2, is_const2_negated);
1995 bool is_y_negated = (y == right) && instruction->IsSub();
1996 right = y->GetRight();
1997 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
1998 int64_t const1_val = GetValue(const1, is_const1_negated);
1999 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2000 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2001 HBasicBlock* block = instruction->GetBlock();
2002 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2003 ArenaAllocator* arena = instruction->GetArena();
2004 HInstruction* z;
2005
2006 if (is_x_negated) {
2007 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2008 } else {
2009 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2010 }
2011
2012 block->ReplaceAndRemoveInstructionWith(instruction, z);
2013 RecordSimplification();
2014 return true;
2015}
2016
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002017} // namespace art