blob: 5c79511bab2dfba38f686fbca2523b4cf7d8fc50 [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
Andreas Gampec6ea7d02017-02-01 16:46:28 -080019#include "art_method-inl.h"
20#include "class_linker-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080021#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010022#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000023#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070024#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000026
Nicolas Geoffray3c049742014-09-24 18:10:46 +010027namespace art {
28
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010029class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000030 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000031 InstructionSimplifierVisitor(HGraph* graph,
32 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010033 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000034 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010035 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000036 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010037 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010038 stats_(stats) {}
39
40 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000041
42 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010043 void RecordSimplification() {
44 simplification_occurred_ = true;
45 simplifications_at_current_position_++;
Igor Murashkin1e065a52017-08-09 13:20:34 -070046 MaybeRecordStat(stats_, kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010047 }
48
Scott Wakeling40a04bf2015-12-11 09:50:36 +000049 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotate(HBinaryOperation* instruction);
51 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
52 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
53 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54
Alexandre Rames188d4312015-04-09 18:30:21 +010055 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000056 // `op` should be either HOr or HAnd.
57 // De Morgan's laws:
58 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
59 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010060 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
61 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
62
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000063 void VisitShift(HBinaryOperation* shift);
64
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000065 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010066 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
67 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010068 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
69 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000070 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000071 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000072 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080073 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000074 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000075 void VisitAdd(HAdd* instruction) OVERRIDE;
76 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040077 void VisitCondition(HCondition* instruction) OVERRIDE;
78 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
79 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
80 void VisitLessThan(HLessThan* condition) OVERRIDE;
81 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060082 void VisitBelow(HBelow* condition) OVERRIDE;
83 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
84 void VisitAbove(HAbove* condition) OVERRIDE;
85 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000086 void VisitDiv(HDiv* instruction) OVERRIDE;
87 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010088 void VisitNeg(HNeg* instruction) OVERRIDE;
89 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000090 void VisitOr(HOr* instruction) OVERRIDE;
91 void VisitShl(HShl* instruction) OVERRIDE;
92 void VisitShr(HShr* instruction) OVERRIDE;
93 void VisitSub(HSub* instruction) OVERRIDE;
94 void VisitUShr(HUShr* instruction) OVERRIDE;
95 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000096 void VisitSelect(HSelect* select) OVERRIDE;
97 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010098 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010099 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700100 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100101
102 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000103
Roland Levillain22c49222016-03-18 14:04:28 +0000104 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100105 void SimplifySystemArrayCopy(HInvoke* invoke);
106 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000107 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800108 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800109 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100110 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100111 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800112 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800113 void SimplifyReturnThis(HInvoke* invoke);
114 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800115 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100116
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000117 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100118 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000119 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100120 bool simplification_occurred_ = false;
121 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700122 // We ensure we do not loop infinitely. The value should not be too high, since that
123 // would allow looping around the same basic block too many times. The value should
124 // not be too low either, however, since we want to allow revisiting a basic block
125 // with many statements and simplifications at least once.
126 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000127};
128
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100129void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100130 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100131 visitor.Run();
132}
133
134void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100135 // Iterate in reverse post order to open up more simplifications to users
136 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100137 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100138 // The simplification of an instruction to another instruction may yield
139 // possibilities for other simplifications. So although we perform a reverse
140 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100141 do {
142 simplification_occurred_ = false;
143 VisitBasicBlock(block);
144 } while (simplification_occurred_ &&
145 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100146 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100147 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100148}
149
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000150namespace {
151
152bool AreAllBitsSet(HConstant* constant) {
153 return Int64FromConstant(constant) == -1;
154}
155
156} // namespace
157
Alexandre Rames188d4312015-04-09 18:30:21 +0100158// Returns true if the code was simplified to use only one negation operation
159// after the binary operation instead of one on each of the inputs.
160bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
161 DCHECK(binop->IsAdd() || binop->IsSub());
162 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
163 HNeg* left_neg = binop->GetLeft()->AsNeg();
164 HNeg* right_neg = binop->GetRight()->AsNeg();
165 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
166 !right_neg->HasOnlyOneNonEnvironmentUse()) {
167 return false;
168 }
169 // Replace code looking like
170 // NEG tmp1, a
171 // NEG tmp2, b
172 // ADD dst, tmp1, tmp2
173 // with
174 // ADD tmp, a, b
175 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600176 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
177 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
178 // while the later yields `-0.0`.
179 if (!Primitive::IsIntegralType(binop->GetType())) {
180 return false;
181 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100182 binop->ReplaceInput(left_neg->GetInput(), 0);
183 binop->ReplaceInput(right_neg->GetInput(), 1);
184 left_neg->GetBlock()->RemoveInstruction(left_neg);
185 right_neg->GetBlock()->RemoveInstruction(right_neg);
186 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
187 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
188 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
189 RecordSimplification();
190 return true;
191}
192
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
194 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
195 Primitive::Type type = op->GetType();
196 HInstruction* left = op->GetLeft();
197 HInstruction* right = op->GetRight();
198
199 // We can apply De Morgan's laws if both inputs are Not's and are only used
200 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000201 if (((left->IsNot() && right->IsNot()) ||
202 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000203 left->HasOnlyOneNonEnvironmentUse() &&
204 right->HasOnlyOneNonEnvironmentUse()) {
205 // Replace code looking like
206 // NOT nota, a
207 // NOT notb, b
208 // AND dst, nota, notb (respectively OR)
209 // with
210 // OR or, a, b (respectively AND)
211 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000212 HInstruction* src_left = left->InputAt(0);
213 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000214 uint32_t dex_pc = op->GetDexPc();
215
216 // Remove the negations on the inputs.
217 left->ReplaceWith(src_left);
218 right->ReplaceWith(src_right);
219 left->GetBlock()->RemoveInstruction(left);
220 right->GetBlock()->RemoveInstruction(right);
221
222 // Replace the `HAnd` or `HOr`.
223 HBinaryOperation* hbin;
224 if (op->IsAnd()) {
225 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
226 } else {
227 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
228 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000229 HInstruction* hnot;
230 if (left->IsBooleanNot()) {
231 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
232 } else {
233 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
234 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000235
236 op->GetBlock()->InsertInstructionBefore(hbin, op);
237 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
238
239 RecordSimplification();
240 return true;
241 }
242
243 return false;
244}
245
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000246void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
247 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100248 HInstruction* shift_amount = instruction->GetRight();
249 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000250
Alexandre Rames50518442016-06-27 11:39:19 +0100251 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
252 ? kMaxLongShiftDistance
253 : kMaxIntShiftDistance;
254
255 if (shift_amount->IsConstant()) {
256 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700257 int64_t masked_cst = cst & implicit_mask;
258 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400259 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100260 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400261 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100262 // value
263 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400264 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100265 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100266 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700267 } else if (masked_cst != cst) {
268 // Replace code looking like
269 // SHL dst, value, cst
270 // where cst exceeds maximum distance with the equivalent
271 // SHL dst, value, cst & implicit_mask
272 // (as defined by shift semantics). This ensures other
273 // optimizations do not need to special case for such situations.
274 DCHECK_EQ(shift_amount->GetType(), Primitive::kPrimInt);
275 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
276 RecordSimplification();
277 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100278 }
279 }
280
281 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
282 // unnecessary explicit masking operations on the shift amount.
283 // Replace code looking like
284 // AND masked_shift, shift, <superset of implicit mask>
285 // SHL dst, value, masked_shift
286 // with
287 // SHL dst, value, shift
288 if (shift_amount->IsAnd()) {
289 HAnd* and_insn = shift_amount->AsAnd();
290 HConstant* mask = and_insn->GetConstantRight();
291 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
292 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
293 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400294 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000295 }
296}
297
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000298static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
299 return (sub->GetRight() == other &&
300 sub->GetLeft()->IsConstant() &&
301 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
302}
303
304bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
305 HUShr* ushr,
306 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000307 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
308 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000309 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
310 if (!ushr->HasUses()) {
311 ushr->GetBlock()->RemoveInstruction(ushr);
312 }
313 if (!ushr->GetRight()->HasUses()) {
314 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
315 }
316 if (!shl->HasUses()) {
317 shl->GetBlock()->RemoveInstruction(shl);
318 }
319 if (!shl->GetRight()->HasUses()) {
320 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
321 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100322 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000323 return true;
324}
325
326// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
327bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000328 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
329 HInstruction* left = op->GetLeft();
330 HInstruction* right = op->GetRight();
331 // If we have an UShr and a Shl (in either order).
332 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
333 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
334 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
335 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
336 if (ushr->GetType() == shl->GetType() &&
337 ushr->GetLeft() == shl->GetLeft()) {
338 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
339 // Shift distances are both constant, try replacing with Ror if they
340 // add up to the register size.
341 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
342 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
343 // Shift distances are potentially of the form x and (reg_size - x).
344 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
345 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
346 // Shift distances are potentially of the form d and -d.
347 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
348 }
349 }
350 }
351 return false;
352}
353
354// Try replacing code looking like (x >>> #rdist OP x << #ldist):
355// UShr dst, x, #rdist
356// Shl tmp, x, #ldist
357// OP dst, dst, tmp
358// or like (x >>> #rdist OP x << #-ldist):
359// UShr dst, x, #rdist
360// Shl tmp, x, #-ldist
361// OP dst, dst, tmp
362// with
363// Ror dst, x, #rdist
364bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
365 HUShr* ushr,
366 HShl* shl) {
367 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
368 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
369 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
370 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
371 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
372 ReplaceRotateWithRor(op, ushr, shl);
373 return true;
374 }
375 return false;
376}
377
378// Replace code looking like (x >>> -d OP x << d):
379// Neg neg, d
380// UShr dst, x, neg
381// Shl tmp, x, d
382// OP dst, dst, tmp
383// with
384// Neg neg, d
385// Ror dst, x, neg
386// *** OR ***
387// Replace code looking like (x >>> d OP x << -d):
388// UShr dst, x, d
389// Neg neg, d
390// Shl tmp, x, neg
391// OP dst, dst, tmp
392// with
393// Ror dst, x, d
394bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
395 HUShr* ushr,
396 HShl* shl) {
397 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
398 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
399 bool neg_is_left = shl->GetRight()->IsNeg();
400 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
401 // And the shift distance being negated is the distance being shifted the other way.
402 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
403 ReplaceRotateWithRor(op, ushr, shl);
404 }
405 return false;
406}
407
408// Try replacing code looking like (x >>> d OP x << (#bits - d)):
409// UShr dst, x, d
410// Sub ld, #bits, d
411// Shl tmp, x, ld
412// OP dst, dst, tmp
413// with
414// Ror dst, x, d
415// *** OR ***
416// Replace code looking like (x >>> (#bits - d) OP x << d):
417// Sub rd, #bits, d
418// UShr dst, x, rd
419// Shl tmp, x, d
420// OP dst, dst, tmp
421// with
422// Neg neg, d
423// Ror dst, x, neg
424bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
425 HUShr* ushr,
426 HShl* shl) {
427 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
428 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
429 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
430 HInstruction* shl_shift = shl->GetRight();
431 HInstruction* ushr_shift = ushr->GetRight();
432 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
433 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
434 return ReplaceRotateWithRor(op, ushr, shl);
435 }
436 return false;
437}
438
Calin Juravle10e244f2015-01-26 18:54:32 +0000439void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
440 HInstruction* obj = null_check->InputAt(0);
441 if (!obj->CanBeNull()) {
442 null_check->ReplaceWith(obj);
443 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000444 if (stats_ != nullptr) {
445 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
446 }
447 }
448}
449
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100450bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
451 if (!input->CanBeNull()) {
452 return true;
453 }
454
Vladimir Marko46817b82016-03-29 12:21:58 +0100455 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
456 HInstruction* user = use.GetUser();
457 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100458 return true;
459 }
460 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100461
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100462 return false;
463}
464
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100465// Returns whether doing a type test between the class of `object` against `klass` has
466// a statically known outcome. The result of the test is stored in `outcome`.
467static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000468 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
469 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
470 ScopedObjectAccess soa(Thread::Current());
471 if (!obj_rti.IsValid()) {
472 // We run the simplifier before the reference type propagation so type info might not be
473 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100474 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000475 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100476
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100477 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100478 if (!class_rti.IsValid()) {
479 // Happens when the loaded class is unresolved.
480 return false;
481 }
482 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000483 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100484 *outcome = true;
485 return true;
486 } else if (obj_rti.IsExact()) {
487 // The test failed at compile time so will also fail at runtime.
488 *outcome = false;
489 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100490 } else if (!class_rti.IsInterface()
491 && !obj_rti.IsInterface()
492 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 // Different type hierarchy. The test will fail.
494 *outcome = false;
495 return true;
496 }
497 return false;
498}
499
500void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
501 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100502 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
503 if (load_class->NeedsAccessCheck()) {
504 // If we need to perform an access check we cannot remove the instruction.
505 return;
506 }
507
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100508 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 check_cast->ClearMustDoNullCheck();
510 }
511
512 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000513 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700514 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100515 return;
516 }
517
Vladimir Markoa65ed302016-03-14 21:21:29 +0000518 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
519 // the return value check with the `outcome` check, b/27651442 .
520 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700521 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100522 if (outcome) {
523 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700524 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700525 if (!load_class->HasUses()) {
526 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
527 // However, here we know that it cannot because the checkcast was successfull, hence
528 // the class was already loaded.
529 load_class->GetBlock()->RemoveInstruction(load_class);
530 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100531 } else {
532 // Don't do anything for exceptional cases for now. Ideally we should remove
533 // all instructions and blocks this instruction dominates.
534 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000535 }
536}
537
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100538void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100539 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100540 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
541 if (load_class->NeedsAccessCheck()) {
542 // If we need to perform an access check we cannot remove the instruction.
543 return;
544 }
545
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100546 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100547 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100548 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100549 instruction->ClearMustDoNullCheck();
550 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100551
552 HGraph* graph = GetGraph();
553 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700554 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100555 instruction->ReplaceWith(graph->GetIntConstant(0));
556 instruction->GetBlock()->RemoveInstruction(instruction);
557 RecordSimplification();
558 return;
559 }
560
Vladimir Marko24bd8952016-03-15 10:40:33 +0000561 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
562 // the return value check with the `outcome` check, b/27651442 .
563 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700564 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700565 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100566 if (outcome && can_be_null) {
567 // Type test will succeed, we just need a null test.
568 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
569 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
570 instruction->ReplaceWith(test);
571 } else {
572 // We've statically determined the result of the instanceof.
573 instruction->ReplaceWith(graph->GetIntConstant(outcome));
574 }
575 RecordSimplification();
576 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700577 if (outcome && !load_class->HasUses()) {
578 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
579 // However, here we know that it cannot because the instanceof check was successfull, hence
580 // the class was already loaded.
581 load_class->GetBlock()->RemoveInstruction(load_class);
582 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100583 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100584}
585
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100586void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
587 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100588 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100589 instruction->ClearValueCanBeNull();
590 }
591}
592
593void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
594 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100595 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100596 instruction->ClearValueCanBeNull();
597 }
598}
599
Anton Shaminbdd79352016-02-15 12:48:36 +0600600static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
601 HInstruction *lhs = cond->InputAt(0);
602 HInstruction *rhs = cond->InputAt(1);
603 switch (cond->GetKind()) {
604 case HInstruction::kEqual:
605 return new (arena) HEqual(rhs, lhs);
606 case HInstruction::kNotEqual:
607 return new (arena) HNotEqual(rhs, lhs);
608 case HInstruction::kLessThan:
609 return new (arena) HGreaterThan(rhs, lhs);
610 case HInstruction::kLessThanOrEqual:
611 return new (arena) HGreaterThanOrEqual(rhs, lhs);
612 case HInstruction::kGreaterThan:
613 return new (arena) HLessThan(rhs, lhs);
614 case HInstruction::kGreaterThanOrEqual:
615 return new (arena) HLessThanOrEqual(rhs, lhs);
616 case HInstruction::kBelow:
617 return new (arena) HAbove(rhs, lhs);
618 case HInstruction::kBelowOrEqual:
619 return new (arena) HAboveOrEqual(rhs, lhs);
620 case HInstruction::kAbove:
621 return new (arena) HBelow(rhs, lhs);
622 case HInstruction::kAboveOrEqual:
623 return new (arena) HBelowOrEqual(rhs, lhs);
624 default:
625 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
626 }
627 return nullptr;
628}
629
Aart Bik2767f4b2016-10-28 15:03:53 -0700630static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
631 if (input->GetType() == Primitive::kPrimBoolean) {
632 return true; // input has direct boolean type
633 } else if (cmp->GetUses().HasExactlyOneElement()) {
634 // Comparison also has boolean type if both its input and the instruction
635 // itself feed into the same phi node.
636 HInstruction* user = cmp->GetUses().front().GetUser();
637 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
638 }
639 return false;
640}
641
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000642void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100643 HInstruction* input_const = equal->GetConstantRight();
644 if (input_const != nullptr) {
645 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700646 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100647 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100648 // We are comparing the boolean to a constant which is of type int and can
649 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000650 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100651 // Replace (bool_value == true) with bool_value
652 equal->ReplaceWith(input_value);
653 block->RemoveInstruction(equal);
654 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000655 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700656 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500657 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
658 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100659 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100660 } else {
661 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
662 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
663 block->RemoveInstruction(equal);
664 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100665 }
Mark Mendellc4701932015-04-10 13:18:51 -0400666 } else {
667 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100668 }
Mark Mendellc4701932015-04-10 13:18:51 -0400669 } else {
670 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100671 }
672}
673
David Brazdil0d13fee2015-04-17 14:52:19 +0100674void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
675 HInstruction* input_const = not_equal->GetConstantRight();
676 if (input_const != nullptr) {
677 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700678 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100679 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100680 // We are comparing the boolean to a constant which is of type int and can
681 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000682 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700683 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500684 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
685 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100686 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000687 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100688 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100689 not_equal->ReplaceWith(input_value);
690 block->RemoveInstruction(not_equal);
691 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100692 } else {
693 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
694 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
695 block->RemoveInstruction(not_equal);
696 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100697 }
Mark Mendellc4701932015-04-10 13:18:51 -0400698 } else {
699 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100700 }
Mark Mendellc4701932015-04-10 13:18:51 -0400701 } else {
702 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100703 }
704}
705
706void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000707 HInstruction* input = bool_not->InputAt(0);
708 HInstruction* replace_with = nullptr;
709
710 if (input->IsIntConstant()) {
711 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000712 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000713 replace_with = GetGraph()->GetIntConstant(0);
714 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000715 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000716 replace_with = GetGraph()->GetIntConstant(1);
717 }
718 } else if (input->IsBooleanNot()) {
719 // Replace (!(!bool_value)) with bool_value.
720 replace_with = input->InputAt(0);
721 } else if (input->IsCondition() &&
722 // Don't change FP compares. The definition of compares involving
723 // NaNs forces the compares to be done as written by the user.
724 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
725 // Replace condition with its opposite.
726 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
727 }
728
729 if (replace_with != nullptr) {
730 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100731 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000732 RecordSimplification();
733 }
734}
735
736void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
737 HInstruction* replace_with = nullptr;
738 HInstruction* condition = select->GetCondition();
739 HInstruction* true_value = select->GetTrueValue();
740 HInstruction* false_value = select->GetFalseValue();
741
742 if (condition->IsBooleanNot()) {
743 // Change ((!cond) ? x : y) to (cond ? y : x).
744 condition = condition->InputAt(0);
745 std::swap(true_value, false_value);
746 select->ReplaceInput(false_value, 0);
747 select->ReplaceInput(true_value, 1);
748 select->ReplaceInput(condition, 2);
749 RecordSimplification();
750 }
751
752 if (true_value == false_value) {
753 // Replace (cond ? x : x) with (x).
754 replace_with = true_value;
755 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000756 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000757 // Replace (true ? x : y) with (x).
758 replace_with = true_value;
759 } else {
760 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000761 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000762 replace_with = false_value;
763 }
764 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000765 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000766 // Replace (cond ? true : false) with (cond).
767 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000768 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000769 // Replace (cond ? false : true) with (!cond).
770 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
771 }
772 }
773
774 if (replace_with != nullptr) {
775 select->ReplaceWith(replace_with);
776 select->GetBlock()->RemoveInstruction(select);
777 RecordSimplification();
778 }
779}
780
781void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
782 HInstruction* condition = instruction->InputAt(0);
783 if (condition->IsBooleanNot()) {
784 // Swap successors if input is negated.
785 instruction->ReplaceInput(condition->InputAt(0), 0);
786 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 RecordSimplification();
788 }
789}
790
Mingyao Yang0304e182015-01-30 16:41:29 -0800791void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
792 HInstruction* input = instruction->InputAt(0);
793 // If the array is a NewArray with constant size, replace the array length
794 // with the constant instruction. This helps the bounds check elimination phase.
795 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000796 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800797 if (input->IsIntConstant()) {
798 instruction->ReplaceWith(input);
799 }
800 }
801}
802
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000803void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000804 HInstruction* value = instruction->GetValue();
805 if (value->GetType() != Primitive::kPrimNot) return;
806
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100807 if (CanEnsureNotNullAt(value, instruction)) {
808 instruction->ClearValueCanBeNull();
809 }
810
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000811 if (value->IsArrayGet()) {
812 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
813 // If the code is just swapping elements in the array, no need for a type check.
814 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100815 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000816 }
817 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100818
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100819 if (value->IsNullConstant()) {
820 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100821 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100822 }
823
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100824 ScopedObjectAccess soa(Thread::Current());
825 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
826 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
827 if (!array_rti.IsValid()) {
828 return;
829 }
830
831 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
832 instruction->ClearNeedsTypeCheck();
833 return;
834 }
835
836 if (array_rti.IsObjectArray()) {
837 if (array_rti.IsExact()) {
838 instruction->ClearNeedsTypeCheck();
839 return;
840 }
841 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100842 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000843}
844
Vladimir Markob52bbde2016-02-12 12:06:05 +0000845static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100846 // Invariant: We should never generate a conversion to a Boolean value.
847 DCHECK_NE(Primitive::kPrimBoolean, result_type);
848
Vladimir Markob52bbde2016-02-12 12:06:05 +0000849 // Besides conversion to the same type, widening integral conversions are implicit,
850 // excluding conversions to long and the byte->char conversion where we need to
851 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
852 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100853 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
854 input_type == Primitive::kPrimByte ||
855 input_type == Primitive::kPrimShort ||
856 input_type == Primitive::kPrimChar)) ||
857 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
858 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
859 input_type == Primitive::kPrimByte)) ||
860 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000861}
862
863static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
864 // The conversion to a larger type is loss-less with the exception of two cases,
865 // - conversion to char, the only unsigned type, where we may lose some bits, and
866 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
867 // For integral to FP conversions this holds because the FP mantissa is large enough.
868 DCHECK_NE(input_type, result_type);
869 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
870 result_type != Primitive::kPrimChar &&
871 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
872}
873
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000874void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000875 HInstruction* input = instruction->GetInput();
876 Primitive::Type input_type = input->GetType();
877 Primitive::Type result_type = instruction->GetResultType();
878 if (IsTypeConversionImplicit(input_type, result_type)) {
879 // Remove the implicit conversion; this includes conversion to the same type.
880 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000881 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000882 RecordSimplification();
883 return;
884 }
885
886 if (input->IsTypeConversion()) {
887 HTypeConversion* input_conversion = input->AsTypeConversion();
888 HInstruction* original_input = input_conversion->GetInput();
889 Primitive::Type original_type = original_input->GetType();
890
891 // When the first conversion is lossless, a direct conversion from the original type
892 // to the final type yields the same result, even for a lossy second conversion, for
893 // example float->double->int or int->double->float.
894 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
895
896 // For integral conversions, see if the first conversion loses only bits that the second
897 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
898 // conversion yields the same result, for example long->int->short or int->char->short.
899 bool integral_conversions_with_non_widening_second =
900 Primitive::IsIntegralType(input_type) &&
901 Primitive::IsIntegralType(original_type) &&
902 Primitive::IsIntegralType(result_type) &&
903 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
904
905 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
906 // If the merged conversion is implicit, do the simplification unconditionally.
907 if (IsTypeConversionImplicit(original_type, result_type)) {
908 instruction->ReplaceWith(original_input);
909 instruction->GetBlock()->RemoveInstruction(instruction);
910 if (!input_conversion->HasUses()) {
911 // Don't wait for DCE.
912 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
913 }
914 RecordSimplification();
915 return;
916 }
917 // Otherwise simplify only if the first conversion has no other use.
918 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
919 input_conversion->ReplaceWith(original_input);
920 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
921 RecordSimplification();
922 return;
923 }
924 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000925 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000926 DCHECK(Primitive::IsIntegralType(input_type));
927 HAnd* input_and = input->AsAnd();
928 HConstant* constant = input_and->GetConstantRight();
929 if (constant != nullptr) {
930 int64_t value = Int64FromConstant(constant);
931 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
932 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
933 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
934 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000935 HInstruction* original_input = input_and->GetLeastConstantLeft();
936 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
937 instruction->ReplaceWith(original_input);
938 instruction->GetBlock()->RemoveInstruction(instruction);
939 RecordSimplification();
940 return;
941 } else if (input->HasOnlyOneNonEnvironmentUse()) {
942 input_and->ReplaceWith(original_input);
943 input_and->GetBlock()->RemoveInstruction(input_and);
944 RecordSimplification();
945 return;
946 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000947 }
948 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000949 }
950}
951
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000952void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
953 HConstant* input_cst = instruction->GetConstantRight();
954 HInstruction* input_other = instruction->GetLeastConstantLeft();
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600955 bool integral_type = Primitive::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +0000956 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000957 // Replace code looking like
958 // ADD dst, src, 0
959 // with
960 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600961 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
962 // `x` is `-0.0`, the former expression yields `0.0`, while the later
963 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600964 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +0600965 instruction->ReplaceWith(input_other);
966 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100967 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600968 return;
969 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100970 }
971
972 HInstruction* left = instruction->GetLeft();
973 HInstruction* right = instruction->GetRight();
974 bool left_is_neg = left->IsNeg();
975 bool right_is_neg = right->IsNeg();
976
977 if (left_is_neg && right_is_neg) {
978 if (TryMoveNegOnInputsAfterBinop(instruction)) {
979 return;
980 }
981 }
982
983 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
984 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
985 // Replace code looking like
986 // NEG tmp, b
987 // ADD dst, a, tmp
988 // with
989 // SUB dst, a, b
990 // We do not perform the optimization if the input negation has environment
991 // uses or multiple non-environment uses as it could lead to worse code. In
992 // particular, we do not want the live range of `b` to be extended if we are
993 // not sure the initial 'NEG' instruction can be removed.
994 HInstruction* other = left_is_neg ? right : left;
995 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
996 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
997 RecordSimplification();
998 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000999 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001000 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001001
Anton Kirilove14dc862016-05-13 17:56:15 +01001002 if (TryReplaceWithRotate(instruction)) {
1003 return;
1004 }
1005
1006 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1007 // so no need to return.
1008 TryHandleAssociativeAndCommutativeOperation(instruction);
1009
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001010 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001011 TrySubtractionChainSimplification(instruction)) {
1012 return;
1013 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001014
1015 if (integral_type) {
1016 // Replace code patterns looking like
1017 // SUB dst1, x, y SUB dst1, x, y
1018 // ADD dst2, dst1, y ADD dst2, y, dst1
1019 // with
1020 // SUB dst1, x, y
1021 // ADD instruction is not needed in this case, we may use
1022 // one of inputs of SUB instead.
1023 if (left->IsSub() && left->InputAt(1) == right) {
1024 instruction->ReplaceWith(left->InputAt(0));
1025 RecordSimplification();
1026 instruction->GetBlock()->RemoveInstruction(instruction);
1027 return;
1028 } else if (right->IsSub() && right->InputAt(1) == left) {
1029 instruction->ReplaceWith(right->InputAt(0));
1030 RecordSimplification();
1031 instruction->GetBlock()->RemoveInstruction(instruction);
1032 return;
1033 }
1034 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001035}
1036
1037void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1038 HConstant* input_cst = instruction->GetConstantRight();
1039 HInstruction* input_other = instruction->GetLeastConstantLeft();
1040
Vladimir Marko452c1b62015-09-25 14:44:17 +01001041 if (input_cst != nullptr) {
1042 int64_t value = Int64FromConstant(input_cst);
1043 if (value == -1) {
1044 // Replace code looking like
1045 // AND dst, src, 0xFFF...FF
1046 // with
1047 // src
1048 instruction->ReplaceWith(input_other);
1049 instruction->GetBlock()->RemoveInstruction(instruction);
1050 RecordSimplification();
1051 return;
1052 }
1053 // Eliminate And from UShr+And if the And-mask contains all the bits that
1054 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1055 // precisely clears the shifted-in sign bits.
1056 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1057 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1058 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1059 size_t num_tail_bits_set = CTZ(value + 1);
1060 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1061 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1062 instruction->ReplaceWith(input_other);
1063 instruction->GetBlock()->RemoveInstruction(instruction);
1064 RecordSimplification();
1065 return;
1066 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1067 input_other->HasOnlyOneNonEnvironmentUse()) {
1068 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1069 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1070 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1071 input_other->InputAt(0),
1072 input_other->InputAt(1),
1073 input_other->GetDexPc());
1074 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1075 input_other->GetBlock()->RemoveInstruction(input_other);
1076 RecordSimplification();
1077 return;
1078 }
1079 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001080 }
1081
1082 // We assume that GVN has run before, so we only perform a pointer comparison.
1083 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001084 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001085 if (instruction->GetLeft() == instruction->GetRight()) {
1086 // Replace code looking like
1087 // AND dst, src, src
1088 // with
1089 // src
1090 instruction->ReplaceWith(instruction->GetLeft());
1091 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001092 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001093 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001094 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001095
Anton Kirilove14dc862016-05-13 17:56:15 +01001096 if (TryDeMorganNegationFactoring(instruction)) {
1097 return;
1098 }
1099
1100 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1101 // so no need to return.
1102 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001103}
1104
Mark Mendellc4701932015-04-10 13:18:51 -04001105void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1106 VisitCondition(condition);
1107}
1108
1109void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1110 VisitCondition(condition);
1111}
1112
1113void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1114 VisitCondition(condition);
1115}
1116
1117void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1118 VisitCondition(condition);
1119}
1120
Anton Shaminbdd79352016-02-15 12:48:36 +06001121void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1122 VisitCondition(condition);
1123}
1124
1125void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1126 VisitCondition(condition);
1127}
1128
1129void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1130 VisitCondition(condition);
1131}
1132
1133void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1134 VisitCondition(condition);
1135}
Aart Bike9f37602015-10-09 11:15:55 -07001136
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001137// Recognize the following pattern:
1138// obj.getClass() ==/!= Foo.class
1139// And replace it with a constant value if the type of `obj` is statically known.
1140static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1141 HInstruction* input_one = condition->InputAt(0);
1142 HInstruction* input_two = condition->InputAt(1);
1143 HLoadClass* load_class = input_one->IsLoadClass()
1144 ? input_one->AsLoadClass()
1145 : input_two->AsLoadClass();
1146 if (load_class == nullptr) {
1147 return false;
1148 }
1149
1150 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1151 if (!class_rti.IsValid()) {
1152 // Unresolved class.
1153 return false;
1154 }
1155
1156 HInstanceFieldGet* field_get = (load_class == input_one)
1157 ? input_two->AsInstanceFieldGet()
1158 : input_one->AsInstanceFieldGet();
1159 if (field_get == nullptr) {
1160 return false;
1161 }
1162
1163 HInstruction* receiver = field_get->InputAt(0);
1164 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1165 if (!receiver_type.IsExact()) {
1166 return false;
1167 }
1168
1169 {
1170 ScopedObjectAccess soa(Thread::Current());
1171 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1172 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1173 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1174 if (field_get->GetFieldInfo().GetField() != field) {
1175 return false;
1176 }
1177
1178 // We can replace the compare.
1179 int value = 0;
1180 if (receiver_type.IsEqual(class_rti)) {
1181 value = condition->IsEqual() ? 1 : 0;
1182 } else {
1183 value = condition->IsNotEqual() ? 1 : 0;
1184 }
1185 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1186 return true;
1187 }
1188}
1189
Mark Mendellc4701932015-04-10 13:18:51 -04001190void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001191 if (condition->IsEqual() || condition->IsNotEqual()) {
1192 if (RecognizeAndSimplifyClassCheck(condition)) {
1193 return;
1194 }
1195 }
1196
Anton Shaminbdd79352016-02-15 12:48:36 +06001197 // Reverse condition if left is constant. Our code generators prefer constant
1198 // on the right hand side.
1199 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1200 HBasicBlock* block = condition->GetBlock();
1201 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1202 // If it is a fp we must set the opposite bias.
1203 if (replacement != nullptr) {
1204 if (condition->IsLtBias()) {
1205 replacement->SetBias(ComparisonBias::kGtBias);
1206 } else if (condition->IsGtBias()) {
1207 replacement->SetBias(ComparisonBias::kLtBias);
1208 }
1209 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1210 RecordSimplification();
1211
1212 condition = replacement;
1213 }
1214 }
Mark Mendellc4701932015-04-10 13:18:51 -04001215
Mark Mendellc4701932015-04-10 13:18:51 -04001216 HInstruction* left = condition->GetLeft();
1217 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001218
1219 // Try to fold an HCompare into this HCondition.
1220
Mark Mendellc4701932015-04-10 13:18:51 -04001221 // We can only replace an HCondition which compares a Compare to 0.
1222 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1223 // condition with a long, float or double comparison as input.
1224 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1225 // Conversion is not possible.
1226 return;
1227 }
1228
1229 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001230 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001231 // Someone else also wants the result of the compare.
1232 return;
1233 }
1234
Vladimir Marko46817b82016-03-29 12:21:58 +01001235 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001236 // There is a reference to the compare result in an environment. Do we really need it?
1237 if (GetGraph()->IsDebuggable()) {
1238 return;
1239 }
1240
1241 // We have to ensure that there are no deopt points in the sequence.
1242 if (left->HasAnyEnvironmentUseBefore(condition)) {
1243 return;
1244 }
1245 }
1246
1247 // Clean up any environment uses from the HCompare, if any.
1248 left->RemoveEnvironmentUsers();
1249
1250 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1251 condition->SetBias(left->AsCompare()->GetBias());
1252
1253 // Replace the operands of the HCondition.
1254 condition->ReplaceInput(left->InputAt(0), 0);
1255 condition->ReplaceInput(left->InputAt(1), 1);
1256
1257 // Remove the HCompare.
1258 left->GetBlock()->RemoveInstruction(left);
1259
1260 RecordSimplification();
1261}
1262
Andreas Gampe9186ced2016-12-12 14:28:21 -08001263// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1264static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1265 // True, if the most significant bits of divisor are 0.
1266 return ((divisor & 0x7fffff) == 0);
1267}
1268
1269// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1270static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1271 // True, if the most significant bits of divisor are 0.
1272 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1273}
1274
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001275void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1276 HConstant* input_cst = instruction->GetConstantRight();
1277 HInstruction* input_other = instruction->GetLeastConstantLeft();
1278 Primitive::Type type = instruction->GetType();
1279
1280 if ((input_cst != nullptr) && input_cst->IsOne()) {
1281 // Replace code looking like
1282 // DIV dst, src, 1
1283 // with
1284 // src
1285 instruction->ReplaceWith(input_other);
1286 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001287 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001288 return;
1289 }
1290
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001291 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001292 // Replace code looking like
1293 // DIV dst, src, -1
1294 // with
1295 // NEG dst, src
1296 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001297 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001298 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001299 return;
1300 }
1301
1302 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1303 // Try replacing code looking like
1304 // DIV dst, src, constant
1305 // with
1306 // MUL dst, src, 1 / constant
1307 HConstant* reciprocal = nullptr;
1308 if (type == Primitive::Primitive::kPrimDouble) {
1309 double value = input_cst->AsDoubleConstant()->GetValue();
1310 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1311 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1312 }
1313 } else {
1314 DCHECK_EQ(type, Primitive::kPrimFloat);
1315 float value = input_cst->AsFloatConstant()->GetValue();
1316 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1317 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1318 }
1319 }
1320
1321 if (reciprocal != nullptr) {
1322 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1323 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1324 RecordSimplification();
1325 return;
1326 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001327 }
1328}
1329
1330void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1331 HConstant* input_cst = instruction->GetConstantRight();
1332 HInstruction* input_other = instruction->GetLeastConstantLeft();
1333 Primitive::Type type = instruction->GetType();
1334 HBasicBlock* block = instruction->GetBlock();
1335 ArenaAllocator* allocator = GetGraph()->GetArena();
1336
1337 if (input_cst == nullptr) {
1338 return;
1339 }
1340
1341 if (input_cst->IsOne()) {
1342 // Replace code looking like
1343 // MUL dst, src, 1
1344 // with
1345 // src
1346 instruction->ReplaceWith(input_other);
1347 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001348 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001349 return;
1350 }
1351
1352 if (input_cst->IsMinusOne() &&
1353 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1354 // Replace code looking like
1355 // MUL dst, src, -1
1356 // with
1357 // NEG dst, src
1358 HNeg* neg = new (allocator) HNeg(type, input_other);
1359 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001360 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001361 return;
1362 }
1363
1364 if (Primitive::IsFloatingPointType(type) &&
1365 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1366 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1367 // Replace code looking like
1368 // FP_MUL dst, src, 2.0
1369 // with
1370 // FP_ADD dst, src, src
1371 // The 'int' and 'long' cases are handled below.
1372 block->ReplaceAndRemoveInstructionWith(instruction,
1373 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001374 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001375 return;
1376 }
1377
1378 if (Primitive::IsIntOrLongType(type)) {
1379 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001380 // Even though constant propagation also takes care of the zero case, other
1381 // optimizations can lead to having a zero multiplication.
1382 if (factor == 0) {
1383 // Replace code looking like
1384 // MUL dst, src, 0
1385 // with
1386 // 0
1387 instruction->ReplaceWith(input_cst);
1388 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001389 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001390 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001391 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001392 // Replace code looking like
1393 // MUL dst, src, pow_of_2
1394 // with
1395 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001396 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001397 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001398 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001399 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001400 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001401 } else if (IsPowerOfTwo(factor - 1)) {
1402 // Transform code looking like
1403 // MUL dst, src, (2^n + 1)
1404 // into
1405 // SHL tmp, src, n
1406 // ADD dst, src, tmp
1407 HShl* shl = new (allocator) HShl(type,
1408 input_other,
1409 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1410 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1411
1412 block->InsertInstructionBefore(shl, instruction);
1413 block->ReplaceAndRemoveInstructionWith(instruction, add);
1414 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001415 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001416 } else if (IsPowerOfTwo(factor + 1)) {
1417 // Transform code looking like
1418 // MUL dst, src, (2^n - 1)
1419 // into
1420 // SHL tmp, src, n
1421 // SUB dst, tmp, src
1422 HShl* shl = new (allocator) HShl(type,
1423 input_other,
1424 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1425 HSub* sub = new (allocator) HSub(type, shl, input_other);
1426
1427 block->InsertInstructionBefore(shl, instruction);
1428 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1429 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001430 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001431 }
1432 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001433
1434 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1435 // so no need to return.
1436 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001437}
1438
Alexandre Rames188d4312015-04-09 18:30:21 +01001439void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1440 HInstruction* input = instruction->GetInput();
1441 if (input->IsNeg()) {
1442 // Replace code looking like
1443 // NEG tmp, src
1444 // NEG dst, tmp
1445 // with
1446 // src
1447 HNeg* previous_neg = input->AsNeg();
1448 instruction->ReplaceWith(previous_neg->GetInput());
1449 instruction->GetBlock()->RemoveInstruction(instruction);
1450 // We perform the optimization even if the input negation has environment
1451 // uses since it allows removing the current instruction. But we only delete
1452 // the input negation only if it is does not have any uses left.
1453 if (!previous_neg->HasUses()) {
1454 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1455 }
1456 RecordSimplification();
1457 return;
1458 }
1459
Serguei Katkov339dfc22015-04-20 12:29:32 +06001460 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1461 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001462 // Replace code looking like
1463 // SUB tmp, a, b
1464 // NEG dst, tmp
1465 // with
1466 // SUB dst, b, a
1467 // We do not perform the optimization if the input subtraction has
1468 // environment uses or multiple non-environment uses as it could lead to
1469 // worse code. In particular, we do not want the live ranges of `a` and `b`
1470 // to be extended if we are not sure the initial 'SUB' instruction can be
1471 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001472 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001473 HSub* sub = input->AsSub();
1474 HSub* new_sub =
1475 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1476 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1477 if (!sub->HasUses()) {
1478 sub->GetBlock()->RemoveInstruction(sub);
1479 }
1480 RecordSimplification();
1481 }
1482}
1483
1484void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1485 HInstruction* input = instruction->GetInput();
1486 if (input->IsNot()) {
1487 // Replace code looking like
1488 // NOT tmp, src
1489 // NOT dst, tmp
1490 // with
1491 // src
1492 // We perform the optimization even if the input negation has environment
1493 // uses since it allows removing the current instruction. But we only delete
1494 // the input negation only if it is does not have any uses left.
1495 HNot* previous_not = input->AsNot();
1496 instruction->ReplaceWith(previous_not->GetInput());
1497 instruction->GetBlock()->RemoveInstruction(instruction);
1498 if (!previous_not->HasUses()) {
1499 previous_not->GetBlock()->RemoveInstruction(previous_not);
1500 }
1501 RecordSimplification();
1502 }
1503}
1504
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001505void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1506 HConstant* input_cst = instruction->GetConstantRight();
1507 HInstruction* input_other = instruction->GetLeastConstantLeft();
1508
Roland Levillain1a653882016-03-18 18:05:57 +00001509 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001510 // Replace code looking like
1511 // OR dst, src, 0
1512 // with
1513 // src
1514 instruction->ReplaceWith(input_other);
1515 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001516 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001517 return;
1518 }
1519
1520 // We assume that GVN has run before, so we only perform a pointer comparison.
1521 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001522 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001523 if (instruction->GetLeft() == instruction->GetRight()) {
1524 // Replace code looking like
1525 // OR dst, src, src
1526 // with
1527 // src
1528 instruction->ReplaceWith(instruction->GetLeft());
1529 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001530 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001531 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001532 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001533
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001534 if (TryDeMorganNegationFactoring(instruction)) return;
1535
Anton Kirilove14dc862016-05-13 17:56:15 +01001536 if (TryReplaceWithRotate(instruction)) {
1537 return;
1538 }
1539
1540 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1541 // so no need to return.
1542 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001543}
1544
1545void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1546 VisitShift(instruction);
1547}
1548
1549void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1550 VisitShift(instruction);
1551}
1552
1553void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1554 HConstant* input_cst = instruction->GetConstantRight();
1555 HInstruction* input_other = instruction->GetLeastConstantLeft();
1556
Serguei Katkov115b53f2015-08-05 17:03:30 +06001557 Primitive::Type type = instruction->GetType();
1558 if (Primitive::IsFloatingPointType(type)) {
1559 return;
1560 }
1561
Roland Levillain1a653882016-03-18 18:05:57 +00001562 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001563 // Replace code looking like
1564 // SUB dst, src, 0
1565 // with
1566 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001567 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1568 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1569 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001570 instruction->ReplaceWith(input_other);
1571 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001572 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001573 return;
1574 }
1575
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001576 HBasicBlock* block = instruction->GetBlock();
1577 ArenaAllocator* allocator = GetGraph()->GetArena();
1578
Alexandre Rames188d4312015-04-09 18:30:21 +01001579 HInstruction* left = instruction->GetLeft();
1580 HInstruction* right = instruction->GetRight();
1581 if (left->IsConstant()) {
1582 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001583 // Replace code looking like
1584 // SUB dst, 0, src
1585 // with
1586 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001587 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001588 // `x` is `0.0`, the former expression yields `0.0`, while the later
1589 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001590 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001591 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001592 RecordSimplification();
1593 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001594 }
1595 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001596
1597 if (left->IsNeg() && right->IsNeg()) {
1598 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1599 return;
1600 }
1601 }
1602
1603 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1604 // Replace code looking like
1605 // NEG tmp, b
1606 // SUB dst, a, tmp
1607 // with
1608 // ADD dst, a, b
1609 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1610 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1611 RecordSimplification();
1612 right->GetBlock()->RemoveInstruction(right);
1613 return;
1614 }
1615
1616 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1617 // Replace code looking like
1618 // NEG tmp, a
1619 // SUB dst, tmp, b
1620 // with
1621 // ADD tmp, a, b
1622 // NEG dst, tmp
1623 // The second version is not intrinsically better, but enables more
1624 // transformations.
1625 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1626 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1627 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1628 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1629 instruction->ReplaceWith(neg);
1630 instruction->GetBlock()->RemoveInstruction(instruction);
1631 RecordSimplification();
1632 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001633 return;
1634 }
1635
1636 if (TrySubtractionChainSimplification(instruction)) {
1637 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001638 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001639
1640 if (left->IsAdd()) {
1641 // Replace code patterns looking like
1642 // ADD dst1, x, y ADD dst1, x, y
1643 // SUB dst2, dst1, y SUB dst2, dst1, x
1644 // with
1645 // ADD dst1, x, y
1646 // SUB instruction is not needed in this case, we may use
1647 // one of inputs of ADD instead.
1648 // It is applicable to integral types only.
1649 DCHECK(Primitive::IsIntegralType(type));
1650 if (left->InputAt(1) == right) {
1651 instruction->ReplaceWith(left->InputAt(0));
1652 RecordSimplification();
1653 instruction->GetBlock()->RemoveInstruction(instruction);
1654 return;
1655 } else if (left->InputAt(0) == right) {
1656 instruction->ReplaceWith(left->InputAt(1));
1657 RecordSimplification();
1658 instruction->GetBlock()->RemoveInstruction(instruction);
1659 return;
1660 }
1661 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001662}
1663
1664void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1665 VisitShift(instruction);
1666}
1667
1668void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1669 HConstant* input_cst = instruction->GetConstantRight();
1670 HInstruction* input_other = instruction->GetLeastConstantLeft();
1671
Roland Levillain1a653882016-03-18 18:05:57 +00001672 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001673 // Replace code looking like
1674 // XOR dst, src, 0
1675 // with
1676 // src
1677 instruction->ReplaceWith(input_other);
1678 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001679 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001680 return;
1681 }
1682
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001683 if ((input_cst != nullptr) && input_cst->IsOne()
1684 && input_other->GetType() == Primitive::kPrimBoolean) {
1685 // Replace code looking like
1686 // XOR dst, src, 1
1687 // with
1688 // BOOLEAN_NOT dst, src
1689 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1690 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1691 RecordSimplification();
1692 return;
1693 }
1694
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001695 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1696 // Replace code looking like
1697 // XOR dst, src, 0xFFF...FF
1698 // with
1699 // NOT dst, src
1700 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1701 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001702 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001703 return;
1704 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001705
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001706 HInstruction* left = instruction->GetLeft();
1707 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001708 if (((left->IsNot() && right->IsNot()) ||
1709 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001710 left->HasOnlyOneNonEnvironmentUse() &&
1711 right->HasOnlyOneNonEnvironmentUse()) {
1712 // Replace code looking like
1713 // NOT nota, a
1714 // NOT notb, b
1715 // XOR dst, nota, notb
1716 // with
1717 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001718 instruction->ReplaceInput(left->InputAt(0), 0);
1719 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001720 left->GetBlock()->RemoveInstruction(left);
1721 right->GetBlock()->RemoveInstruction(right);
1722 RecordSimplification();
1723 return;
1724 }
1725
Anton Kirilove14dc862016-05-13 17:56:15 +01001726 if (TryReplaceWithRotate(instruction)) {
1727 return;
1728 }
1729
1730 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1731 // so no need to return.
1732 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001733}
1734
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001735void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1736 HInstruction* argument = instruction->InputAt(1);
1737 HInstruction* receiver = instruction->InputAt(0);
1738 if (receiver == argument) {
1739 // Because String.equals is an instance call, the receiver is
1740 // a null check if we don't know it's null. The argument however, will
1741 // be the actual object. So we cannot end up in a situation where both
1742 // are equal but could be null.
1743 DCHECK(CanEnsureNotNullAt(argument, instruction));
1744 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1745 instruction->GetBlock()->RemoveInstruction(instruction);
1746 } else {
1747 StringEqualsOptimizations optimizations(instruction);
1748 if (CanEnsureNotNullAt(argument, instruction)) {
1749 optimizations.SetArgumentNotNull();
1750 }
1751 ScopedObjectAccess soa(Thread::Current());
1752 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1753 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1754 optimizations.SetArgumentIsString();
1755 }
1756 }
1757}
1758
Roland Levillain22c49222016-03-18 14:04:28 +00001759void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1760 bool is_left,
1761 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001762 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001763 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001764 HInstruction* value = invoke->InputAt(0);
1765 HInstruction* distance = invoke->InputAt(1);
1766 // Replace the invoke with an HRor.
1767 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001768 // Unconditionally set the type of the negated distance to `int`,
1769 // as shift and rotate operations expect a 32-bit (or narrower)
1770 // value for their distance input.
1771 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001772 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1773 }
Roland Levillain22c49222016-03-18 14:04:28 +00001774 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001775 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1776 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001777 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001778 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1779 clinit->GetBlock()->RemoveInstruction(clinit);
1780 HInstruction* ldclass = clinit->InputAt(0);
1781 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1782 ldclass->GetBlock()->RemoveInstruction(ldclass);
1783 }
1784 }
1785}
1786
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001787static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1788 if (potential_length->IsArrayLength()) {
1789 return potential_length->InputAt(0) == potential_array;
1790 }
1791
1792 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001793 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001794 }
1795
1796 return false;
1797}
1798
1799void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1800 HInstruction* source = instruction->InputAt(0);
1801 HInstruction* destination = instruction->InputAt(2);
1802 HInstruction* count = instruction->InputAt(4);
1803 SystemArrayCopyOptimizations optimizations(instruction);
1804 if (CanEnsureNotNullAt(source, instruction)) {
1805 optimizations.SetSourceIsNotNull();
1806 }
1807 if (CanEnsureNotNullAt(destination, instruction)) {
1808 optimizations.SetDestinationIsNotNull();
1809 }
1810 if (destination == source) {
1811 optimizations.SetDestinationIsSource();
1812 }
1813
1814 if (IsArrayLengthOf(count, source)) {
1815 optimizations.SetCountIsSourceLength();
1816 }
1817
1818 if (IsArrayLengthOf(count, destination)) {
1819 optimizations.SetCountIsDestinationLength();
1820 }
1821
1822 {
1823 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001824 Primitive::Type source_component_type = Primitive::kPrimVoid;
1825 Primitive::Type destination_component_type = Primitive::kPrimVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001826 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1827 if (destination_rti.IsValid()) {
1828 if (destination_rti.IsObjectArray()) {
1829 if (destination_rti.IsExact()) {
1830 optimizations.SetDoesNotNeedTypeCheck();
1831 }
1832 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001833 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001834 if (destination_rti.IsPrimitiveArrayClass()) {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001835 destination_component_type =
1836 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001837 optimizations.SetDestinationIsPrimitiveArray();
1838 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1839 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001840 }
1841 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001842 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1843 if (source_rti.IsValid()) {
1844 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1845 optimizations.SetDoesNotNeedTypeCheck();
1846 }
1847 if (source_rti.IsPrimitiveArrayClass()) {
1848 optimizations.SetSourceIsPrimitiveArray();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001849 source_component_type = source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001850 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1851 optimizations.SetSourceIsNonPrimitiveArray();
1852 }
1853 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001854 // For primitive arrays, use their optimized ArtMethod implementations.
1855 if ((source_component_type != Primitive::kPrimVoid) &&
1856 (source_component_type == destination_component_type)) {
1857 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1858 PointerSize image_size = class_linker->GetImagePointerSize();
1859 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1860 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
1861 ArtMethod* method = nullptr;
1862 switch (source_component_type) {
1863 case Primitive::kPrimBoolean:
Vladimir Markoba118822017-06-12 15:41:56 +01001864 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001865 break;
1866 case Primitive::kPrimByte:
Vladimir Markoba118822017-06-12 15:41:56 +01001867 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001868 break;
1869 case Primitive::kPrimChar:
Vladimir Markoba118822017-06-12 15:41:56 +01001870 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001871 break;
1872 case Primitive::kPrimShort:
Vladimir Markoba118822017-06-12 15:41:56 +01001873 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001874 break;
1875 case Primitive::kPrimInt:
Vladimir Markoba118822017-06-12 15:41:56 +01001876 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001877 break;
1878 case Primitive::kPrimFloat:
Vladimir Markoba118822017-06-12 15:41:56 +01001879 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001880 break;
1881 case Primitive::kPrimLong:
Vladimir Markoba118822017-06-12 15:41:56 +01001882 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001883 break;
1884 case Primitive::kPrimDouble:
Vladimir Markoba118822017-06-12 15:41:56 +01001885 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001886 break;
1887 default:
1888 LOG(FATAL) << "Unreachable";
1889 }
1890 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001891 DCHECK(method->IsStatic());
1892 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001893 invoke->SetResolvedMethod(method);
1894 // Sharpen the new invoke. Note that we do not update the dex method index of
1895 // the invoke, as we would need to look it up in the current dex file, and it
1896 // is unlikely that it exists. The most usual situation for such typed
1897 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01001898 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001899 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001900 }
1901}
1902
Roland Levillaina5c4a402016-03-15 15:02:50 +00001903void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1904 bool is_signum,
1905 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001906 DCHECK(invoke->IsInvokeStaticOrDirect());
1907 uint32_t dex_pc = invoke->GetDexPc();
1908 HInstruction* left = invoke->InputAt(0);
1909 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001910 if (!is_signum) {
1911 right = invoke->InputAt(1);
1912 } else if (type == Primitive::kPrimLong) {
1913 right = GetGraph()->GetLongConstant(0);
1914 } else {
1915 right = GetGraph()->GetIntConstant(0);
1916 }
1917 HCompare* compare = new (GetGraph()->GetArena())
1918 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1919 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1920}
1921
Aart Bik75a38b22016-02-17 10:41:50 -08001922void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1923 DCHECK(invoke->IsInvokeStaticOrDirect());
1924 uint32_t dex_pc = invoke->GetDexPc();
1925 // IsNaN(x) is the same as x != x.
1926 HInstruction* x = invoke->InputAt(0);
1927 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001928 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001929 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1930}
1931
Aart Bik2a6aad92016-02-25 11:32:32 -08001932void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1933 DCHECK(invoke->IsInvokeStaticOrDirect());
1934 uint32_t dex_pc = invoke->GetDexPc();
1935 HInstruction* x = invoke->InputAt(0);
1936 Primitive::Type type = x->GetType();
1937 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1938 HInstruction* nan;
1939 if (type == Primitive::kPrimDouble) {
1940 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1941 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1942 kNeedsEnvironmentOrCache,
1943 kNoSideEffects,
1944 kNoThrow);
1945 } else {
1946 DCHECK_EQ(type, Primitive::kPrimFloat);
1947 nan = GetGraph()->GetIntConstant(0x7fc00000);
1948 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1949 kNeedsEnvironmentOrCache,
1950 kNoSideEffects,
1951 kNoThrow);
1952 }
1953 // Test IsNaN(x), which is the same as x != x.
1954 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1955 condition->SetBias(ComparisonBias::kLtBias);
1956 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1957 // Select between the two.
1958 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1959 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1960 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1961}
1962
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001963void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1964 HInstruction* str = invoke->InputAt(0);
1965 HInstruction* index = invoke->InputAt(1);
1966 uint32_t dex_pc = invoke->GetDexPc();
1967 ArenaAllocator* arena = GetGraph()->GetArena();
1968 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1969 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1970 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1971 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00001972 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
1973 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001974 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00001975 HArrayGet* array_get = new (arena) HArrayGet(
1976 str, bounds_check, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001977 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1978 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1979 GetGraph()->SetHasBoundsChecks(true);
1980}
1981
Vladimir Markodce016e2016-04-28 13:10:02 +01001982void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1983 HInstruction* str = invoke->InputAt(0);
1984 uint32_t dex_pc = invoke->GetDexPc();
1985 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1986 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001987 HArrayLength* length =
1988 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001989 HInstruction* replacement;
1990 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1991 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1992 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1993 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1994 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1995 replacement = equal;
1996 } else {
1997 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1998 replacement = length;
1999 }
2000 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2001}
2002
Aart Bikff7d89c2016-11-07 08:49:28 -08002003// This method should only be used on intrinsics whose sole way of throwing an
2004// exception is raising a NPE when the nth argument is null. If that argument
2005// is provably non-null, we can clear the flag.
2006void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2007 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002008 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002009 invoke->SetCanThrow(false);
2010 }
2011}
2012
Aart Bik71bf7b42016-11-16 10:17:46 -08002013// Methods that return "this" can replace the returned value with the receiver.
2014void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2015 if (invoke->HasUses()) {
2016 HInstruction* receiver = invoke->InputAt(0);
2017 invoke->ReplaceWith(receiver);
2018 RecordSimplification();
2019 }
2020}
2021
2022// Helper method for StringBuffer escape analysis.
2023static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2024 if (user->IsInvokeStaticOrDirect()) {
2025 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002026 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2027 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002028 user->InputAt(0) == reference;
2029 } else if (user->IsInvokeVirtual()) {
2030 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2031 case Intrinsics::kStringBufferLength:
2032 case Intrinsics::kStringBufferToString:
2033 DCHECK_EQ(user->InputAt(0), reference);
2034 return true;
2035 case Intrinsics::kStringBufferAppend:
2036 // Returns "this", so only okay if no further uses.
2037 DCHECK_EQ(user->InputAt(0), reference);
2038 DCHECK_NE(user->InputAt(1), reference);
2039 return !user->HasUses();
2040 default:
2041 break;
2042 }
2043 }
2044 return false;
2045}
2046
2047// Certain allocation intrinsics are not removed by dead code elimination
2048// because of potentially throwing an OOM exception or other side effects.
2049// This method removes such intrinsics when special circumstances allow.
2050void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2051 if (!invoke->HasUses()) {
2052 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2053 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2054 // call does not escape since only thread-local synchronization may be removed.
2055 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2056 HInstruction* receiver = invoke->InputAt(0);
2057 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2058 invoke->GetBlock()->RemoveInstruction(invoke);
2059 RecordSimplification();
2060 }
2061 }
2062}
2063
Aart Bik11932592016-03-08 12:42:25 -08002064void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2065 uint32_t dex_pc = invoke->GetDexPc();
2066 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2067 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2068}
2069
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002070void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002071 switch (instruction->GetIntrinsic()) {
2072 case Intrinsics::kStringEquals:
2073 SimplifyStringEquals(instruction);
2074 break;
2075 case Intrinsics::kSystemArrayCopy:
2076 SimplifySystemArrayCopy(instruction);
2077 break;
2078 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002079 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
2080 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002081 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002082 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002083 break;
2084 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002085 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
2086 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002087 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002088 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002089 break;
2090 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002091 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
2092 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002093 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002094 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002095 break;
2096 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002097 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
2098 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002099 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002100 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002101 break;
2102 case Intrinsics::kFloatIsNaN:
2103 case Intrinsics::kDoubleIsNaN:
2104 SimplifyIsNaN(instruction);
2105 break;
2106 case Intrinsics::kFloatFloatToIntBits:
2107 case Intrinsics::kDoubleDoubleToLongBits:
2108 SimplifyFP2Int(instruction);
2109 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002110 case Intrinsics::kStringCharAt:
2111 SimplifyStringCharAt(instruction);
2112 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002113 case Intrinsics::kStringIsEmpty:
2114 case Intrinsics::kStringLength:
2115 SimplifyStringIsEmptyOrLength(instruction);
2116 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002117 case Intrinsics::kStringStringIndexOf:
2118 case Intrinsics::kStringStringIndexOfAfter:
2119 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2120 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002121 case Intrinsics::kStringBufferAppend:
2122 case Intrinsics::kStringBuilderAppend:
2123 SimplifyReturnThis(instruction);
2124 break;
2125 case Intrinsics::kStringBufferToString:
2126 case Intrinsics::kStringBuilderToString:
2127 SimplifyAllocationIntrinsic(instruction);
2128 break;
Aart Bik11932592016-03-08 12:42:25 -08002129 case Intrinsics::kUnsafeLoadFence:
2130 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2131 break;
2132 case Intrinsics::kUnsafeStoreFence:
2133 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2134 break;
2135 case Intrinsics::kUnsafeFullFence:
2136 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2137 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002138 default:
2139 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002140 }
2141}
2142
Aart Bikbb245d12015-10-19 11:05:03 -07002143void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2144 HInstruction* cond = deoptimize->InputAt(0);
2145 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002146 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002147 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002148 if (deoptimize->GuardsAnInput()) {
2149 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2150 }
Aart Bikbb245d12015-10-19 11:05:03 -07002151 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2152 } else {
2153 // Always deopt.
2154 }
2155 }
2156}
2157
Anton Kirilove14dc862016-05-13 17:56:15 +01002158// Replace code looking like
2159// OP y, x, const1
2160// OP z, y, const2
2161// with
2162// OP z, x, const3
2163// where OP is both an associative and a commutative operation.
2164bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2165 HBinaryOperation* instruction) {
2166 DCHECK(instruction->IsCommutative());
2167
2168 if (!Primitive::IsIntegralType(instruction->GetType())) {
2169 return false;
2170 }
2171
2172 HInstruction* left = instruction->GetLeft();
2173 HInstruction* right = instruction->GetRight();
2174 // Variable names as described above.
2175 HConstant* const2;
2176 HBinaryOperation* y;
2177
2178 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2179 const2 = right->AsConstant();
2180 y = left->AsBinaryOperation();
2181 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2182 const2 = left->AsConstant();
2183 y = right->AsBinaryOperation();
2184 } else {
2185 // The node does not match the pattern.
2186 return false;
2187 }
2188
2189 // If `y` has more than one use, we do not perform the optimization
2190 // because it might increase code size (e.g. if the new constant is
2191 // no longer encodable as an immediate operand in the target ISA).
2192 if (!y->HasOnlyOneNonEnvironmentUse()) {
2193 return false;
2194 }
2195
2196 // GetConstantRight() can return both left and right constants
2197 // for commutative operations.
2198 HConstant* const1 = y->GetConstantRight();
2199 if (const1 == nullptr) {
2200 return false;
2201 }
2202
2203 instruction->ReplaceInput(const1, 0);
2204 instruction->ReplaceInput(const2, 1);
2205 HConstant* const3 = instruction->TryStaticEvaluation();
2206 DCHECK(const3 != nullptr);
2207 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2208 instruction->ReplaceInput(const3, 1);
2209 RecordSimplification();
2210 return true;
2211}
2212
2213static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2214 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2215}
2216
2217// Helper function that performs addition statically, considering the result type.
2218static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
2219 // Use the Compute() method for consistency with TryStaticEvaluation().
2220 if (type == Primitive::kPrimInt) {
2221 return HAdd::Compute<int32_t>(x, y);
2222 } else {
2223 DCHECK_EQ(type, Primitive::kPrimLong);
2224 return HAdd::Compute<int64_t>(x, y);
2225 }
2226}
2227
2228// Helper function that handles the child classes of HConstant
2229// and returns an integer with the appropriate sign.
2230static int64_t GetValue(HConstant* constant, bool is_negated) {
2231 int64_t ret = Int64FromConstant(constant);
2232 return is_negated ? -ret : ret;
2233}
2234
2235// Replace code looking like
2236// OP1 y, x, const1
2237// OP2 z, y, const2
2238// with
2239// OP3 z, x, const3
2240// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2241bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2242 HBinaryOperation* instruction) {
2243 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2244
2245 Primitive::Type type = instruction->GetType();
2246 if (!Primitive::IsIntegralType(type)) {
2247 return false;
2248 }
2249
2250 HInstruction* left = instruction->GetLeft();
2251 HInstruction* right = instruction->GetRight();
2252 // Variable names as described above.
2253 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2254 if (const2 == nullptr) {
2255 return false;
2256 }
2257
2258 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2259 ? left->AsBinaryOperation()
2260 : AsAddOrSub(right);
2261 // If y has more than one use, we do not perform the optimization because
2262 // it might increase code size (e.g. if the new constant is no longer
2263 // encodable as an immediate operand in the target ISA).
2264 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2265 return false;
2266 }
2267
2268 left = y->GetLeft();
2269 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2270 if (const1 == nullptr) {
2271 return false;
2272 }
2273
2274 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2275 // If both inputs are constants, let the constant folding pass deal with it.
2276 if (x->IsConstant()) {
2277 return false;
2278 }
2279
2280 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2281 int64_t const2_val = GetValue(const2, is_const2_negated);
2282 bool is_y_negated = (y == right) && instruction->IsSub();
2283 right = y->GetRight();
2284 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2285 int64_t const1_val = GetValue(const1, is_const1_negated);
2286 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2287 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2288 HBasicBlock* block = instruction->GetBlock();
2289 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2290 ArenaAllocator* arena = instruction->GetArena();
2291 HInstruction* z;
2292
2293 if (is_x_negated) {
2294 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2295 } else {
2296 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2297 }
2298
2299 block->ReplaceAndRemoveInstructionWith(instruction, z);
2300 RecordSimplification();
2301 return true;
2302}
2303
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002304} // namespace art