blob: f2a829fa56ba16bb3c98542fb41cbfb567128122 [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);
Lena Djokicbc5460b2017-07-20 16:07:36 +020062 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010063
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000064 void VisitShift(HBinaryOperation* shift);
65
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000066 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010067 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
68 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010069 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
70 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000071 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000072 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000073 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080074 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000075 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000076 void VisitAdd(HAdd* instruction) OVERRIDE;
77 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040078 void VisitCondition(HCondition* instruction) OVERRIDE;
79 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
80 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
81 void VisitLessThan(HLessThan* condition) OVERRIDE;
82 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060083 void VisitBelow(HBelow* condition) OVERRIDE;
84 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
85 void VisitAbove(HAbove* condition) OVERRIDE;
86 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000087 void VisitDiv(HDiv* instruction) OVERRIDE;
88 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010089 void VisitNeg(HNeg* instruction) OVERRIDE;
90 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000091 void VisitOr(HOr* instruction) OVERRIDE;
92 void VisitShl(HShl* instruction) OVERRIDE;
93 void VisitShr(HShr* instruction) OVERRIDE;
94 void VisitSub(HSub* instruction) OVERRIDE;
95 void VisitUShr(HUShr* instruction) OVERRIDE;
96 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000097 void VisitSelect(HSelect* select) OVERRIDE;
98 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010099 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100100 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700101 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200102 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100103
104 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000105
Roland Levillain22c49222016-03-18 14:04:28 +0000106 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100107 void SimplifySystemArrayCopy(HInvoke* invoke);
108 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000109 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800110 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800111 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100112 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100113 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800114 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800115 void SimplifyReturnThis(HInvoke* invoke);
116 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800117 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100118
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000119 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100120 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000121 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100122 bool simplification_occurred_ = false;
123 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700124 // We ensure we do not loop infinitely. The value should not be too high, since that
125 // would allow looping around the same basic block too many times. The value should
126 // not be too low either, however, since we want to allow revisiting a basic block
127 // with many statements and simplifications at least once.
128 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000129};
130
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100131void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100132 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100133 visitor.Run();
134}
135
136void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100137 // Iterate in reverse post order to open up more simplifications to users
138 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100139 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100140 // The simplification of an instruction to another instruction may yield
141 // possibilities for other simplifications. So although we perform a reverse
142 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100143 do {
144 simplification_occurred_ = false;
145 VisitBasicBlock(block);
146 } while (simplification_occurred_ &&
147 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100148 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100149 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100150}
151
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000152namespace {
153
154bool AreAllBitsSet(HConstant* constant) {
155 return Int64FromConstant(constant) == -1;
156}
157
158} // namespace
159
Alexandre Rames188d4312015-04-09 18:30:21 +0100160// Returns true if the code was simplified to use only one negation operation
161// after the binary operation instead of one on each of the inputs.
162bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
163 DCHECK(binop->IsAdd() || binop->IsSub());
164 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
165 HNeg* left_neg = binop->GetLeft()->AsNeg();
166 HNeg* right_neg = binop->GetRight()->AsNeg();
167 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
168 !right_neg->HasOnlyOneNonEnvironmentUse()) {
169 return false;
170 }
171 // Replace code looking like
172 // NEG tmp1, a
173 // NEG tmp2, b
174 // ADD dst, tmp1, tmp2
175 // with
176 // ADD tmp, a, b
177 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600178 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
179 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
180 // while the later yields `-0.0`.
181 if (!Primitive::IsIntegralType(binop->GetType())) {
182 return false;
183 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100184 binop->ReplaceInput(left_neg->GetInput(), 0);
185 binop->ReplaceInput(right_neg->GetInput(), 1);
186 left_neg->GetBlock()->RemoveInstruction(left_neg);
187 right_neg->GetBlock()->RemoveInstruction(right_neg);
188 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
189 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
190 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
191 RecordSimplification();
192 return true;
193}
194
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000195bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
196 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
197 Primitive::Type type = op->GetType();
198 HInstruction* left = op->GetLeft();
199 HInstruction* right = op->GetRight();
200
201 // We can apply De Morgan's laws if both inputs are Not's and are only used
202 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000203 if (((left->IsNot() && right->IsNot()) ||
204 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000205 left->HasOnlyOneNonEnvironmentUse() &&
206 right->HasOnlyOneNonEnvironmentUse()) {
207 // Replace code looking like
208 // NOT nota, a
209 // NOT notb, b
210 // AND dst, nota, notb (respectively OR)
211 // with
212 // OR or, a, b (respectively AND)
213 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000214 HInstruction* src_left = left->InputAt(0);
215 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000216 uint32_t dex_pc = op->GetDexPc();
217
218 // Remove the negations on the inputs.
219 left->ReplaceWith(src_left);
220 right->ReplaceWith(src_right);
221 left->GetBlock()->RemoveInstruction(left);
222 right->GetBlock()->RemoveInstruction(right);
223
224 // Replace the `HAnd` or `HOr`.
225 HBinaryOperation* hbin;
226 if (op->IsAnd()) {
227 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
228 } else {
229 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
230 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000231 HInstruction* hnot;
232 if (left->IsBooleanNot()) {
233 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
234 } else {
235 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
236 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000237
238 op->GetBlock()->InsertInstructionBefore(hbin, op);
239 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
240
241 RecordSimplification();
242 return true;
243 }
244
245 return false;
246}
247
Lena Djokicbc5460b2017-07-20 16:07:36 +0200248bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
249 Primitive::Type type = mul->GetPackedType();
250 InstructionSet isa = codegen_->GetInstructionSet();
251 switch (isa) {
252 case kArm64:
253 if (!(type == Primitive::kPrimByte ||
254 type == Primitive::kPrimChar ||
255 type == Primitive::kPrimShort ||
256 type == Primitive::kPrimInt)) {
257 return false;
258 }
259 break;
260 case kMips:
261 case kMips64:
262 if (!(type == Primitive::kPrimByte ||
263 type == Primitive::kPrimChar ||
264 type == Primitive::kPrimShort ||
265 type == Primitive::kPrimInt ||
266 type == Primitive::kPrimLong)) {
267 return false;
268 }
269 break;
270 default:
271 return false;
272 }
273
274 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetArena();
275
276 if (mul->HasOnlyOneNonEnvironmentUse()) {
277 HInstruction* use = mul->GetUses().front().GetUser();
278 if (use->IsVecAdd() || use->IsVecSub()) {
279 // Replace code looking like
280 // VECMUL tmp, x, y
281 // VECADD/SUB dst, acc, tmp
282 // with
283 // VECMULACC dst, acc, x, y
284 // Note that we do not want to (unconditionally) perform the merge when the
285 // multiplication has multiple uses and it can be merged in all of them.
286 // Multiple uses could happen on the same control-flow path, and we would
287 // then increase the amount of work. In the future we could try to evaluate
288 // whether all uses are on different control-flow paths (using dominance and
289 // reverse-dominance information) and only perform the merge when they are.
290 HInstruction* accumulator = nullptr;
291 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
292 HInstruction* binop_left = binop->GetLeft();
293 HInstruction* binop_right = binop->GetRight();
294 // This is always true since the `HVecMul` has only one use (which is checked above).
295 DCHECK_NE(binop_left, binop_right);
296 if (binop_right == mul) {
297 accumulator = binop_left;
298 } else if (use->IsVecAdd()) {
299 DCHECK_EQ(binop_left, mul);
300 accumulator = binop_right;
301 }
302
303 HInstruction::InstructionKind kind =
304 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
305 if (accumulator != nullptr) {
306 HVecMultiplyAccumulate* mulacc =
307 new (arena) HVecMultiplyAccumulate(arena,
308 kind,
309 accumulator,
310 mul->GetLeft(),
311 mul->GetRight(),
312 binop->GetPackedType(),
313 binop->GetVectorLength());
314
315 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
316 DCHECK(!mul->HasUses());
317 mul->GetBlock()->RemoveInstruction(mul);
318 return true;
319 }
320 }
321 }
322
323 return false;
324}
325
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000326void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
327 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100328 HInstruction* shift_amount = instruction->GetRight();
329 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000330
Alexandre Rames50518442016-06-27 11:39:19 +0100331 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
332 ? kMaxLongShiftDistance
333 : kMaxIntShiftDistance;
334
335 if (shift_amount->IsConstant()) {
336 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700337 int64_t masked_cst = cst & implicit_mask;
338 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400339 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100340 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400341 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100342 // value
343 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400344 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100345 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100346 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700347 } else if (masked_cst != cst) {
348 // Replace code looking like
349 // SHL dst, value, cst
350 // where cst exceeds maximum distance with the equivalent
351 // SHL dst, value, cst & implicit_mask
352 // (as defined by shift semantics). This ensures other
353 // optimizations do not need to special case for such situations.
354 DCHECK_EQ(shift_amount->GetType(), Primitive::kPrimInt);
355 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
356 RecordSimplification();
357 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100358 }
359 }
360
361 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
362 // unnecessary explicit masking operations on the shift amount.
363 // Replace code looking like
364 // AND masked_shift, shift, <superset of implicit mask>
365 // SHL dst, value, masked_shift
366 // with
367 // SHL dst, value, shift
368 if (shift_amount->IsAnd()) {
369 HAnd* and_insn = shift_amount->AsAnd();
370 HConstant* mask = and_insn->GetConstantRight();
371 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
372 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
373 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400374 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000375 }
376}
377
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000378static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
379 return (sub->GetRight() == other &&
380 sub->GetLeft()->IsConstant() &&
381 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
382}
383
384bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
385 HUShr* ushr,
386 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000387 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
388 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000389 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
390 if (!ushr->HasUses()) {
391 ushr->GetBlock()->RemoveInstruction(ushr);
392 }
393 if (!ushr->GetRight()->HasUses()) {
394 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
395 }
396 if (!shl->HasUses()) {
397 shl->GetBlock()->RemoveInstruction(shl);
398 }
399 if (!shl->GetRight()->HasUses()) {
400 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
401 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100402 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000403 return true;
404}
405
406// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
407bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000408 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
409 HInstruction* left = op->GetLeft();
410 HInstruction* right = op->GetRight();
411 // If we have an UShr and a Shl (in either order).
412 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
413 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
414 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
415 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
416 if (ushr->GetType() == shl->GetType() &&
417 ushr->GetLeft() == shl->GetLeft()) {
418 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
419 // Shift distances are both constant, try replacing with Ror if they
420 // add up to the register size.
421 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
422 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
423 // Shift distances are potentially of the form x and (reg_size - x).
424 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
425 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
426 // Shift distances are potentially of the form d and -d.
427 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
428 }
429 }
430 }
431 return false;
432}
433
434// Try replacing code looking like (x >>> #rdist OP x << #ldist):
435// UShr dst, x, #rdist
436// Shl tmp, x, #ldist
437// OP dst, dst, tmp
438// or like (x >>> #rdist OP x << #-ldist):
439// UShr dst, x, #rdist
440// Shl tmp, x, #-ldist
441// OP dst, dst, tmp
442// with
443// Ror dst, x, #rdist
444bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
445 HUShr* ushr,
446 HShl* shl) {
447 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
448 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
449 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
450 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
451 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
452 ReplaceRotateWithRor(op, ushr, shl);
453 return true;
454 }
455 return false;
456}
457
458// Replace code looking like (x >>> -d OP x << d):
459// Neg neg, d
460// UShr dst, x, neg
461// Shl tmp, x, d
462// OP dst, dst, tmp
463// with
464// Neg neg, d
465// Ror dst, x, neg
466// *** OR ***
467// Replace code looking like (x >>> d OP x << -d):
468// UShr dst, x, d
469// Neg neg, d
470// Shl tmp, x, neg
471// OP dst, dst, tmp
472// with
473// Ror dst, x, d
474bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
475 HUShr* ushr,
476 HShl* shl) {
477 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
478 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
479 bool neg_is_left = shl->GetRight()->IsNeg();
480 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
481 // And the shift distance being negated is the distance being shifted the other way.
482 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
483 ReplaceRotateWithRor(op, ushr, shl);
484 }
485 return false;
486}
487
488// Try replacing code looking like (x >>> d OP x << (#bits - d)):
489// UShr dst, x, d
490// Sub ld, #bits, d
491// Shl tmp, x, ld
492// OP dst, dst, tmp
493// with
494// Ror dst, x, d
495// *** OR ***
496// Replace code looking like (x >>> (#bits - d) OP x << d):
497// Sub rd, #bits, d
498// UShr dst, x, rd
499// Shl tmp, x, d
500// OP dst, dst, tmp
501// with
502// Neg neg, d
503// Ror dst, x, neg
504bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
505 HUShr* ushr,
506 HShl* shl) {
507 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
508 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
509 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
510 HInstruction* shl_shift = shl->GetRight();
511 HInstruction* ushr_shift = ushr->GetRight();
512 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
513 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
514 return ReplaceRotateWithRor(op, ushr, shl);
515 }
516 return false;
517}
518
Calin Juravle10e244f2015-01-26 18:54:32 +0000519void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
520 HInstruction* obj = null_check->InputAt(0);
521 if (!obj->CanBeNull()) {
522 null_check->ReplaceWith(obj);
523 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000524 if (stats_ != nullptr) {
525 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
526 }
527 }
528}
529
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100530bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
531 if (!input->CanBeNull()) {
532 return true;
533 }
534
Vladimir Marko46817b82016-03-29 12:21:58 +0100535 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
536 HInstruction* user = use.GetUser();
537 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100538 return true;
539 }
540 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100541
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100542 return false;
543}
544
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100545// Returns whether doing a type test between the class of `object` against `klass` has
546// a statically known outcome. The result of the test is stored in `outcome`.
547static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000548 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
549 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
550 ScopedObjectAccess soa(Thread::Current());
551 if (!obj_rti.IsValid()) {
552 // We run the simplifier before the reference type propagation so type info might not be
553 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100554 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000555 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100556
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100557 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100558 if (!class_rti.IsValid()) {
559 // Happens when the loaded class is unresolved.
560 return false;
561 }
562 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000563 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100564 *outcome = true;
565 return true;
566 } else if (obj_rti.IsExact()) {
567 // The test failed at compile time so will also fail at runtime.
568 *outcome = false;
569 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100570 } else if (!class_rti.IsInterface()
571 && !obj_rti.IsInterface()
572 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100573 // Different type hierarchy. The test will fail.
574 *outcome = false;
575 return true;
576 }
577 return false;
578}
579
580void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
581 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100582 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
583 if (load_class->NeedsAccessCheck()) {
584 // If we need to perform an access check we cannot remove the instruction.
585 return;
586 }
587
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100588 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100589 check_cast->ClearMustDoNullCheck();
590 }
591
592 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000593 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700594 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100595 return;
596 }
597
Vladimir Markoa65ed302016-03-14 21:21:29 +0000598 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
599 // the return value check with the `outcome` check, b/27651442 .
600 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700601 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100602 if (outcome) {
603 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700604 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700605 if (!load_class->HasUses()) {
606 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
607 // However, here we know that it cannot because the checkcast was successfull, hence
608 // the class was already loaded.
609 load_class->GetBlock()->RemoveInstruction(load_class);
610 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100611 } else {
612 // Don't do anything for exceptional cases for now. Ideally we should remove
613 // all instructions and blocks this instruction dominates.
614 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000615 }
616}
617
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100618void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100619 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100620 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
621 if (load_class->NeedsAccessCheck()) {
622 // If we need to perform an access check we cannot remove the instruction.
623 return;
624 }
625
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100626 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100627 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100628 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100629 instruction->ClearMustDoNullCheck();
630 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100631
632 HGraph* graph = GetGraph();
633 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700634 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100635 instruction->ReplaceWith(graph->GetIntConstant(0));
636 instruction->GetBlock()->RemoveInstruction(instruction);
637 RecordSimplification();
638 return;
639 }
640
Vladimir Marko24bd8952016-03-15 10:40:33 +0000641 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
642 // the return value check with the `outcome` check, b/27651442 .
643 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700644 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700645 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100646 if (outcome && can_be_null) {
647 // Type test will succeed, we just need a null test.
648 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
649 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
650 instruction->ReplaceWith(test);
651 } else {
652 // We've statically determined the result of the instanceof.
653 instruction->ReplaceWith(graph->GetIntConstant(outcome));
654 }
655 RecordSimplification();
656 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700657 if (outcome && !load_class->HasUses()) {
658 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
659 // However, here we know that it cannot because the instanceof check was successfull, hence
660 // the class was already loaded.
661 load_class->GetBlock()->RemoveInstruction(load_class);
662 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100663 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100664}
665
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100666void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
667 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100668 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100669 instruction->ClearValueCanBeNull();
670 }
671}
672
673void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
674 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100675 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100676 instruction->ClearValueCanBeNull();
677 }
678}
679
Anton Shaminbdd79352016-02-15 12:48:36 +0600680static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
681 HInstruction *lhs = cond->InputAt(0);
682 HInstruction *rhs = cond->InputAt(1);
683 switch (cond->GetKind()) {
684 case HInstruction::kEqual:
685 return new (arena) HEqual(rhs, lhs);
686 case HInstruction::kNotEqual:
687 return new (arena) HNotEqual(rhs, lhs);
688 case HInstruction::kLessThan:
689 return new (arena) HGreaterThan(rhs, lhs);
690 case HInstruction::kLessThanOrEqual:
691 return new (arena) HGreaterThanOrEqual(rhs, lhs);
692 case HInstruction::kGreaterThan:
693 return new (arena) HLessThan(rhs, lhs);
694 case HInstruction::kGreaterThanOrEqual:
695 return new (arena) HLessThanOrEqual(rhs, lhs);
696 case HInstruction::kBelow:
697 return new (arena) HAbove(rhs, lhs);
698 case HInstruction::kBelowOrEqual:
699 return new (arena) HAboveOrEqual(rhs, lhs);
700 case HInstruction::kAbove:
701 return new (arena) HBelow(rhs, lhs);
702 case HInstruction::kAboveOrEqual:
703 return new (arena) HBelowOrEqual(rhs, lhs);
704 default:
705 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
706 }
707 return nullptr;
708}
709
Aart Bik2767f4b2016-10-28 15:03:53 -0700710static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
711 if (input->GetType() == Primitive::kPrimBoolean) {
712 return true; // input has direct boolean type
713 } else if (cmp->GetUses().HasExactlyOneElement()) {
714 // Comparison also has boolean type if both its input and the instruction
715 // itself feed into the same phi node.
716 HInstruction* user = cmp->GetUses().front().GetUser();
717 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
718 }
719 return false;
720}
721
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000722void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100723 HInstruction* input_const = equal->GetConstantRight();
724 if (input_const != nullptr) {
725 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700726 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100727 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100728 // We are comparing the boolean to a constant which is of type int and can
729 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000730 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100731 // Replace (bool_value == true) with bool_value
732 equal->ReplaceWith(input_value);
733 block->RemoveInstruction(equal);
734 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000735 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700736 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500737 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
738 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100739 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100740 } else {
741 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
742 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
743 block->RemoveInstruction(equal);
744 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100745 }
Mark Mendellc4701932015-04-10 13:18:51 -0400746 } else {
747 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100748 }
Mark Mendellc4701932015-04-10 13:18:51 -0400749 } else {
750 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100751 }
752}
753
David Brazdil0d13fee2015-04-17 14:52:19 +0100754void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
755 HInstruction* input_const = not_equal->GetConstantRight();
756 if (input_const != nullptr) {
757 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700758 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100759 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100760 // We are comparing the boolean to a constant which is of type int and can
761 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000762 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700763 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500764 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
765 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100766 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000767 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100768 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100769 not_equal->ReplaceWith(input_value);
770 block->RemoveInstruction(not_equal);
771 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100772 } else {
773 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
774 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
775 block->RemoveInstruction(not_equal);
776 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100777 }
Mark Mendellc4701932015-04-10 13:18:51 -0400778 } else {
779 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100780 }
Mark Mendellc4701932015-04-10 13:18:51 -0400781 } else {
782 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100783 }
784}
785
786void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000787 HInstruction* input = bool_not->InputAt(0);
788 HInstruction* replace_with = nullptr;
789
790 if (input->IsIntConstant()) {
791 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000792 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000793 replace_with = GetGraph()->GetIntConstant(0);
794 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000795 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000796 replace_with = GetGraph()->GetIntConstant(1);
797 }
798 } else if (input->IsBooleanNot()) {
799 // Replace (!(!bool_value)) with bool_value.
800 replace_with = input->InputAt(0);
801 } else if (input->IsCondition() &&
802 // Don't change FP compares. The definition of compares involving
803 // NaNs forces the compares to be done as written by the user.
804 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
805 // Replace condition with its opposite.
806 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
807 }
808
809 if (replace_with != nullptr) {
810 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100811 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000812 RecordSimplification();
813 }
814}
815
816void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
817 HInstruction* replace_with = nullptr;
818 HInstruction* condition = select->GetCondition();
819 HInstruction* true_value = select->GetTrueValue();
820 HInstruction* false_value = select->GetFalseValue();
821
822 if (condition->IsBooleanNot()) {
823 // Change ((!cond) ? x : y) to (cond ? y : x).
824 condition = condition->InputAt(0);
825 std::swap(true_value, false_value);
826 select->ReplaceInput(false_value, 0);
827 select->ReplaceInput(true_value, 1);
828 select->ReplaceInput(condition, 2);
829 RecordSimplification();
830 }
831
832 if (true_value == false_value) {
833 // Replace (cond ? x : x) with (x).
834 replace_with = true_value;
835 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000836 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000837 // Replace (true ? x : y) with (x).
838 replace_with = true_value;
839 } else {
840 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000841 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000842 replace_with = false_value;
843 }
844 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000845 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000846 // Replace (cond ? true : false) with (cond).
847 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000848 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000849 // Replace (cond ? false : true) with (!cond).
850 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
851 }
852 }
853
854 if (replace_with != nullptr) {
855 select->ReplaceWith(replace_with);
856 select->GetBlock()->RemoveInstruction(select);
857 RecordSimplification();
858 }
859}
860
861void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
862 HInstruction* condition = instruction->InputAt(0);
863 if (condition->IsBooleanNot()) {
864 // Swap successors if input is negated.
865 instruction->ReplaceInput(condition->InputAt(0), 0);
866 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100867 RecordSimplification();
868 }
869}
870
Mingyao Yang0304e182015-01-30 16:41:29 -0800871void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
872 HInstruction* input = instruction->InputAt(0);
873 // If the array is a NewArray with constant size, replace the array length
874 // with the constant instruction. This helps the bounds check elimination phase.
875 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000876 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800877 if (input->IsIntConstant()) {
878 instruction->ReplaceWith(input);
879 }
880 }
881}
882
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000883void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000884 HInstruction* value = instruction->GetValue();
885 if (value->GetType() != Primitive::kPrimNot) return;
886
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100887 if (CanEnsureNotNullAt(value, instruction)) {
888 instruction->ClearValueCanBeNull();
889 }
890
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000891 if (value->IsArrayGet()) {
892 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
893 // If the code is just swapping elements in the array, no need for a type check.
894 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100895 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000896 }
897 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100898
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100899 if (value->IsNullConstant()) {
900 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100901 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100902 }
903
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100904 ScopedObjectAccess soa(Thread::Current());
905 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
906 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
907 if (!array_rti.IsValid()) {
908 return;
909 }
910
911 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
912 instruction->ClearNeedsTypeCheck();
913 return;
914 }
915
916 if (array_rti.IsObjectArray()) {
917 if (array_rti.IsExact()) {
918 instruction->ClearNeedsTypeCheck();
919 return;
920 }
921 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100922 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000923}
924
Vladimir Markob52bbde2016-02-12 12:06:05 +0000925static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100926 // Invariant: We should never generate a conversion to a Boolean value.
927 DCHECK_NE(Primitive::kPrimBoolean, result_type);
928
Vladimir Markob52bbde2016-02-12 12:06:05 +0000929 // Besides conversion to the same type, widening integral conversions are implicit,
930 // excluding conversions to long and the byte->char conversion where we need to
931 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
932 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100933 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
934 input_type == Primitive::kPrimByte ||
935 input_type == Primitive::kPrimShort ||
936 input_type == Primitive::kPrimChar)) ||
937 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
938 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
939 input_type == Primitive::kPrimByte)) ||
940 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000941}
942
943static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
944 // The conversion to a larger type is loss-less with the exception of two cases,
945 // - conversion to char, the only unsigned type, where we may lose some bits, and
946 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
947 // For integral to FP conversions this holds because the FP mantissa is large enough.
948 DCHECK_NE(input_type, result_type);
949 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
950 result_type != Primitive::kPrimChar &&
951 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
952}
953
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000954void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000955 HInstruction* input = instruction->GetInput();
956 Primitive::Type input_type = input->GetType();
957 Primitive::Type result_type = instruction->GetResultType();
958 if (IsTypeConversionImplicit(input_type, result_type)) {
959 // Remove the implicit conversion; this includes conversion to the same type.
960 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000961 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000962 RecordSimplification();
963 return;
964 }
965
966 if (input->IsTypeConversion()) {
967 HTypeConversion* input_conversion = input->AsTypeConversion();
968 HInstruction* original_input = input_conversion->GetInput();
969 Primitive::Type original_type = original_input->GetType();
970
971 // When the first conversion is lossless, a direct conversion from the original type
972 // to the final type yields the same result, even for a lossy second conversion, for
973 // example float->double->int or int->double->float.
974 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
975
976 // For integral conversions, see if the first conversion loses only bits that the second
977 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
978 // conversion yields the same result, for example long->int->short or int->char->short.
979 bool integral_conversions_with_non_widening_second =
980 Primitive::IsIntegralType(input_type) &&
981 Primitive::IsIntegralType(original_type) &&
982 Primitive::IsIntegralType(result_type) &&
983 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
984
985 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
986 // If the merged conversion is implicit, do the simplification unconditionally.
987 if (IsTypeConversionImplicit(original_type, result_type)) {
988 instruction->ReplaceWith(original_input);
989 instruction->GetBlock()->RemoveInstruction(instruction);
990 if (!input_conversion->HasUses()) {
991 // Don't wait for DCE.
992 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
993 }
994 RecordSimplification();
995 return;
996 }
997 // Otherwise simplify only if the first conversion has no other use.
998 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
999 input_conversion->ReplaceWith(original_input);
1000 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1001 RecordSimplification();
1002 return;
1003 }
1004 }
Vladimir Marko625090f2016-03-14 18:00:05 +00001005 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001006 DCHECK(Primitive::IsIntegralType(input_type));
1007 HAnd* input_and = input->AsAnd();
1008 HConstant* constant = input_and->GetConstantRight();
1009 if (constant != nullptr) {
1010 int64_t value = Int64FromConstant(constant);
1011 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1012 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
1013 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
1014 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001015 HInstruction* original_input = input_and->GetLeastConstantLeft();
1016 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
1017 instruction->ReplaceWith(original_input);
1018 instruction->GetBlock()->RemoveInstruction(instruction);
1019 RecordSimplification();
1020 return;
1021 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1022 input_and->ReplaceWith(original_input);
1023 input_and->GetBlock()->RemoveInstruction(input_and);
1024 RecordSimplification();
1025 return;
1026 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001027 }
1028 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001029 }
1030}
1031
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001032void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1033 HConstant* input_cst = instruction->GetConstantRight();
1034 HInstruction* input_other = instruction->GetLeastConstantLeft();
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001035 bool integral_type = Primitive::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001036 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001037 // Replace code looking like
1038 // ADD dst, src, 0
1039 // with
1040 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001041 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1042 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1043 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001044 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001045 instruction->ReplaceWith(input_other);
1046 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001047 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001048 return;
1049 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001050 }
1051
1052 HInstruction* left = instruction->GetLeft();
1053 HInstruction* right = instruction->GetRight();
1054 bool left_is_neg = left->IsNeg();
1055 bool right_is_neg = right->IsNeg();
1056
1057 if (left_is_neg && right_is_neg) {
1058 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1059 return;
1060 }
1061 }
1062
1063 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1064 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1065 // Replace code looking like
1066 // NEG tmp, b
1067 // ADD dst, a, tmp
1068 // with
1069 // SUB dst, a, b
1070 // We do not perform the optimization if the input negation has environment
1071 // uses or multiple non-environment uses as it could lead to worse code. In
1072 // particular, we do not want the live range of `b` to be extended if we are
1073 // not sure the initial 'NEG' instruction can be removed.
1074 HInstruction* other = left_is_neg ? right : left;
1075 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
1076 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1077 RecordSimplification();
1078 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001079 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001080 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001081
Anton Kirilove14dc862016-05-13 17:56:15 +01001082 if (TryReplaceWithRotate(instruction)) {
1083 return;
1084 }
1085
1086 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1087 // so no need to return.
1088 TryHandleAssociativeAndCommutativeOperation(instruction);
1089
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001090 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001091 TrySubtractionChainSimplification(instruction)) {
1092 return;
1093 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001094
1095 if (integral_type) {
1096 // Replace code patterns looking like
1097 // SUB dst1, x, y SUB dst1, x, y
1098 // ADD dst2, dst1, y ADD dst2, y, dst1
1099 // with
1100 // SUB dst1, x, y
1101 // ADD instruction is not needed in this case, we may use
1102 // one of inputs of SUB instead.
1103 if (left->IsSub() && left->InputAt(1) == right) {
1104 instruction->ReplaceWith(left->InputAt(0));
1105 RecordSimplification();
1106 instruction->GetBlock()->RemoveInstruction(instruction);
1107 return;
1108 } else if (right->IsSub() && right->InputAt(1) == left) {
1109 instruction->ReplaceWith(right->InputAt(0));
1110 RecordSimplification();
1111 instruction->GetBlock()->RemoveInstruction(instruction);
1112 return;
1113 }
1114 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001115}
1116
1117void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1118 HConstant* input_cst = instruction->GetConstantRight();
1119 HInstruction* input_other = instruction->GetLeastConstantLeft();
1120
Vladimir Marko452c1b62015-09-25 14:44:17 +01001121 if (input_cst != nullptr) {
1122 int64_t value = Int64FromConstant(input_cst);
1123 if (value == -1) {
1124 // Replace code looking like
1125 // AND dst, src, 0xFFF...FF
1126 // with
1127 // src
1128 instruction->ReplaceWith(input_other);
1129 instruction->GetBlock()->RemoveInstruction(instruction);
1130 RecordSimplification();
1131 return;
1132 }
1133 // Eliminate And from UShr+And if the And-mask contains all the bits that
1134 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1135 // precisely clears the shifted-in sign bits.
1136 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1137 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1138 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1139 size_t num_tail_bits_set = CTZ(value + 1);
1140 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1141 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1142 instruction->ReplaceWith(input_other);
1143 instruction->GetBlock()->RemoveInstruction(instruction);
1144 RecordSimplification();
1145 return;
1146 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1147 input_other->HasOnlyOneNonEnvironmentUse()) {
1148 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1149 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1150 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1151 input_other->InputAt(0),
1152 input_other->InputAt(1),
1153 input_other->GetDexPc());
1154 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1155 input_other->GetBlock()->RemoveInstruction(input_other);
1156 RecordSimplification();
1157 return;
1158 }
1159 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001160 }
1161
1162 // We assume that GVN has run before, so we only perform a pointer comparison.
1163 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001164 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001165 if (instruction->GetLeft() == instruction->GetRight()) {
1166 // Replace code looking like
1167 // AND dst, src, src
1168 // with
1169 // src
1170 instruction->ReplaceWith(instruction->GetLeft());
1171 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001172 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001173 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001174 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001175
Anton Kirilove14dc862016-05-13 17:56:15 +01001176 if (TryDeMorganNegationFactoring(instruction)) {
1177 return;
1178 }
1179
1180 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1181 // so no need to return.
1182 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001183}
1184
Mark Mendellc4701932015-04-10 13:18:51 -04001185void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1186 VisitCondition(condition);
1187}
1188
1189void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1190 VisitCondition(condition);
1191}
1192
1193void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1194 VisitCondition(condition);
1195}
1196
1197void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1198 VisitCondition(condition);
1199}
1200
Anton Shaminbdd79352016-02-15 12:48:36 +06001201void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1202 VisitCondition(condition);
1203}
1204
1205void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1206 VisitCondition(condition);
1207}
1208
1209void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1210 VisitCondition(condition);
1211}
1212
1213void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1214 VisitCondition(condition);
1215}
Aart Bike9f37602015-10-09 11:15:55 -07001216
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001217// Recognize the following pattern:
1218// obj.getClass() ==/!= Foo.class
1219// And replace it with a constant value if the type of `obj` is statically known.
1220static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1221 HInstruction* input_one = condition->InputAt(0);
1222 HInstruction* input_two = condition->InputAt(1);
1223 HLoadClass* load_class = input_one->IsLoadClass()
1224 ? input_one->AsLoadClass()
1225 : input_two->AsLoadClass();
1226 if (load_class == nullptr) {
1227 return false;
1228 }
1229
1230 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1231 if (!class_rti.IsValid()) {
1232 // Unresolved class.
1233 return false;
1234 }
1235
1236 HInstanceFieldGet* field_get = (load_class == input_one)
1237 ? input_two->AsInstanceFieldGet()
1238 : input_one->AsInstanceFieldGet();
1239 if (field_get == nullptr) {
1240 return false;
1241 }
1242
1243 HInstruction* receiver = field_get->InputAt(0);
1244 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1245 if (!receiver_type.IsExact()) {
1246 return false;
1247 }
1248
1249 {
1250 ScopedObjectAccess soa(Thread::Current());
1251 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1252 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1253 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1254 if (field_get->GetFieldInfo().GetField() != field) {
1255 return false;
1256 }
1257
1258 // We can replace the compare.
1259 int value = 0;
1260 if (receiver_type.IsEqual(class_rti)) {
1261 value = condition->IsEqual() ? 1 : 0;
1262 } else {
1263 value = condition->IsNotEqual() ? 1 : 0;
1264 }
1265 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1266 return true;
1267 }
1268}
1269
Mark Mendellc4701932015-04-10 13:18:51 -04001270void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001271 if (condition->IsEqual() || condition->IsNotEqual()) {
1272 if (RecognizeAndSimplifyClassCheck(condition)) {
1273 return;
1274 }
1275 }
1276
Anton Shaminbdd79352016-02-15 12:48:36 +06001277 // Reverse condition if left is constant. Our code generators prefer constant
1278 // on the right hand side.
1279 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1280 HBasicBlock* block = condition->GetBlock();
1281 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1282 // If it is a fp we must set the opposite bias.
1283 if (replacement != nullptr) {
1284 if (condition->IsLtBias()) {
1285 replacement->SetBias(ComparisonBias::kGtBias);
1286 } else if (condition->IsGtBias()) {
1287 replacement->SetBias(ComparisonBias::kLtBias);
1288 }
1289 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1290 RecordSimplification();
1291
1292 condition = replacement;
1293 }
1294 }
Mark Mendellc4701932015-04-10 13:18:51 -04001295
Mark Mendellc4701932015-04-10 13:18:51 -04001296 HInstruction* left = condition->GetLeft();
1297 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001298
1299 // Try to fold an HCompare into this HCondition.
1300
Mark Mendellc4701932015-04-10 13:18:51 -04001301 // We can only replace an HCondition which compares a Compare to 0.
1302 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1303 // condition with a long, float or double comparison as input.
1304 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1305 // Conversion is not possible.
1306 return;
1307 }
1308
1309 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001310 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001311 // Someone else also wants the result of the compare.
1312 return;
1313 }
1314
Vladimir Marko46817b82016-03-29 12:21:58 +01001315 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001316 // There is a reference to the compare result in an environment. Do we really need it?
1317 if (GetGraph()->IsDebuggable()) {
1318 return;
1319 }
1320
1321 // We have to ensure that there are no deopt points in the sequence.
1322 if (left->HasAnyEnvironmentUseBefore(condition)) {
1323 return;
1324 }
1325 }
1326
1327 // Clean up any environment uses from the HCompare, if any.
1328 left->RemoveEnvironmentUsers();
1329
1330 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1331 condition->SetBias(left->AsCompare()->GetBias());
1332
1333 // Replace the operands of the HCondition.
1334 condition->ReplaceInput(left->InputAt(0), 0);
1335 condition->ReplaceInput(left->InputAt(1), 1);
1336
1337 // Remove the HCompare.
1338 left->GetBlock()->RemoveInstruction(left);
1339
1340 RecordSimplification();
1341}
1342
Andreas Gampe9186ced2016-12-12 14:28:21 -08001343// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1344static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1345 // True, if the most significant bits of divisor are 0.
1346 return ((divisor & 0x7fffff) == 0);
1347}
1348
1349// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1350static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1351 // True, if the most significant bits of divisor are 0.
1352 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1353}
1354
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001355void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1356 HConstant* input_cst = instruction->GetConstantRight();
1357 HInstruction* input_other = instruction->GetLeastConstantLeft();
1358 Primitive::Type type = instruction->GetType();
1359
1360 if ((input_cst != nullptr) && input_cst->IsOne()) {
1361 // Replace code looking like
1362 // DIV dst, src, 1
1363 // with
1364 // src
1365 instruction->ReplaceWith(input_other);
1366 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001367 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001368 return;
1369 }
1370
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001371 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001372 // Replace code looking like
1373 // DIV dst, src, -1
1374 // with
1375 // NEG dst, src
1376 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001377 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001378 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001379 return;
1380 }
1381
1382 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1383 // Try replacing code looking like
1384 // DIV dst, src, constant
1385 // with
1386 // MUL dst, src, 1 / constant
1387 HConstant* reciprocal = nullptr;
1388 if (type == Primitive::Primitive::kPrimDouble) {
1389 double value = input_cst->AsDoubleConstant()->GetValue();
1390 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1391 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1392 }
1393 } else {
1394 DCHECK_EQ(type, Primitive::kPrimFloat);
1395 float value = input_cst->AsFloatConstant()->GetValue();
1396 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1397 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1398 }
1399 }
1400
1401 if (reciprocal != nullptr) {
1402 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1403 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1404 RecordSimplification();
1405 return;
1406 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001407 }
1408}
1409
1410void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1411 HConstant* input_cst = instruction->GetConstantRight();
1412 HInstruction* input_other = instruction->GetLeastConstantLeft();
1413 Primitive::Type type = instruction->GetType();
1414 HBasicBlock* block = instruction->GetBlock();
1415 ArenaAllocator* allocator = GetGraph()->GetArena();
1416
1417 if (input_cst == nullptr) {
1418 return;
1419 }
1420
1421 if (input_cst->IsOne()) {
1422 // Replace code looking like
1423 // MUL dst, src, 1
1424 // with
1425 // src
1426 instruction->ReplaceWith(input_other);
1427 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001428 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001429 return;
1430 }
1431
1432 if (input_cst->IsMinusOne() &&
1433 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1434 // Replace code looking like
1435 // MUL dst, src, -1
1436 // with
1437 // NEG dst, src
1438 HNeg* neg = new (allocator) HNeg(type, input_other);
1439 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001440 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001441 return;
1442 }
1443
1444 if (Primitive::IsFloatingPointType(type) &&
1445 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1446 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1447 // Replace code looking like
1448 // FP_MUL dst, src, 2.0
1449 // with
1450 // FP_ADD dst, src, src
1451 // The 'int' and 'long' cases are handled below.
1452 block->ReplaceAndRemoveInstructionWith(instruction,
1453 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001454 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001455 return;
1456 }
1457
1458 if (Primitive::IsIntOrLongType(type)) {
1459 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001460 // Even though constant propagation also takes care of the zero case, other
1461 // optimizations can lead to having a zero multiplication.
1462 if (factor == 0) {
1463 // Replace code looking like
1464 // MUL dst, src, 0
1465 // with
1466 // 0
1467 instruction->ReplaceWith(input_cst);
1468 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001469 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001470 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001471 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001472 // Replace code looking like
1473 // MUL dst, src, pow_of_2
1474 // with
1475 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001476 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001477 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001478 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001479 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001480 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001481 } else if (IsPowerOfTwo(factor - 1)) {
1482 // Transform code looking like
1483 // MUL dst, src, (2^n + 1)
1484 // into
1485 // SHL tmp, src, n
1486 // ADD dst, src, tmp
1487 HShl* shl = new (allocator) HShl(type,
1488 input_other,
1489 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1490 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1491
1492 block->InsertInstructionBefore(shl, instruction);
1493 block->ReplaceAndRemoveInstructionWith(instruction, add);
1494 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001495 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001496 } else if (IsPowerOfTwo(factor + 1)) {
1497 // Transform code looking like
1498 // MUL dst, src, (2^n - 1)
1499 // into
1500 // SHL tmp, src, n
1501 // SUB dst, tmp, src
1502 HShl* shl = new (allocator) HShl(type,
1503 input_other,
1504 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1505 HSub* sub = new (allocator) HSub(type, shl, input_other);
1506
1507 block->InsertInstructionBefore(shl, instruction);
1508 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1509 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001510 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001511 }
1512 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001513
1514 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1515 // so no need to return.
1516 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001517}
1518
Alexandre Rames188d4312015-04-09 18:30:21 +01001519void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1520 HInstruction* input = instruction->GetInput();
1521 if (input->IsNeg()) {
1522 // Replace code looking like
1523 // NEG tmp, src
1524 // NEG dst, tmp
1525 // with
1526 // src
1527 HNeg* previous_neg = input->AsNeg();
1528 instruction->ReplaceWith(previous_neg->GetInput());
1529 instruction->GetBlock()->RemoveInstruction(instruction);
1530 // We perform the optimization even if the input negation has environment
1531 // uses since it allows removing the current instruction. But we only delete
1532 // the input negation only if it is does not have any uses left.
1533 if (!previous_neg->HasUses()) {
1534 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1535 }
1536 RecordSimplification();
1537 return;
1538 }
1539
Serguei Katkov339dfc22015-04-20 12:29:32 +06001540 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1541 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001542 // Replace code looking like
1543 // SUB tmp, a, b
1544 // NEG dst, tmp
1545 // with
1546 // SUB dst, b, a
1547 // We do not perform the optimization if the input subtraction has
1548 // environment uses or multiple non-environment uses as it could lead to
1549 // worse code. In particular, we do not want the live ranges of `a` and `b`
1550 // to be extended if we are not sure the initial 'SUB' instruction can be
1551 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001552 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001553 HSub* sub = input->AsSub();
1554 HSub* new_sub =
1555 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1556 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1557 if (!sub->HasUses()) {
1558 sub->GetBlock()->RemoveInstruction(sub);
1559 }
1560 RecordSimplification();
1561 }
1562}
1563
1564void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1565 HInstruction* input = instruction->GetInput();
1566 if (input->IsNot()) {
1567 // Replace code looking like
1568 // NOT tmp, src
1569 // NOT dst, tmp
1570 // with
1571 // src
1572 // We perform the optimization even if the input negation has environment
1573 // uses since it allows removing the current instruction. But we only delete
1574 // the input negation only if it is does not have any uses left.
1575 HNot* previous_not = input->AsNot();
1576 instruction->ReplaceWith(previous_not->GetInput());
1577 instruction->GetBlock()->RemoveInstruction(instruction);
1578 if (!previous_not->HasUses()) {
1579 previous_not->GetBlock()->RemoveInstruction(previous_not);
1580 }
1581 RecordSimplification();
1582 }
1583}
1584
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001585void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1586 HConstant* input_cst = instruction->GetConstantRight();
1587 HInstruction* input_other = instruction->GetLeastConstantLeft();
1588
Roland Levillain1a653882016-03-18 18:05:57 +00001589 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001590 // Replace code looking like
1591 // OR dst, src, 0
1592 // with
1593 // src
1594 instruction->ReplaceWith(input_other);
1595 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001596 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001597 return;
1598 }
1599
1600 // We assume that GVN has run before, so we only perform a pointer comparison.
1601 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001602 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001603 if (instruction->GetLeft() == instruction->GetRight()) {
1604 // Replace code looking like
1605 // OR dst, src, src
1606 // with
1607 // src
1608 instruction->ReplaceWith(instruction->GetLeft());
1609 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001610 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001611 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001612 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001613
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001614 if (TryDeMorganNegationFactoring(instruction)) return;
1615
Anton Kirilove14dc862016-05-13 17:56:15 +01001616 if (TryReplaceWithRotate(instruction)) {
1617 return;
1618 }
1619
1620 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1621 // so no need to return.
1622 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001623}
1624
1625void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1626 VisitShift(instruction);
1627}
1628
1629void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1630 VisitShift(instruction);
1631}
1632
1633void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1634 HConstant* input_cst = instruction->GetConstantRight();
1635 HInstruction* input_other = instruction->GetLeastConstantLeft();
1636
Serguei Katkov115b53f2015-08-05 17:03:30 +06001637 Primitive::Type type = instruction->GetType();
1638 if (Primitive::IsFloatingPointType(type)) {
1639 return;
1640 }
1641
Roland Levillain1a653882016-03-18 18:05:57 +00001642 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001643 // Replace code looking like
1644 // SUB dst, src, 0
1645 // with
1646 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001647 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1648 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1649 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001650 instruction->ReplaceWith(input_other);
1651 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001652 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001653 return;
1654 }
1655
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001656 HBasicBlock* block = instruction->GetBlock();
1657 ArenaAllocator* allocator = GetGraph()->GetArena();
1658
Alexandre Rames188d4312015-04-09 18:30:21 +01001659 HInstruction* left = instruction->GetLeft();
1660 HInstruction* right = instruction->GetRight();
1661 if (left->IsConstant()) {
1662 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001663 // Replace code looking like
1664 // SUB dst, 0, src
1665 // with
1666 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001667 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001668 // `x` is `0.0`, the former expression yields `0.0`, while the later
1669 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001670 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001671 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001672 RecordSimplification();
1673 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001674 }
1675 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001676
1677 if (left->IsNeg() && right->IsNeg()) {
1678 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1679 return;
1680 }
1681 }
1682
1683 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1684 // Replace code looking like
1685 // NEG tmp, b
1686 // SUB dst, a, tmp
1687 // with
1688 // ADD dst, a, b
1689 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1690 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1691 RecordSimplification();
1692 right->GetBlock()->RemoveInstruction(right);
1693 return;
1694 }
1695
1696 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1697 // Replace code looking like
1698 // NEG tmp, a
1699 // SUB dst, tmp, b
1700 // with
1701 // ADD tmp, a, b
1702 // NEG dst, tmp
1703 // The second version is not intrinsically better, but enables more
1704 // transformations.
1705 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1706 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1707 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1708 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1709 instruction->ReplaceWith(neg);
1710 instruction->GetBlock()->RemoveInstruction(instruction);
1711 RecordSimplification();
1712 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001713 return;
1714 }
1715
1716 if (TrySubtractionChainSimplification(instruction)) {
1717 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001718 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001719
1720 if (left->IsAdd()) {
1721 // Replace code patterns looking like
1722 // ADD dst1, x, y ADD dst1, x, y
1723 // SUB dst2, dst1, y SUB dst2, dst1, x
1724 // with
1725 // ADD dst1, x, y
1726 // SUB instruction is not needed in this case, we may use
1727 // one of inputs of ADD instead.
1728 // It is applicable to integral types only.
1729 DCHECK(Primitive::IsIntegralType(type));
1730 if (left->InputAt(1) == right) {
1731 instruction->ReplaceWith(left->InputAt(0));
1732 RecordSimplification();
1733 instruction->GetBlock()->RemoveInstruction(instruction);
1734 return;
1735 } else if (left->InputAt(0) == right) {
1736 instruction->ReplaceWith(left->InputAt(1));
1737 RecordSimplification();
1738 instruction->GetBlock()->RemoveInstruction(instruction);
1739 return;
1740 }
1741 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001742}
1743
1744void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1745 VisitShift(instruction);
1746}
1747
1748void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1749 HConstant* input_cst = instruction->GetConstantRight();
1750 HInstruction* input_other = instruction->GetLeastConstantLeft();
1751
Roland Levillain1a653882016-03-18 18:05:57 +00001752 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001753 // Replace code looking like
1754 // XOR dst, src, 0
1755 // with
1756 // src
1757 instruction->ReplaceWith(input_other);
1758 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001759 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001760 return;
1761 }
1762
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001763 if ((input_cst != nullptr) && input_cst->IsOne()
1764 && input_other->GetType() == Primitive::kPrimBoolean) {
1765 // Replace code looking like
1766 // XOR dst, src, 1
1767 // with
1768 // BOOLEAN_NOT dst, src
1769 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1770 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1771 RecordSimplification();
1772 return;
1773 }
1774
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001775 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1776 // Replace code looking like
1777 // XOR dst, src, 0xFFF...FF
1778 // with
1779 // NOT dst, src
1780 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1781 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001782 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001783 return;
1784 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001785
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001786 HInstruction* left = instruction->GetLeft();
1787 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001788 if (((left->IsNot() && right->IsNot()) ||
1789 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001790 left->HasOnlyOneNonEnvironmentUse() &&
1791 right->HasOnlyOneNonEnvironmentUse()) {
1792 // Replace code looking like
1793 // NOT nota, a
1794 // NOT notb, b
1795 // XOR dst, nota, notb
1796 // with
1797 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001798 instruction->ReplaceInput(left->InputAt(0), 0);
1799 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001800 left->GetBlock()->RemoveInstruction(left);
1801 right->GetBlock()->RemoveInstruction(right);
1802 RecordSimplification();
1803 return;
1804 }
1805
Anton Kirilove14dc862016-05-13 17:56:15 +01001806 if (TryReplaceWithRotate(instruction)) {
1807 return;
1808 }
1809
1810 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1811 // so no need to return.
1812 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001813}
1814
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001815void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1816 HInstruction* argument = instruction->InputAt(1);
1817 HInstruction* receiver = instruction->InputAt(0);
1818 if (receiver == argument) {
1819 // Because String.equals is an instance call, the receiver is
1820 // a null check if we don't know it's null. The argument however, will
1821 // be the actual object. So we cannot end up in a situation where both
1822 // are equal but could be null.
1823 DCHECK(CanEnsureNotNullAt(argument, instruction));
1824 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1825 instruction->GetBlock()->RemoveInstruction(instruction);
1826 } else {
1827 StringEqualsOptimizations optimizations(instruction);
1828 if (CanEnsureNotNullAt(argument, instruction)) {
1829 optimizations.SetArgumentNotNull();
1830 }
1831 ScopedObjectAccess soa(Thread::Current());
1832 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1833 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1834 optimizations.SetArgumentIsString();
1835 }
1836 }
1837}
1838
Roland Levillain22c49222016-03-18 14:04:28 +00001839void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1840 bool is_left,
1841 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001842 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001843 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001844 HInstruction* value = invoke->InputAt(0);
1845 HInstruction* distance = invoke->InputAt(1);
1846 // Replace the invoke with an HRor.
1847 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001848 // Unconditionally set the type of the negated distance to `int`,
1849 // as shift and rotate operations expect a 32-bit (or narrower)
1850 // value for their distance input.
1851 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001852 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1853 }
Roland Levillain22c49222016-03-18 14:04:28 +00001854 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001855 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1856 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001857 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001858 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1859 clinit->GetBlock()->RemoveInstruction(clinit);
1860 HInstruction* ldclass = clinit->InputAt(0);
1861 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1862 ldclass->GetBlock()->RemoveInstruction(ldclass);
1863 }
1864 }
1865}
1866
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001867static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1868 if (potential_length->IsArrayLength()) {
1869 return potential_length->InputAt(0) == potential_array;
1870 }
1871
1872 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001873 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001874 }
1875
1876 return false;
1877}
1878
1879void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1880 HInstruction* source = instruction->InputAt(0);
1881 HInstruction* destination = instruction->InputAt(2);
1882 HInstruction* count = instruction->InputAt(4);
1883 SystemArrayCopyOptimizations optimizations(instruction);
1884 if (CanEnsureNotNullAt(source, instruction)) {
1885 optimizations.SetSourceIsNotNull();
1886 }
1887 if (CanEnsureNotNullAt(destination, instruction)) {
1888 optimizations.SetDestinationIsNotNull();
1889 }
1890 if (destination == source) {
1891 optimizations.SetDestinationIsSource();
1892 }
1893
1894 if (IsArrayLengthOf(count, source)) {
1895 optimizations.SetCountIsSourceLength();
1896 }
1897
1898 if (IsArrayLengthOf(count, destination)) {
1899 optimizations.SetCountIsDestinationLength();
1900 }
1901
1902 {
1903 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001904 Primitive::Type source_component_type = Primitive::kPrimVoid;
1905 Primitive::Type destination_component_type = Primitive::kPrimVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001906 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1907 if (destination_rti.IsValid()) {
1908 if (destination_rti.IsObjectArray()) {
1909 if (destination_rti.IsExact()) {
1910 optimizations.SetDoesNotNeedTypeCheck();
1911 }
1912 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001913 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001914 if (destination_rti.IsPrimitiveArrayClass()) {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001915 destination_component_type =
1916 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001917 optimizations.SetDestinationIsPrimitiveArray();
1918 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1919 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001920 }
1921 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001922 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1923 if (source_rti.IsValid()) {
1924 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1925 optimizations.SetDoesNotNeedTypeCheck();
1926 }
1927 if (source_rti.IsPrimitiveArrayClass()) {
1928 optimizations.SetSourceIsPrimitiveArray();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001929 source_component_type = source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType();
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001930 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1931 optimizations.SetSourceIsNonPrimitiveArray();
1932 }
1933 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001934 // For primitive arrays, use their optimized ArtMethod implementations.
1935 if ((source_component_type != Primitive::kPrimVoid) &&
1936 (source_component_type == destination_component_type)) {
1937 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1938 PointerSize image_size = class_linker->GetImagePointerSize();
1939 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1940 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
1941 ArtMethod* method = nullptr;
1942 switch (source_component_type) {
1943 case Primitive::kPrimBoolean:
Vladimir Markoba118822017-06-12 15:41:56 +01001944 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001945 break;
1946 case Primitive::kPrimByte:
Vladimir Markoba118822017-06-12 15:41:56 +01001947 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001948 break;
1949 case Primitive::kPrimChar:
Vladimir Markoba118822017-06-12 15:41:56 +01001950 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001951 break;
1952 case Primitive::kPrimShort:
Vladimir Markoba118822017-06-12 15:41:56 +01001953 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001954 break;
1955 case Primitive::kPrimInt:
Vladimir Markoba118822017-06-12 15:41:56 +01001956 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001957 break;
1958 case Primitive::kPrimFloat:
Vladimir Markoba118822017-06-12 15:41:56 +01001959 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001960 break;
1961 case Primitive::kPrimLong:
Vladimir Markoba118822017-06-12 15:41:56 +01001962 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001963 break;
1964 case Primitive::kPrimDouble:
Vladimir Markoba118822017-06-12 15:41:56 +01001965 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001966 break;
1967 default:
1968 LOG(FATAL) << "Unreachable";
1969 }
1970 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001971 DCHECK(method->IsStatic());
1972 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001973 invoke->SetResolvedMethod(method);
1974 // Sharpen the new invoke. Note that we do not update the dex method index of
1975 // the invoke, as we would need to look it up in the current dex file, and it
1976 // is unlikely that it exists. The most usual situation for such typed
1977 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01001978 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001979 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001980 }
1981}
1982
Roland Levillaina5c4a402016-03-15 15:02:50 +00001983void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1984 bool is_signum,
1985 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001986 DCHECK(invoke->IsInvokeStaticOrDirect());
1987 uint32_t dex_pc = invoke->GetDexPc();
1988 HInstruction* left = invoke->InputAt(0);
1989 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001990 if (!is_signum) {
1991 right = invoke->InputAt(1);
1992 } else if (type == Primitive::kPrimLong) {
1993 right = GetGraph()->GetLongConstant(0);
1994 } else {
1995 right = GetGraph()->GetIntConstant(0);
1996 }
1997 HCompare* compare = new (GetGraph()->GetArena())
1998 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1999 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2000}
2001
Aart Bik75a38b22016-02-17 10:41:50 -08002002void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2003 DCHECK(invoke->IsInvokeStaticOrDirect());
2004 uint32_t dex_pc = invoke->GetDexPc();
2005 // IsNaN(x) is the same as x != x.
2006 HInstruction* x = invoke->InputAt(0);
2007 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002008 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002009 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2010}
2011
Aart Bik2a6aad92016-02-25 11:32:32 -08002012void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2013 DCHECK(invoke->IsInvokeStaticOrDirect());
2014 uint32_t dex_pc = invoke->GetDexPc();
2015 HInstruction* x = invoke->InputAt(0);
2016 Primitive::Type type = x->GetType();
2017 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2018 HInstruction* nan;
2019 if (type == Primitive::kPrimDouble) {
2020 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2021 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2022 kNeedsEnvironmentOrCache,
2023 kNoSideEffects,
2024 kNoThrow);
2025 } else {
2026 DCHECK_EQ(type, Primitive::kPrimFloat);
2027 nan = GetGraph()->GetIntConstant(0x7fc00000);
2028 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2029 kNeedsEnvironmentOrCache,
2030 kNoSideEffects,
2031 kNoThrow);
2032 }
2033 // Test IsNaN(x), which is the same as x != x.
2034 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
2035 condition->SetBias(ComparisonBias::kLtBias);
2036 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2037 // Select between the two.
2038 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
2039 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2040 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2041}
2042
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002043void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2044 HInstruction* str = invoke->InputAt(0);
2045 HInstruction* index = invoke->InputAt(1);
2046 uint32_t dex_pc = invoke->GetDexPc();
2047 ArenaAllocator* arena = GetGraph()->GetArena();
2048 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2049 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2050 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2051 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002052 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2053 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002054 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002055 HArrayGet* array_get = new (arena) HArrayGet(
2056 str, bounds_check, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002057 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2058 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2059 GetGraph()->SetHasBoundsChecks(true);
2060}
2061
Vladimir Markodce016e2016-04-28 13:10:02 +01002062void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2063 HInstruction* str = invoke->InputAt(0);
2064 uint32_t dex_pc = invoke->GetDexPc();
2065 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2066 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002067 HArrayLength* length =
2068 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002069 HInstruction* replacement;
2070 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2071 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2072 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2073 HIntConstant* zero = GetGraph()->GetIntConstant(0);
2074 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
2075 replacement = equal;
2076 } else {
2077 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2078 replacement = length;
2079 }
2080 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2081}
2082
Aart Bikff7d89c2016-11-07 08:49:28 -08002083// This method should only be used on intrinsics whose sole way of throwing an
2084// exception is raising a NPE when the nth argument is null. If that argument
2085// is provably non-null, we can clear the flag.
2086void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2087 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002088 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002089 invoke->SetCanThrow(false);
2090 }
2091}
2092
Aart Bik71bf7b42016-11-16 10:17:46 -08002093// Methods that return "this" can replace the returned value with the receiver.
2094void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2095 if (invoke->HasUses()) {
2096 HInstruction* receiver = invoke->InputAt(0);
2097 invoke->ReplaceWith(receiver);
2098 RecordSimplification();
2099 }
2100}
2101
2102// Helper method for StringBuffer escape analysis.
2103static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2104 if (user->IsInvokeStaticOrDirect()) {
2105 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002106 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2107 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002108 user->InputAt(0) == reference;
2109 } else if (user->IsInvokeVirtual()) {
2110 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2111 case Intrinsics::kStringBufferLength:
2112 case Intrinsics::kStringBufferToString:
2113 DCHECK_EQ(user->InputAt(0), reference);
2114 return true;
2115 case Intrinsics::kStringBufferAppend:
2116 // Returns "this", so only okay if no further uses.
2117 DCHECK_EQ(user->InputAt(0), reference);
2118 DCHECK_NE(user->InputAt(1), reference);
2119 return !user->HasUses();
2120 default:
2121 break;
2122 }
2123 }
2124 return false;
2125}
2126
2127// Certain allocation intrinsics are not removed by dead code elimination
2128// because of potentially throwing an OOM exception or other side effects.
2129// This method removes such intrinsics when special circumstances allow.
2130void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2131 if (!invoke->HasUses()) {
2132 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2133 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2134 // call does not escape since only thread-local synchronization may be removed.
2135 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2136 HInstruction* receiver = invoke->InputAt(0);
2137 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2138 invoke->GetBlock()->RemoveInstruction(invoke);
2139 RecordSimplification();
2140 }
2141 }
2142}
2143
Aart Bik11932592016-03-08 12:42:25 -08002144void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2145 uint32_t dex_pc = invoke->GetDexPc();
2146 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2147 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2148}
2149
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002150void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002151 switch (instruction->GetIntrinsic()) {
2152 case Intrinsics::kStringEquals:
2153 SimplifyStringEquals(instruction);
2154 break;
2155 case Intrinsics::kSystemArrayCopy:
2156 SimplifySystemArrayCopy(instruction);
2157 break;
2158 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002159 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
2160 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002161 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00002162 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002163 break;
2164 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002165 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
2166 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002167 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00002168 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002169 break;
2170 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002171 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
2172 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002173 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002174 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002175 break;
2176 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002177 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
2178 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002179 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00002180 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08002181 break;
2182 case Intrinsics::kFloatIsNaN:
2183 case Intrinsics::kDoubleIsNaN:
2184 SimplifyIsNaN(instruction);
2185 break;
2186 case Intrinsics::kFloatFloatToIntBits:
2187 case Intrinsics::kDoubleDoubleToLongBits:
2188 SimplifyFP2Int(instruction);
2189 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002190 case Intrinsics::kStringCharAt:
2191 SimplifyStringCharAt(instruction);
2192 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002193 case Intrinsics::kStringIsEmpty:
2194 case Intrinsics::kStringLength:
2195 SimplifyStringIsEmptyOrLength(instruction);
2196 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002197 case Intrinsics::kStringStringIndexOf:
2198 case Intrinsics::kStringStringIndexOfAfter:
2199 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2200 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002201 case Intrinsics::kStringBufferAppend:
2202 case Intrinsics::kStringBuilderAppend:
2203 SimplifyReturnThis(instruction);
2204 break;
2205 case Intrinsics::kStringBufferToString:
2206 case Intrinsics::kStringBuilderToString:
2207 SimplifyAllocationIntrinsic(instruction);
2208 break;
Aart Bik11932592016-03-08 12:42:25 -08002209 case Intrinsics::kUnsafeLoadFence:
2210 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2211 break;
2212 case Intrinsics::kUnsafeStoreFence:
2213 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2214 break;
2215 case Intrinsics::kUnsafeFullFence:
2216 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2217 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002218 default:
2219 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002220 }
2221}
2222
Aart Bikbb245d12015-10-19 11:05:03 -07002223void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2224 HInstruction* cond = deoptimize->InputAt(0);
2225 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002226 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002227 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002228 if (deoptimize->GuardsAnInput()) {
2229 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2230 }
Aart Bikbb245d12015-10-19 11:05:03 -07002231 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2232 } else {
2233 // Always deopt.
2234 }
2235 }
2236}
2237
Anton Kirilove14dc862016-05-13 17:56:15 +01002238// Replace code looking like
2239// OP y, x, const1
2240// OP z, y, const2
2241// with
2242// OP z, x, const3
2243// where OP is both an associative and a commutative operation.
2244bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2245 HBinaryOperation* instruction) {
2246 DCHECK(instruction->IsCommutative());
2247
2248 if (!Primitive::IsIntegralType(instruction->GetType())) {
2249 return false;
2250 }
2251
2252 HInstruction* left = instruction->GetLeft();
2253 HInstruction* right = instruction->GetRight();
2254 // Variable names as described above.
2255 HConstant* const2;
2256 HBinaryOperation* y;
2257
2258 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2259 const2 = right->AsConstant();
2260 y = left->AsBinaryOperation();
2261 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2262 const2 = left->AsConstant();
2263 y = right->AsBinaryOperation();
2264 } else {
2265 // The node does not match the pattern.
2266 return false;
2267 }
2268
2269 // If `y` has more than one use, we do not perform the optimization
2270 // because it might increase code size (e.g. if the new constant is
2271 // no longer encodable as an immediate operand in the target ISA).
2272 if (!y->HasOnlyOneNonEnvironmentUse()) {
2273 return false;
2274 }
2275
2276 // GetConstantRight() can return both left and right constants
2277 // for commutative operations.
2278 HConstant* const1 = y->GetConstantRight();
2279 if (const1 == nullptr) {
2280 return false;
2281 }
2282
2283 instruction->ReplaceInput(const1, 0);
2284 instruction->ReplaceInput(const2, 1);
2285 HConstant* const3 = instruction->TryStaticEvaluation();
2286 DCHECK(const3 != nullptr);
2287 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2288 instruction->ReplaceInput(const3, 1);
2289 RecordSimplification();
2290 return true;
2291}
2292
2293static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2294 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2295}
2296
2297// Helper function that performs addition statically, considering the result type.
2298static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
2299 // Use the Compute() method for consistency with TryStaticEvaluation().
2300 if (type == Primitive::kPrimInt) {
2301 return HAdd::Compute<int32_t>(x, y);
2302 } else {
2303 DCHECK_EQ(type, Primitive::kPrimLong);
2304 return HAdd::Compute<int64_t>(x, y);
2305 }
2306}
2307
2308// Helper function that handles the child classes of HConstant
2309// and returns an integer with the appropriate sign.
2310static int64_t GetValue(HConstant* constant, bool is_negated) {
2311 int64_t ret = Int64FromConstant(constant);
2312 return is_negated ? -ret : ret;
2313}
2314
2315// Replace code looking like
2316// OP1 y, x, const1
2317// OP2 z, y, const2
2318// with
2319// OP3 z, x, const3
2320// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2321bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2322 HBinaryOperation* instruction) {
2323 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2324
2325 Primitive::Type type = instruction->GetType();
2326 if (!Primitive::IsIntegralType(type)) {
2327 return false;
2328 }
2329
2330 HInstruction* left = instruction->GetLeft();
2331 HInstruction* right = instruction->GetRight();
2332 // Variable names as described above.
2333 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2334 if (const2 == nullptr) {
2335 return false;
2336 }
2337
2338 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2339 ? left->AsBinaryOperation()
2340 : AsAddOrSub(right);
2341 // If y has more than one use, we do not perform the optimization because
2342 // it might increase code size (e.g. if the new constant is no longer
2343 // encodable as an immediate operand in the target ISA).
2344 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2345 return false;
2346 }
2347
2348 left = y->GetLeft();
2349 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2350 if (const1 == nullptr) {
2351 return false;
2352 }
2353
2354 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2355 // If both inputs are constants, let the constant folding pass deal with it.
2356 if (x->IsConstant()) {
2357 return false;
2358 }
2359
2360 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2361 int64_t const2_val = GetValue(const2, is_const2_negated);
2362 bool is_y_negated = (y == right) && instruction->IsSub();
2363 right = y->GetRight();
2364 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2365 int64_t const1_val = GetValue(const1, is_const1_negated);
2366 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2367 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2368 HBasicBlock* block = instruction->GetBlock();
2369 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2370 ArenaAllocator* arena = instruction->GetArena();
2371 HInstruction* z;
2372
2373 if (is_x_negated) {
2374 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2375 } else {
2376 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2377 }
2378
2379 block->ReplaceAndRemoveInstructionWith(instruction, z);
2380 RecordSimplification();
2381 return true;
2382}
2383
Lena Djokicbc5460b2017-07-20 16:07:36 +02002384void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2385 if (TryCombineVecMultiplyAccumulate(instruction)) {
2386 RecordSimplification();
2387 }
2388}
2389
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002390} // namespace art