blob: 3164ce138f9a20191e4ba05a4153364656247b34 [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"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010021#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080022#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010023#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070025#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070026#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027
Nicolas Geoffray3c049742014-09-24 18:10:46 +010028namespace art {
29
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010030class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000032 InstructionSimplifierVisitor(HGraph* graph,
33 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010034 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000035 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010038 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010039 stats_(stats) {}
40
41 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000042
43 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010044 void RecordSimplification() {
45 simplification_occurred_ = true;
46 simplifications_at_current_position_++;
Igor Murashkin1e065a52017-08-09 13:20:34 -070047 MaybeRecordStat(stats_, kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010048 }
49
Scott Wakeling40a04bf2015-12-11 09:50:36 +000050 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51 bool TryReplaceWithRotate(HBinaryOperation* instruction);
52 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
53 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55
Alexandre Rames188d4312015-04-09 18:30:21 +010056 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000057 // `op` should be either HOr or HAnd.
58 // De Morgan's laws:
59 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
60 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010061 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
62 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020063 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010064
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000065 void VisitShift(HBinaryOperation* shift);
66
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010068 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
69 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010070 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
71 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000072 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000073 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000074 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080075 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000076 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitAdd(HAdd* instruction) OVERRIDE;
78 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040079 void VisitCondition(HCondition* instruction) OVERRIDE;
80 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
81 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
82 void VisitLessThan(HLessThan* condition) OVERRIDE;
83 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060084 void VisitBelow(HBelow* condition) OVERRIDE;
85 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
86 void VisitAbove(HAbove* condition) OVERRIDE;
87 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitDiv(HDiv* instruction) OVERRIDE;
89 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010090 void VisitNeg(HNeg* instruction) OVERRIDE;
91 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitOr(HOr* instruction) OVERRIDE;
93 void VisitShl(HShl* instruction) OVERRIDE;
94 void VisitShr(HShr* instruction) OVERRIDE;
95 void VisitSub(HSub* instruction) OVERRIDE;
96 void VisitUShr(HUShr* instruction) OVERRIDE;
97 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000098 void VisitSelect(HSelect* select) OVERRIDE;
99 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100100 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100101 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700102 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200103 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100104
105 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000106
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100107 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100108 void SimplifySystemArrayCopy(HInvoke* invoke);
109 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800111 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800112 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100113 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100114 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800115 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800116 void SimplifyReturnThis(HInvoke* invoke);
117 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800118 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100119
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000120 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100121 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000122 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 bool simplification_occurred_ = false;
124 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700125 // We ensure we do not loop infinitely. The value should not be too high, since that
126 // would allow looping around the same basic block too many times. The value should
127 // not be too low either, however, since we want to allow revisiting a basic block
128 // with many statements and simplifications at least once.
129 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000130};
131
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100132void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100133 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100134 visitor.Run();
135}
136
137void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100138 // Iterate in reverse post order to open up more simplifications to users
139 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100140 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100141 // The simplification of an instruction to another instruction may yield
142 // possibilities for other simplifications. So although we perform a reverse
143 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100144 do {
145 simplification_occurred_ = false;
146 VisitBasicBlock(block);
147 } while (simplification_occurred_ &&
148 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100149 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100150 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100151}
152
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000153namespace {
154
155bool AreAllBitsSet(HConstant* constant) {
156 return Int64FromConstant(constant) == -1;
157}
158
159} // namespace
160
Alexandre Rames188d4312015-04-09 18:30:21 +0100161// Returns true if the code was simplified to use only one negation operation
162// after the binary operation instead of one on each of the inputs.
163bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
164 DCHECK(binop->IsAdd() || binop->IsSub());
165 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
166 HNeg* left_neg = binop->GetLeft()->AsNeg();
167 HNeg* right_neg = binop->GetRight()->AsNeg();
168 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
169 !right_neg->HasOnlyOneNonEnvironmentUse()) {
170 return false;
171 }
172 // Replace code looking like
173 // NEG tmp1, a
174 // NEG tmp2, b
175 // ADD dst, tmp1, tmp2
176 // with
177 // ADD tmp, a, b
178 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600179 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
180 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
181 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100182 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600183 return false;
184 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100185 binop->ReplaceInput(left_neg->GetInput(), 0);
186 binop->ReplaceInput(right_neg->GetInput(), 1);
187 left_neg->GetBlock()->RemoveInstruction(left_neg);
188 right_neg->GetBlock()->RemoveInstruction(right_neg);
189 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
190 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
191 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
192 RecordSimplification();
193 return true;
194}
195
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000196bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
197 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100198 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000199 HInstruction* left = op->GetLeft();
200 HInstruction* right = op->GetRight();
201
202 // We can apply De Morgan's laws if both inputs are Not's and are only used
203 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000204 if (((left->IsNot() && right->IsNot()) ||
205 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000206 left->HasOnlyOneNonEnvironmentUse() &&
207 right->HasOnlyOneNonEnvironmentUse()) {
208 // Replace code looking like
209 // NOT nota, a
210 // NOT notb, b
211 // AND dst, nota, notb (respectively OR)
212 // with
213 // OR or, a, b (respectively AND)
214 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* src_left = left->InputAt(0);
216 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000217 uint32_t dex_pc = op->GetDexPc();
218
219 // Remove the negations on the inputs.
220 left->ReplaceWith(src_left);
221 right->ReplaceWith(src_right);
222 left->GetBlock()->RemoveInstruction(left);
223 right->GetBlock()->RemoveInstruction(right);
224
225 // Replace the `HAnd` or `HOr`.
226 HBinaryOperation* hbin;
227 if (op->IsAnd()) {
228 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
229 } else {
230 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
234 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
235 } else {
236 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
237 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000238
239 op->GetBlock()->InsertInstructionBefore(hbin, op);
240 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
241
242 RecordSimplification();
243 return true;
244 }
245
246 return false;
247}
248
Lena Djokicbc5460b2017-07-20 16:07:36 +0200249bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200251 InstructionSet isa = codegen_->GetInstructionSet();
252 switch (isa) {
253 case kArm64:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100254 if (!(type == DataType::Type::kInt8 ||
255 type == DataType::Type::kUint16 ||
256 type == DataType::Type::kInt16 ||
257 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200258 return false;
259 }
260 break;
261 case kMips:
262 case kMips64:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100263 if (!(type == DataType::Type::kInt8 ||
264 type == DataType::Type::kUint16 ||
265 type == DataType::Type::kInt16 ||
266 type == DataType::Type::kInt32 ||
267 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200268 return false;
269 }
270 break;
271 default:
272 return false;
273 }
274
275 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetArena();
276
277 if (mul->HasOnlyOneNonEnvironmentUse()) {
278 HInstruction* use = mul->GetUses().front().GetUser();
279 if (use->IsVecAdd() || use->IsVecSub()) {
280 // Replace code looking like
281 // VECMUL tmp, x, y
282 // VECADD/SUB dst, acc, tmp
283 // with
284 // VECMULACC dst, acc, x, y
285 // Note that we do not want to (unconditionally) perform the merge when the
286 // multiplication has multiple uses and it can be merged in all of them.
287 // Multiple uses could happen on the same control-flow path, and we would
288 // then increase the amount of work. In the future we could try to evaluate
289 // whether all uses are on different control-flow paths (using dominance and
290 // reverse-dominance information) and only perform the merge when they are.
291 HInstruction* accumulator = nullptr;
292 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
293 HInstruction* binop_left = binop->GetLeft();
294 HInstruction* binop_right = binop->GetRight();
295 // This is always true since the `HVecMul` has only one use (which is checked above).
296 DCHECK_NE(binop_left, binop_right);
297 if (binop_right == mul) {
298 accumulator = binop_left;
299 } else if (use->IsVecAdd()) {
300 DCHECK_EQ(binop_left, mul);
301 accumulator = binop_right;
302 }
303
304 HInstruction::InstructionKind kind =
305 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
306 if (accumulator != nullptr) {
307 HVecMultiplyAccumulate* mulacc =
308 new (arena) HVecMultiplyAccumulate(arena,
309 kind,
310 accumulator,
311 mul->GetLeft(),
312 mul->GetRight(),
313 binop->GetPackedType(),
314 binop->GetVectorLength());
315
316 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
317 DCHECK(!mul->HasUses());
318 mul->GetBlock()->RemoveInstruction(mul);
319 return true;
320 }
321 }
322 }
323
324 return false;
325}
326
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000327void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
328 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100329 HInstruction* shift_amount = instruction->GetRight();
330 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000331
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100332 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100333 ? kMaxLongShiftDistance
334 : kMaxIntShiftDistance;
335
336 if (shift_amount->IsConstant()) {
337 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700338 int64_t masked_cst = cst & implicit_mask;
339 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400340 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100341 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400342 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100343 // value
344 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400345 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100346 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100347 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700348 } else if (masked_cst != cst) {
349 // Replace code looking like
350 // SHL dst, value, cst
351 // where cst exceeds maximum distance with the equivalent
352 // SHL dst, value, cst & implicit_mask
353 // (as defined by shift semantics). This ensures other
354 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100355 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700356 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
357 RecordSimplification();
358 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100359 }
360 }
361
362 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100363 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
364 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100365 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100366 // AND adjusted_shift, shift, <superset of implicit mask>
367 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
368 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
369 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100370 // with
371 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100372 if (shift_amount->IsAnd() ||
373 shift_amount->IsOr() ||
374 shift_amount->IsXor() ||
375 shift_amount->IsAdd() ||
376 shift_amount->IsSub()) {
377 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
378 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
379 HConstant* mask = bin_op->GetConstantRight();
380 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
381 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100382 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100383 return;
384 }
385 } else if (shift_amount->IsTypeConversion()) {
386 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
387 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
388 // Non-integral and 64-bit source types require an explicit type conversion.
389 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
390 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
391 RecordSimplification();
392 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400393 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000394 }
395}
396
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000397static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
398 return (sub->GetRight() == other &&
399 sub->GetLeft()->IsConstant() &&
400 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
401}
402
403bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
404 HUShr* ushr,
405 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000406 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
407 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000408 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
409 if (!ushr->HasUses()) {
410 ushr->GetBlock()->RemoveInstruction(ushr);
411 }
412 if (!ushr->GetRight()->HasUses()) {
413 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
414 }
415 if (!shl->HasUses()) {
416 shl->GetBlock()->RemoveInstruction(shl);
417 }
418 if (!shl->GetRight()->HasUses()) {
419 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
420 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100421 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000422 return true;
423}
424
425// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
426bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000427 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
428 HInstruction* left = op->GetLeft();
429 HInstruction* right = op->GetRight();
430 // If we have an UShr and a Shl (in either order).
431 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
432 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
433 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100434 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000435 if (ushr->GetType() == shl->GetType() &&
436 ushr->GetLeft() == shl->GetLeft()) {
437 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
438 // Shift distances are both constant, try replacing with Ror if they
439 // add up to the register size.
440 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
441 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
442 // Shift distances are potentially of the form x and (reg_size - x).
443 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
444 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
445 // Shift distances are potentially of the form d and -d.
446 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
447 }
448 }
449 }
450 return false;
451}
452
453// Try replacing code looking like (x >>> #rdist OP x << #ldist):
454// UShr dst, x, #rdist
455// Shl tmp, x, #ldist
456// OP dst, dst, tmp
457// or like (x >>> #rdist OP x << #-ldist):
458// UShr dst, x, #rdist
459// Shl tmp, x, #-ldist
460// OP dst, dst, tmp
461// with
462// Ror dst, x, #rdist
463bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
464 HUShr* ushr,
465 HShl* shl) {
466 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100467 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000468 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
469 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
470 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
471 ReplaceRotateWithRor(op, ushr, shl);
472 return true;
473 }
474 return false;
475}
476
477// Replace code looking like (x >>> -d OP x << d):
478// Neg neg, d
479// UShr dst, x, neg
480// Shl tmp, x, d
481// OP dst, dst, tmp
482// with
483// Neg neg, d
484// Ror dst, x, neg
485// *** OR ***
486// Replace code looking like (x >>> d OP x << -d):
487// UShr dst, x, d
488// Neg neg, d
489// Shl tmp, x, neg
490// OP dst, dst, tmp
491// with
492// Ror dst, x, d
493bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
494 HUShr* ushr,
495 HShl* shl) {
496 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
497 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
498 bool neg_is_left = shl->GetRight()->IsNeg();
499 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
500 // And the shift distance being negated is the distance being shifted the other way.
501 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
502 ReplaceRotateWithRor(op, ushr, shl);
503 }
504 return false;
505}
506
507// Try replacing code looking like (x >>> d OP x << (#bits - d)):
508// UShr dst, x, d
509// Sub ld, #bits, d
510// Shl tmp, x, ld
511// OP dst, dst, tmp
512// with
513// Ror dst, x, d
514// *** OR ***
515// Replace code looking like (x >>> (#bits - d) OP x << d):
516// Sub rd, #bits, d
517// UShr dst, x, rd
518// Shl tmp, x, d
519// OP dst, dst, tmp
520// with
521// Neg neg, d
522// Ror dst, x, neg
523bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
524 HUShr* ushr,
525 HShl* shl) {
526 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
527 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100528 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000529 HInstruction* shl_shift = shl->GetRight();
530 HInstruction* ushr_shift = ushr->GetRight();
531 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
532 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
533 return ReplaceRotateWithRor(op, ushr, shl);
534 }
535 return false;
536}
537
Calin Juravle10e244f2015-01-26 18:54:32 +0000538void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
539 HInstruction* obj = null_check->InputAt(0);
540 if (!obj->CanBeNull()) {
541 null_check->ReplaceWith(obj);
542 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000543 if (stats_ != nullptr) {
544 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
545 }
546 }
547}
548
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100549bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
550 if (!input->CanBeNull()) {
551 return true;
552 }
553
Vladimir Marko46817b82016-03-29 12:21:58 +0100554 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
555 HInstruction* user = use.GetUser();
556 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100557 return true;
558 }
559 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100560
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100561 return false;
562}
563
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100564// Returns whether doing a type test between the class of `object` against `klass` has
565// a statically known outcome. The result of the test is stored in `outcome`.
566static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000567 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
568 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
569 ScopedObjectAccess soa(Thread::Current());
570 if (!obj_rti.IsValid()) {
571 // We run the simplifier before the reference type propagation so type info might not be
572 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100573 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000574 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100575
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100576 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100577 if (!class_rti.IsValid()) {
578 // Happens when the loaded class is unresolved.
579 return false;
580 }
581 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000582 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100583 *outcome = true;
584 return true;
585 } else if (obj_rti.IsExact()) {
586 // The test failed at compile time so will also fail at runtime.
587 *outcome = false;
588 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100589 } else if (!class_rti.IsInterface()
590 && !obj_rti.IsInterface()
591 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100592 // Different type hierarchy. The test will fail.
593 *outcome = false;
594 return true;
595 }
596 return false;
597}
598
599void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
600 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100601 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
602 if (load_class->NeedsAccessCheck()) {
603 // If we need to perform an access check we cannot remove the instruction.
604 return;
605 }
606
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100607 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100608 check_cast->ClearMustDoNullCheck();
609 }
610
611 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000612 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700613 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100614 return;
615 }
616
Vladimir Markoa65ed302016-03-14 21:21:29 +0000617 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
618 // the return value check with the `outcome` check, b/27651442 .
619 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700620 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100621 if (outcome) {
622 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700623 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700624 if (!load_class->HasUses()) {
625 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
626 // However, here we know that it cannot because the checkcast was successfull, hence
627 // the class was already loaded.
628 load_class->GetBlock()->RemoveInstruction(load_class);
629 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100630 } else {
631 // Don't do anything for exceptional cases for now. Ideally we should remove
632 // all instructions and blocks this instruction dominates.
633 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000634 }
635}
636
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100637void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100638 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100639 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
640 if (load_class->NeedsAccessCheck()) {
641 // If we need to perform an access check we cannot remove the instruction.
642 return;
643 }
644
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100645 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100646 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100647 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100648 instruction->ClearMustDoNullCheck();
649 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100650
651 HGraph* graph = GetGraph();
652 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700653 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654 instruction->ReplaceWith(graph->GetIntConstant(0));
655 instruction->GetBlock()->RemoveInstruction(instruction);
656 RecordSimplification();
657 return;
658 }
659
Vladimir Marko24bd8952016-03-15 10:40:33 +0000660 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
661 // the return value check with the `outcome` check, b/27651442 .
662 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700663 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700664 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100665 if (outcome && can_be_null) {
666 // Type test will succeed, we just need a null test.
667 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
668 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
669 instruction->ReplaceWith(test);
670 } else {
671 // We've statically determined the result of the instanceof.
672 instruction->ReplaceWith(graph->GetIntConstant(outcome));
673 }
674 RecordSimplification();
675 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700676 if (outcome && !load_class->HasUses()) {
677 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
678 // However, here we know that it cannot because the instanceof check was successfull, hence
679 // the class was already loaded.
680 load_class->GetBlock()->RemoveInstruction(load_class);
681 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100682 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100683}
684
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100685void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100686 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100687 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100688 instruction->ClearValueCanBeNull();
689 }
690}
691
692void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100693 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100694 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100695 instruction->ClearValueCanBeNull();
696 }
697}
698
Anton Shaminbdd79352016-02-15 12:48:36 +0600699static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
700 HInstruction *lhs = cond->InputAt(0);
701 HInstruction *rhs = cond->InputAt(1);
702 switch (cond->GetKind()) {
703 case HInstruction::kEqual:
704 return new (arena) HEqual(rhs, lhs);
705 case HInstruction::kNotEqual:
706 return new (arena) HNotEqual(rhs, lhs);
707 case HInstruction::kLessThan:
708 return new (arena) HGreaterThan(rhs, lhs);
709 case HInstruction::kLessThanOrEqual:
710 return new (arena) HGreaterThanOrEqual(rhs, lhs);
711 case HInstruction::kGreaterThan:
712 return new (arena) HLessThan(rhs, lhs);
713 case HInstruction::kGreaterThanOrEqual:
714 return new (arena) HLessThanOrEqual(rhs, lhs);
715 case HInstruction::kBelow:
716 return new (arena) HAbove(rhs, lhs);
717 case HInstruction::kBelowOrEqual:
718 return new (arena) HAboveOrEqual(rhs, lhs);
719 case HInstruction::kAbove:
720 return new (arena) HBelow(rhs, lhs);
721 case HInstruction::kAboveOrEqual:
722 return new (arena) HBelowOrEqual(rhs, lhs);
723 default:
724 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
725 }
726 return nullptr;
727}
728
Aart Bik2767f4b2016-10-28 15:03:53 -0700729static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100730 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700731 return true; // input has direct boolean type
732 } else if (cmp->GetUses().HasExactlyOneElement()) {
733 // Comparison also has boolean type if both its input and the instruction
734 // itself feed into the same phi node.
735 HInstruction* user = cmp->GetUses().front().GetUser();
736 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
737 }
738 return false;
739}
740
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000741void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100742 HInstruction* input_const = equal->GetConstantRight();
743 if (input_const != nullptr) {
744 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700745 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100746 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100747 // We are comparing the boolean to a constant which is of type int and can
748 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000749 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100750 // Replace (bool_value == true) with bool_value
751 equal->ReplaceWith(input_value);
752 block->RemoveInstruction(equal);
753 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000754 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700755 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500756 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
757 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100758 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100759 } else {
760 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
761 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
762 block->RemoveInstruction(equal);
763 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100764 }
Mark Mendellc4701932015-04-10 13:18:51 -0400765 } else {
766 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100767 }
Mark Mendellc4701932015-04-10 13:18:51 -0400768 } else {
769 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100770 }
771}
772
David Brazdil0d13fee2015-04-17 14:52:19 +0100773void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
774 HInstruction* input_const = not_equal->GetConstantRight();
775 if (input_const != nullptr) {
776 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700777 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100778 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100779 // We are comparing the boolean to a constant which is of type int and can
780 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000781 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700782 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500783 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
784 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100785 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000786 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100788 not_equal->ReplaceWith(input_value);
789 block->RemoveInstruction(not_equal);
790 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100791 } else {
792 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
793 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
794 block->RemoveInstruction(not_equal);
795 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100796 }
Mark Mendellc4701932015-04-10 13:18:51 -0400797 } else {
798 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100799 }
Mark Mendellc4701932015-04-10 13:18:51 -0400800 } else {
801 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100802 }
803}
804
805void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000806 HInstruction* input = bool_not->InputAt(0);
807 HInstruction* replace_with = nullptr;
808
809 if (input->IsIntConstant()) {
810 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000811 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000812 replace_with = GetGraph()->GetIntConstant(0);
813 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000814 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000815 replace_with = GetGraph()->GetIntConstant(1);
816 }
817 } else if (input->IsBooleanNot()) {
818 // Replace (!(!bool_value)) with bool_value.
819 replace_with = input->InputAt(0);
820 } else if (input->IsCondition() &&
821 // Don't change FP compares. The definition of compares involving
822 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100823 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000824 // Replace condition with its opposite.
825 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
826 }
827
828 if (replace_with != nullptr) {
829 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100830 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000831 RecordSimplification();
832 }
833}
834
Aart Bik4f7dd342017-09-12 13:12:57 -0700835// Constructs a new ABS(x) node in the HIR.
836static HInstruction* NewIntegralAbs(ArenaAllocator* arena, HInstruction* x, HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100837 DataType::Type type = x->GetType();
838 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700839 // Construct a fake intrinsic with as much context as is needed to allocate one.
840 // The intrinsic will always be lowered into code later anyway.
841 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
842 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
843 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
844 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
845 0u
846 };
847 HInvokeStaticOrDirect* invoke = new (arena) HInvokeStaticOrDirect(
848 arena,
849 1,
850 type,
851 x->GetDexPc(),
852 /*method_idx*/ -1,
853 /*resolved_method*/ nullptr,
854 dispatch_info,
855 kStatic,
856 MethodReference(nullptr, dex::kDexNoIndex),
857 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
858 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100859 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
860 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700861 kNoEnvironmentOrCache,
862 kNoSideEffects,
863 kNoThrow);
864 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
865 return invoke;
866}
867
868// Returns true if operands a and b consists of widening type conversions
869// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100870static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700871 if (a->IsTypeConversion() && a->GetType() == to_type) {
872 a = a->InputAt(0);
873 }
874 if (b->IsTypeConversion() && b->GetType() == to_type) {
875 b = b->InputAt(0);
876 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100877 DataType::Type type1 = a->GetType();
878 DataType::Type type2 = b->GetType();
879 return (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
880 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
881 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
882 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
883 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700884}
885
David Brazdil74eb1b22015-12-14 11:44:01 +0000886void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
887 HInstruction* replace_with = nullptr;
888 HInstruction* condition = select->GetCondition();
889 HInstruction* true_value = select->GetTrueValue();
890 HInstruction* false_value = select->GetFalseValue();
891
892 if (condition->IsBooleanNot()) {
893 // Change ((!cond) ? x : y) to (cond ? y : x).
894 condition = condition->InputAt(0);
895 std::swap(true_value, false_value);
896 select->ReplaceInput(false_value, 0);
897 select->ReplaceInput(true_value, 1);
898 select->ReplaceInput(condition, 2);
899 RecordSimplification();
900 }
901
902 if (true_value == false_value) {
903 // Replace (cond ? x : x) with (x).
904 replace_with = true_value;
905 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000906 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000907 // Replace (true ? x : y) with (x).
908 replace_with = true_value;
909 } else {
910 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000911 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000912 replace_with = false_value;
913 }
914 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000915 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000916 // Replace (cond ? true : false) with (cond).
917 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000918 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000919 // Replace (cond ? false : true) with (!cond).
920 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
921 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700922 } else if (condition->IsCondition()) {
923 IfCondition cmp = condition->AsCondition()->GetCondition();
924 HInstruction* a = condition->InputAt(0);
925 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100926 DataType::Type t_type = true_value->GetType();
927 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700928 // Here we have a <cmp> b ? true_value : false_value.
929 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100930 if (t_type == f_type &&
931 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700932 // Try to replace typical integral ABS constructs.
933 if (true_value->IsNeg()) {
934 HInstruction* negated = true_value->InputAt(0);
935 if ((cmp == kCondLT || cmp == kCondLE) &&
936 (a == negated && a == false_value && IsInt64Value(b, 0))) {
937 // Found a < 0 ? -a : a which can be replaced by ABS(a).
938 replace_with = NewIntegralAbs(GetGraph()->GetArena(), false_value, select);
939 }
940 } else if (false_value->IsNeg()) {
941 HInstruction* negated = false_value->InputAt(0);
942 if ((cmp == kCondGT || cmp == kCondGE) &&
943 (a == true_value && a == negated && IsInt64Value(b, 0))) {
944 // Found a > 0 ? a : -a which can be replaced by ABS(a).
945 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
946 }
947 } else if (true_value->IsSub() && false_value->IsSub()) {
948 HInstruction* true_sub1 = true_value->InputAt(0);
949 HInstruction* true_sub2 = true_value->InputAt(1);
950 HInstruction* false_sub1 = false_value->InputAt(0);
951 HInstruction* false_sub2 = false_value->InputAt(1);
952 if ((((cmp == kCondGT || cmp == kCondGE) &&
953 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
954 ((cmp == kCondLT || cmp == kCondLE) &&
955 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
956 AreLowerPrecisionArgs(t_type, a, b)) {
957 // Found a > b ? a - b : b - a or
958 // a < b ? b - a : a - b
959 // which can be replaced by ABS(a - b) for lower precision operands a, b.
960 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
961 }
962 }
963 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000964 }
965
966 if (replace_with != nullptr) {
967 select->ReplaceWith(replace_with);
968 select->GetBlock()->RemoveInstruction(select);
969 RecordSimplification();
970 }
971}
972
973void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
974 HInstruction* condition = instruction->InputAt(0);
975 if (condition->IsBooleanNot()) {
976 // Swap successors if input is negated.
977 instruction->ReplaceInput(condition->InputAt(0), 0);
978 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100979 RecordSimplification();
980 }
981}
982
Mingyao Yang0304e182015-01-30 16:41:29 -0800983void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
984 HInstruction* input = instruction->InputAt(0);
985 // If the array is a NewArray with constant size, replace the array length
986 // with the constant instruction. This helps the bounds check elimination phase.
987 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000988 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800989 if (input->IsIntConstant()) {
990 instruction->ReplaceWith(input);
991 }
992 }
993}
994
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000995void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000996 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100997 if (value->GetType() != DataType::Type::kReference) {
998 return;
999 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001000
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001001 if (CanEnsureNotNullAt(value, instruction)) {
1002 instruction->ClearValueCanBeNull();
1003 }
1004
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001005 if (value->IsArrayGet()) {
1006 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1007 // If the code is just swapping elements in the array, no need for a type check.
1008 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001009 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001010 }
1011 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001012
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001013 if (value->IsNullConstant()) {
1014 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001015 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001016 }
1017
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001018 ScopedObjectAccess soa(Thread::Current());
1019 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1020 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1021 if (!array_rti.IsValid()) {
1022 return;
1023 }
1024
1025 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1026 instruction->ClearNeedsTypeCheck();
1027 return;
1028 }
1029
1030 if (array_rti.IsObjectArray()) {
1031 if (array_rti.IsExact()) {
1032 instruction->ClearNeedsTypeCheck();
1033 return;
1034 }
1035 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001036 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001037}
1038
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001039static bool IsTypeConversionImplicit(DataType::Type input_type, DataType::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +01001040 // Invariant: We should never generate a conversion to a Boolean value.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001041 DCHECK_NE(DataType::Type::kBool, result_type);
Roland Levillainf355c3f2016-03-30 19:09:03 +01001042
Vladimir Markob52bbde2016-02-12 12:06:05 +00001043 // Besides conversion to the same type, widening integral conversions are implicit,
1044 // excluding conversions to long and the byte->char conversion where we need to
1045 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
1046 return result_type == input_type ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001047 (result_type == DataType::Type::kInt32 && (input_type == DataType::Type::kBool ||
1048 input_type == DataType::Type::kInt8 ||
1049 input_type == DataType::Type::kInt16 ||
1050 input_type == DataType::Type::kUint16)) ||
1051 (result_type == DataType::Type::kUint16 && input_type == DataType::Type::kBool) ||
1052 (result_type == DataType::Type::kInt16 && (input_type == DataType::Type::kBool ||
1053 input_type == DataType::Type::kInt8)) ||
1054 (result_type == DataType::Type::kInt8 && input_type == DataType::Type::kBool);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001055}
1056
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001057static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001058 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001059 // - conversion to Uint16, the only unsigned type, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001060 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1061 // For integral to FP conversions this holds because the FP mantissa is large enough.
1062 DCHECK_NE(input_type, result_type);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001063 return DataType::Size(result_type) > DataType::Size(input_type) &&
1064 result_type != DataType::Type::kUint16 &&
1065 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001066}
1067
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001068void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001069 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001070 DataType::Type input_type = input->GetType();
1071 DataType::Type result_type = instruction->GetResultType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001072 if (IsTypeConversionImplicit(input_type, result_type)) {
1073 // Remove the implicit conversion; this includes conversion to the same type.
1074 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001075 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001076 RecordSimplification();
1077 return;
1078 }
1079
1080 if (input->IsTypeConversion()) {
1081 HTypeConversion* input_conversion = input->AsTypeConversion();
1082 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001083 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001084
1085 // When the first conversion is lossless, a direct conversion from the original type
1086 // to the final type yields the same result, even for a lossy second conversion, for
1087 // example float->double->int or int->double->float.
1088 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1089
1090 // For integral conversions, see if the first conversion loses only bits that the second
1091 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1092 // conversion yields the same result, for example long->int->short or int->char->short.
1093 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001094 DataType::IsIntegralType(input_type) &&
1095 DataType::IsIntegralType(original_type) &&
1096 DataType::IsIntegralType(result_type) &&
1097 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001098
1099 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1100 // If the merged conversion is implicit, do the simplification unconditionally.
1101 if (IsTypeConversionImplicit(original_type, result_type)) {
1102 instruction->ReplaceWith(original_input);
1103 instruction->GetBlock()->RemoveInstruction(instruction);
1104 if (!input_conversion->HasUses()) {
1105 // Don't wait for DCE.
1106 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1107 }
1108 RecordSimplification();
1109 return;
1110 }
1111 // Otherwise simplify only if the first conversion has no other use.
1112 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1113 input_conversion->ReplaceWith(original_input);
1114 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1115 RecordSimplification();
1116 return;
1117 }
1118 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001119 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1120 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001121 HAnd* input_and = input->AsAnd();
1122 HConstant* constant = input_and->GetConstantRight();
1123 if (constant != nullptr) {
1124 int64_t value = Int64FromConstant(constant);
1125 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1126 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001127 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001128 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001129 HInstruction* original_input = input_and->GetLeastConstantLeft();
1130 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
1131 instruction->ReplaceWith(original_input);
1132 instruction->GetBlock()->RemoveInstruction(instruction);
1133 RecordSimplification();
1134 return;
1135 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1136 input_and->ReplaceWith(original_input);
1137 input_and->GetBlock()->RemoveInstruction(input_and);
1138 RecordSimplification();
1139 return;
1140 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001141 }
1142 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001143 }
1144}
1145
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001146void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1147 HConstant* input_cst = instruction->GetConstantRight();
1148 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001149 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001150 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001151 // Replace code looking like
1152 // ADD dst, src, 0
1153 // with
1154 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001155 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1156 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1157 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001158 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001159 instruction->ReplaceWith(input_other);
1160 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001161 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001162 return;
1163 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001164 }
1165
1166 HInstruction* left = instruction->GetLeft();
1167 HInstruction* right = instruction->GetRight();
1168 bool left_is_neg = left->IsNeg();
1169 bool right_is_neg = right->IsNeg();
1170
1171 if (left_is_neg && right_is_neg) {
1172 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1173 return;
1174 }
1175 }
1176
1177 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1178 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1179 // Replace code looking like
1180 // NEG tmp, b
1181 // ADD dst, a, tmp
1182 // with
1183 // SUB dst, a, b
1184 // We do not perform the optimization if the input negation has environment
1185 // uses or multiple non-environment uses as it could lead to worse code. In
1186 // particular, we do not want the live range of `b` to be extended if we are
1187 // not sure the initial 'NEG' instruction can be removed.
1188 HInstruction* other = left_is_neg ? right : left;
1189 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
1190 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1191 RecordSimplification();
1192 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001193 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001194 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001195
Anton Kirilove14dc862016-05-13 17:56:15 +01001196 if (TryReplaceWithRotate(instruction)) {
1197 return;
1198 }
1199
1200 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1201 // so no need to return.
1202 TryHandleAssociativeAndCommutativeOperation(instruction);
1203
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001204 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001205 TrySubtractionChainSimplification(instruction)) {
1206 return;
1207 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001208
1209 if (integral_type) {
1210 // Replace code patterns looking like
1211 // SUB dst1, x, y SUB dst1, x, y
1212 // ADD dst2, dst1, y ADD dst2, y, dst1
1213 // with
1214 // SUB dst1, x, y
1215 // ADD instruction is not needed in this case, we may use
1216 // one of inputs of SUB instead.
1217 if (left->IsSub() && left->InputAt(1) == right) {
1218 instruction->ReplaceWith(left->InputAt(0));
1219 RecordSimplification();
1220 instruction->GetBlock()->RemoveInstruction(instruction);
1221 return;
1222 } else if (right->IsSub() && right->InputAt(1) == left) {
1223 instruction->ReplaceWith(right->InputAt(0));
1224 RecordSimplification();
1225 instruction->GetBlock()->RemoveInstruction(instruction);
1226 return;
1227 }
1228 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001229}
1230
1231void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1232 HConstant* input_cst = instruction->GetConstantRight();
1233 HInstruction* input_other = instruction->GetLeastConstantLeft();
1234
Vladimir Marko452c1b62015-09-25 14:44:17 +01001235 if (input_cst != nullptr) {
1236 int64_t value = Int64FromConstant(input_cst);
1237 if (value == -1) {
1238 // Replace code looking like
1239 // AND dst, src, 0xFFF...FF
1240 // with
1241 // src
1242 instruction->ReplaceWith(input_other);
1243 instruction->GetBlock()->RemoveInstruction(instruction);
1244 RecordSimplification();
1245 return;
1246 }
1247 // Eliminate And from UShr+And if the And-mask contains all the bits that
1248 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1249 // precisely clears the shifted-in sign bits.
1250 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001251 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001252 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1253 size_t num_tail_bits_set = CTZ(value + 1);
1254 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1255 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1256 instruction->ReplaceWith(input_other);
1257 instruction->GetBlock()->RemoveInstruction(instruction);
1258 RecordSimplification();
1259 return;
1260 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1261 input_other->HasOnlyOneNonEnvironmentUse()) {
1262 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1263 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1264 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1265 input_other->InputAt(0),
1266 input_other->InputAt(1),
1267 input_other->GetDexPc());
1268 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1269 input_other->GetBlock()->RemoveInstruction(input_other);
1270 RecordSimplification();
1271 return;
1272 }
1273 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001274 }
1275
1276 // We assume that GVN has run before, so we only perform a pointer comparison.
1277 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001278 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001279 if (instruction->GetLeft() == instruction->GetRight()) {
1280 // Replace code looking like
1281 // AND dst, src, src
1282 // with
1283 // src
1284 instruction->ReplaceWith(instruction->GetLeft());
1285 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001286 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001287 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001288 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001289
Anton Kirilove14dc862016-05-13 17:56:15 +01001290 if (TryDeMorganNegationFactoring(instruction)) {
1291 return;
1292 }
1293
1294 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1295 // so no need to return.
1296 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001297}
1298
Mark Mendellc4701932015-04-10 13:18:51 -04001299void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1300 VisitCondition(condition);
1301}
1302
1303void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1304 VisitCondition(condition);
1305}
1306
1307void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1308 VisitCondition(condition);
1309}
1310
1311void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1312 VisitCondition(condition);
1313}
1314
Anton Shaminbdd79352016-02-15 12:48:36 +06001315void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1316 VisitCondition(condition);
1317}
1318
1319void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1320 VisitCondition(condition);
1321}
1322
1323void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1324 VisitCondition(condition);
1325}
1326
1327void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1328 VisitCondition(condition);
1329}
Aart Bike9f37602015-10-09 11:15:55 -07001330
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001331// Recognize the following pattern:
1332// obj.getClass() ==/!= Foo.class
1333// And replace it with a constant value if the type of `obj` is statically known.
1334static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1335 HInstruction* input_one = condition->InputAt(0);
1336 HInstruction* input_two = condition->InputAt(1);
1337 HLoadClass* load_class = input_one->IsLoadClass()
1338 ? input_one->AsLoadClass()
1339 : input_two->AsLoadClass();
1340 if (load_class == nullptr) {
1341 return false;
1342 }
1343
1344 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1345 if (!class_rti.IsValid()) {
1346 // Unresolved class.
1347 return false;
1348 }
1349
1350 HInstanceFieldGet* field_get = (load_class == input_one)
1351 ? input_two->AsInstanceFieldGet()
1352 : input_one->AsInstanceFieldGet();
1353 if (field_get == nullptr) {
1354 return false;
1355 }
1356
1357 HInstruction* receiver = field_get->InputAt(0);
1358 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1359 if (!receiver_type.IsExact()) {
1360 return false;
1361 }
1362
1363 {
1364 ScopedObjectAccess soa(Thread::Current());
1365 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1366 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1367 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1368 if (field_get->GetFieldInfo().GetField() != field) {
1369 return false;
1370 }
1371
1372 // We can replace the compare.
1373 int value = 0;
1374 if (receiver_type.IsEqual(class_rti)) {
1375 value = condition->IsEqual() ? 1 : 0;
1376 } else {
1377 value = condition->IsNotEqual() ? 1 : 0;
1378 }
1379 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1380 return true;
1381 }
1382}
1383
Mark Mendellc4701932015-04-10 13:18:51 -04001384void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001385 if (condition->IsEqual() || condition->IsNotEqual()) {
1386 if (RecognizeAndSimplifyClassCheck(condition)) {
1387 return;
1388 }
1389 }
1390
Anton Shaminbdd79352016-02-15 12:48:36 +06001391 // Reverse condition if left is constant. Our code generators prefer constant
1392 // on the right hand side.
1393 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1394 HBasicBlock* block = condition->GetBlock();
1395 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1396 // If it is a fp we must set the opposite bias.
1397 if (replacement != nullptr) {
1398 if (condition->IsLtBias()) {
1399 replacement->SetBias(ComparisonBias::kGtBias);
1400 } else if (condition->IsGtBias()) {
1401 replacement->SetBias(ComparisonBias::kLtBias);
1402 }
1403 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1404 RecordSimplification();
1405
1406 condition = replacement;
1407 }
1408 }
Mark Mendellc4701932015-04-10 13:18:51 -04001409
Mark Mendellc4701932015-04-10 13:18:51 -04001410 HInstruction* left = condition->GetLeft();
1411 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001412
1413 // Try to fold an HCompare into this HCondition.
1414
Mark Mendellc4701932015-04-10 13:18:51 -04001415 // We can only replace an HCondition which compares a Compare to 0.
1416 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1417 // condition with a long, float or double comparison as input.
1418 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1419 // Conversion is not possible.
1420 return;
1421 }
1422
1423 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001424 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001425 // Someone else also wants the result of the compare.
1426 return;
1427 }
1428
Vladimir Marko46817b82016-03-29 12:21:58 +01001429 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001430 // There is a reference to the compare result in an environment. Do we really need it?
1431 if (GetGraph()->IsDebuggable()) {
1432 return;
1433 }
1434
1435 // We have to ensure that there are no deopt points in the sequence.
1436 if (left->HasAnyEnvironmentUseBefore(condition)) {
1437 return;
1438 }
1439 }
1440
1441 // Clean up any environment uses from the HCompare, if any.
1442 left->RemoveEnvironmentUsers();
1443
1444 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1445 condition->SetBias(left->AsCompare()->GetBias());
1446
1447 // Replace the operands of the HCondition.
1448 condition->ReplaceInput(left->InputAt(0), 0);
1449 condition->ReplaceInput(left->InputAt(1), 1);
1450
1451 // Remove the HCompare.
1452 left->GetBlock()->RemoveInstruction(left);
1453
1454 RecordSimplification();
1455}
1456
Andreas Gampe9186ced2016-12-12 14:28:21 -08001457// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1458static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1459 // True, if the most significant bits of divisor are 0.
1460 return ((divisor & 0x7fffff) == 0);
1461}
1462
1463// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1464static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1465 // True, if the most significant bits of divisor are 0.
1466 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1467}
1468
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001469void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1470 HConstant* input_cst = instruction->GetConstantRight();
1471 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001473
1474 if ((input_cst != nullptr) && input_cst->IsOne()) {
1475 // Replace code looking like
1476 // DIV dst, src, 1
1477 // with
1478 // src
1479 instruction->ReplaceWith(input_other);
1480 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001481 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001482 return;
1483 }
1484
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001485 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001486 // Replace code looking like
1487 // DIV dst, src, -1
1488 // with
1489 // NEG dst, src
1490 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001491 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001492 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001493 return;
1494 }
1495
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001496 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001497 // Try replacing code looking like
1498 // DIV dst, src, constant
1499 // with
1500 // MUL dst, src, 1 / constant
1501 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001502 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001503 double value = input_cst->AsDoubleConstant()->GetValue();
1504 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1505 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1506 }
1507 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001508 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001509 float value = input_cst->AsFloatConstant()->GetValue();
1510 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1511 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1512 }
1513 }
1514
1515 if (reciprocal != nullptr) {
1516 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1517 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1518 RecordSimplification();
1519 return;
1520 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001521 }
1522}
1523
1524void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1525 HConstant* input_cst = instruction->GetConstantRight();
1526 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001527 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001528 HBasicBlock* block = instruction->GetBlock();
1529 ArenaAllocator* allocator = GetGraph()->GetArena();
1530
1531 if (input_cst == nullptr) {
1532 return;
1533 }
1534
1535 if (input_cst->IsOne()) {
1536 // Replace code looking like
1537 // MUL dst, src, 1
1538 // with
1539 // src
1540 instruction->ReplaceWith(input_other);
1541 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001542 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001543 return;
1544 }
1545
1546 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001547 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001548 // Replace code looking like
1549 // MUL dst, src, -1
1550 // with
1551 // NEG dst, src
1552 HNeg* neg = new (allocator) HNeg(type, input_other);
1553 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001554 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001555 return;
1556 }
1557
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001558 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001559 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1560 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1561 // Replace code looking like
1562 // FP_MUL dst, src, 2.0
1563 // with
1564 // FP_ADD dst, src, src
1565 // The 'int' and 'long' cases are handled below.
1566 block->ReplaceAndRemoveInstructionWith(instruction,
1567 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001568 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001569 return;
1570 }
1571
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001573 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001574 // Even though constant propagation also takes care of the zero case, other
1575 // optimizations can lead to having a zero multiplication.
1576 if (factor == 0) {
1577 // Replace code looking like
1578 // MUL dst, src, 0
1579 // with
1580 // 0
1581 instruction->ReplaceWith(input_cst);
1582 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001583 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001584 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001585 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001586 // Replace code looking like
1587 // MUL dst, src, pow_of_2
1588 // with
1589 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001590 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001591 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001592 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001593 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001594 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001595 } else if (IsPowerOfTwo(factor - 1)) {
1596 // Transform code looking like
1597 // MUL dst, src, (2^n + 1)
1598 // into
1599 // SHL tmp, src, n
1600 // ADD dst, src, tmp
1601 HShl* shl = new (allocator) HShl(type,
1602 input_other,
1603 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1604 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1605
1606 block->InsertInstructionBefore(shl, instruction);
1607 block->ReplaceAndRemoveInstructionWith(instruction, add);
1608 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001609 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001610 } else if (IsPowerOfTwo(factor + 1)) {
1611 // Transform code looking like
1612 // MUL dst, src, (2^n - 1)
1613 // into
1614 // SHL tmp, src, n
1615 // SUB dst, tmp, src
1616 HShl* shl = new (allocator) HShl(type,
1617 input_other,
1618 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1619 HSub* sub = new (allocator) HSub(type, shl, input_other);
1620
1621 block->InsertInstructionBefore(shl, instruction);
1622 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1623 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001624 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001625 }
1626 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001627
1628 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1629 // so no need to return.
1630 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001631}
1632
Alexandre Rames188d4312015-04-09 18:30:21 +01001633void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1634 HInstruction* input = instruction->GetInput();
1635 if (input->IsNeg()) {
1636 // Replace code looking like
1637 // NEG tmp, src
1638 // NEG dst, tmp
1639 // with
1640 // src
1641 HNeg* previous_neg = input->AsNeg();
1642 instruction->ReplaceWith(previous_neg->GetInput());
1643 instruction->GetBlock()->RemoveInstruction(instruction);
1644 // We perform the optimization even if the input negation has environment
1645 // uses since it allows removing the current instruction. But we only delete
1646 // the input negation only if it is does not have any uses left.
1647 if (!previous_neg->HasUses()) {
1648 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1649 }
1650 RecordSimplification();
1651 return;
1652 }
1653
Serguei Katkov339dfc22015-04-20 12:29:32 +06001654 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001655 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001656 // Replace code looking like
1657 // SUB tmp, a, b
1658 // NEG dst, tmp
1659 // with
1660 // SUB dst, b, a
1661 // We do not perform the optimization if the input subtraction has
1662 // environment uses or multiple non-environment uses as it could lead to
1663 // worse code. In particular, we do not want the live ranges of `a` and `b`
1664 // to be extended if we are not sure the initial 'SUB' instruction can be
1665 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001666 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001667 HSub* sub = input->AsSub();
1668 HSub* new_sub =
1669 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1670 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1671 if (!sub->HasUses()) {
1672 sub->GetBlock()->RemoveInstruction(sub);
1673 }
1674 RecordSimplification();
1675 }
1676}
1677
1678void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1679 HInstruction* input = instruction->GetInput();
1680 if (input->IsNot()) {
1681 // Replace code looking like
1682 // NOT tmp, src
1683 // NOT dst, tmp
1684 // with
1685 // src
1686 // We perform the optimization even if the input negation has environment
1687 // uses since it allows removing the current instruction. But we only delete
1688 // the input negation only if it is does not have any uses left.
1689 HNot* previous_not = input->AsNot();
1690 instruction->ReplaceWith(previous_not->GetInput());
1691 instruction->GetBlock()->RemoveInstruction(instruction);
1692 if (!previous_not->HasUses()) {
1693 previous_not->GetBlock()->RemoveInstruction(previous_not);
1694 }
1695 RecordSimplification();
1696 }
1697}
1698
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001699void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1700 HConstant* input_cst = instruction->GetConstantRight();
1701 HInstruction* input_other = instruction->GetLeastConstantLeft();
1702
Roland Levillain1a653882016-03-18 18:05:57 +00001703 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001704 // Replace code looking like
1705 // OR dst, src, 0
1706 // with
1707 // src
1708 instruction->ReplaceWith(input_other);
1709 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001710 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001711 return;
1712 }
1713
1714 // We assume that GVN has run before, so we only perform a pointer comparison.
1715 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001716 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001717 if (instruction->GetLeft() == instruction->GetRight()) {
1718 // Replace code looking like
1719 // OR dst, src, src
1720 // with
1721 // src
1722 instruction->ReplaceWith(instruction->GetLeft());
1723 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001724 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001725 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001726 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001727
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001728 if (TryDeMorganNegationFactoring(instruction)) return;
1729
Anton Kirilove14dc862016-05-13 17:56:15 +01001730 if (TryReplaceWithRotate(instruction)) {
1731 return;
1732 }
1733
1734 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1735 // so no need to return.
1736 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001737}
1738
1739void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1740 VisitShift(instruction);
1741}
1742
1743void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1744 VisitShift(instruction);
1745}
1746
1747void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1748 HConstant* input_cst = instruction->GetConstantRight();
1749 HInstruction* input_other = instruction->GetLeastConstantLeft();
1750
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001751 DataType::Type type = instruction->GetType();
1752 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001753 return;
1754 }
1755
Roland Levillain1a653882016-03-18 18:05:57 +00001756 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001757 // Replace code looking like
1758 // SUB dst, src, 0
1759 // with
1760 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001761 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1762 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1763 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001764 instruction->ReplaceWith(input_other);
1765 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001766 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001767 return;
1768 }
1769
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001770 HBasicBlock* block = instruction->GetBlock();
1771 ArenaAllocator* allocator = GetGraph()->GetArena();
1772
Alexandre Rames188d4312015-04-09 18:30:21 +01001773 HInstruction* left = instruction->GetLeft();
1774 HInstruction* right = instruction->GetRight();
1775 if (left->IsConstant()) {
1776 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001777 // Replace code looking like
1778 // SUB dst, 0, src
1779 // with
1780 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001781 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001782 // `x` is `0.0`, the former expression yields `0.0`, while the later
1783 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001784 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001785 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001786 RecordSimplification();
1787 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001788 }
1789 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001790
1791 if (left->IsNeg() && right->IsNeg()) {
1792 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1793 return;
1794 }
1795 }
1796
1797 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1798 // Replace code looking like
1799 // NEG tmp, b
1800 // SUB dst, a, tmp
1801 // with
1802 // ADD dst, a, b
1803 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1804 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1805 RecordSimplification();
1806 right->GetBlock()->RemoveInstruction(right);
1807 return;
1808 }
1809
1810 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1811 // Replace code looking like
1812 // NEG tmp, a
1813 // SUB dst, tmp, b
1814 // with
1815 // ADD tmp, a, b
1816 // NEG dst, tmp
1817 // The second version is not intrinsically better, but enables more
1818 // transformations.
1819 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1820 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1821 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1822 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1823 instruction->ReplaceWith(neg);
1824 instruction->GetBlock()->RemoveInstruction(instruction);
1825 RecordSimplification();
1826 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001827 return;
1828 }
1829
1830 if (TrySubtractionChainSimplification(instruction)) {
1831 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001832 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001833
1834 if (left->IsAdd()) {
1835 // Replace code patterns looking like
1836 // ADD dst1, x, y ADD dst1, x, y
1837 // SUB dst2, dst1, y SUB dst2, dst1, x
1838 // with
1839 // ADD dst1, x, y
1840 // SUB instruction is not needed in this case, we may use
1841 // one of inputs of ADD instead.
1842 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001843 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001844 if (left->InputAt(1) == right) {
1845 instruction->ReplaceWith(left->InputAt(0));
1846 RecordSimplification();
1847 instruction->GetBlock()->RemoveInstruction(instruction);
1848 return;
1849 } else if (left->InputAt(0) == right) {
1850 instruction->ReplaceWith(left->InputAt(1));
1851 RecordSimplification();
1852 instruction->GetBlock()->RemoveInstruction(instruction);
1853 return;
1854 }
1855 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001856}
1857
1858void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1859 VisitShift(instruction);
1860}
1861
1862void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1863 HConstant* input_cst = instruction->GetConstantRight();
1864 HInstruction* input_other = instruction->GetLeastConstantLeft();
1865
Roland Levillain1a653882016-03-18 18:05:57 +00001866 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001867 // Replace code looking like
1868 // XOR dst, src, 0
1869 // with
1870 // src
1871 instruction->ReplaceWith(input_other);
1872 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001873 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001874 return;
1875 }
1876
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001877 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001878 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001879 // Replace code looking like
1880 // XOR dst, src, 1
1881 // with
1882 // BOOLEAN_NOT dst, src
1883 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1884 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1885 RecordSimplification();
1886 return;
1887 }
1888
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001889 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1890 // Replace code looking like
1891 // XOR dst, src, 0xFFF...FF
1892 // with
1893 // NOT dst, src
1894 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1895 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001896 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001897 return;
1898 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001899
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001900 HInstruction* left = instruction->GetLeft();
1901 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001902 if (((left->IsNot() && right->IsNot()) ||
1903 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001904 left->HasOnlyOneNonEnvironmentUse() &&
1905 right->HasOnlyOneNonEnvironmentUse()) {
1906 // Replace code looking like
1907 // NOT nota, a
1908 // NOT notb, b
1909 // XOR dst, nota, notb
1910 // with
1911 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001912 instruction->ReplaceInput(left->InputAt(0), 0);
1913 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001914 left->GetBlock()->RemoveInstruction(left);
1915 right->GetBlock()->RemoveInstruction(right);
1916 RecordSimplification();
1917 return;
1918 }
1919
Anton Kirilove14dc862016-05-13 17:56:15 +01001920 if (TryReplaceWithRotate(instruction)) {
1921 return;
1922 }
1923
1924 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1925 // so no need to return.
1926 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001927}
1928
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001929void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1930 HInstruction* argument = instruction->InputAt(1);
1931 HInstruction* receiver = instruction->InputAt(0);
1932 if (receiver == argument) {
1933 // Because String.equals is an instance call, the receiver is
1934 // a null check if we don't know it's null. The argument however, will
1935 // be the actual object. So we cannot end up in a situation where both
1936 // are equal but could be null.
1937 DCHECK(CanEnsureNotNullAt(argument, instruction));
1938 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1939 instruction->GetBlock()->RemoveInstruction(instruction);
1940 } else {
1941 StringEqualsOptimizations optimizations(instruction);
1942 if (CanEnsureNotNullAt(argument, instruction)) {
1943 optimizations.SetArgumentNotNull();
1944 }
1945 ScopedObjectAccess soa(Thread::Current());
1946 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1947 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1948 optimizations.SetArgumentIsString();
1949 }
1950 }
1951}
1952
Roland Levillain22c49222016-03-18 14:04:28 +00001953void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1954 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001955 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001956 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001957 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001958 HInstruction* value = invoke->InputAt(0);
1959 HInstruction* distance = invoke->InputAt(1);
1960 // Replace the invoke with an HRor.
1961 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001962 // Unconditionally set the type of the negated distance to `int`,
1963 // as shift and rotate operations expect a 32-bit (or narrower)
1964 // value for their distance input.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001965 distance = new (GetGraph()->GetArena()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001966 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1967 }
Roland Levillain22c49222016-03-18 14:04:28 +00001968 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001969 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1970 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001971 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001972 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1973 clinit->GetBlock()->RemoveInstruction(clinit);
1974 HInstruction* ldclass = clinit->InputAt(0);
1975 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1976 ldclass->GetBlock()->RemoveInstruction(ldclass);
1977 }
1978 }
1979}
1980
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001981static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1982 if (potential_length->IsArrayLength()) {
1983 return potential_length->InputAt(0) == potential_array;
1984 }
1985
1986 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001987 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001988 }
1989
1990 return false;
1991}
1992
1993void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1994 HInstruction* source = instruction->InputAt(0);
1995 HInstruction* destination = instruction->InputAt(2);
1996 HInstruction* count = instruction->InputAt(4);
1997 SystemArrayCopyOptimizations optimizations(instruction);
1998 if (CanEnsureNotNullAt(source, instruction)) {
1999 optimizations.SetSourceIsNotNull();
2000 }
2001 if (CanEnsureNotNullAt(destination, instruction)) {
2002 optimizations.SetDestinationIsNotNull();
2003 }
2004 if (destination == source) {
2005 optimizations.SetDestinationIsSource();
2006 }
2007
2008 if (IsArrayLengthOf(count, source)) {
2009 optimizations.SetCountIsSourceLength();
2010 }
2011
2012 if (IsArrayLengthOf(count, destination)) {
2013 optimizations.SetCountIsDestinationLength();
2014 }
2015
2016 {
2017 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002018 DataType::Type source_component_type = DataType::Type::kVoid;
2019 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002020 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2021 if (destination_rti.IsValid()) {
2022 if (destination_rti.IsObjectArray()) {
2023 if (destination_rti.IsExact()) {
2024 optimizations.SetDoesNotNeedTypeCheck();
2025 }
2026 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002027 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002028 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002029 destination_component_type = DataTypeFromPrimitive(
2030 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002031 optimizations.SetDestinationIsPrimitiveArray();
2032 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2033 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002034 }
2035 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002036 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2037 if (source_rti.IsValid()) {
2038 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2039 optimizations.SetDoesNotNeedTypeCheck();
2040 }
2041 if (source_rti.IsPrimitiveArrayClass()) {
2042 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002043 source_component_type = DataTypeFromPrimitive(
2044 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002045 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2046 optimizations.SetSourceIsNonPrimitiveArray();
2047 }
2048 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002049 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002050 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002051 (source_component_type == destination_component_type)) {
2052 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2053 PointerSize image_size = class_linker->GetImagePointerSize();
2054 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2055 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2056 ArtMethod* method = nullptr;
2057 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002058 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002059 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002060 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002061 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002062 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002063 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002064 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002065 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002066 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002067 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002068 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002069 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002070 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002071 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002072 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002073 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002074 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002075 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002076 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002077 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002078 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002079 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002080 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002081 break;
2082 default:
2083 LOG(FATAL) << "Unreachable";
2084 }
2085 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002086 DCHECK(method->IsStatic());
2087 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002088 invoke->SetResolvedMethod(method);
2089 // Sharpen the new invoke. Note that we do not update the dex method index of
2090 // the invoke, as we would need to look it up in the current dex file, and it
2091 // is unlikely that it exists. The most usual situation for such typed
2092 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002093 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002094 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002095 }
2096}
2097
Roland Levillaina5c4a402016-03-15 15:02:50 +00002098void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2099 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002100 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002101 DCHECK(invoke->IsInvokeStaticOrDirect());
2102 uint32_t dex_pc = invoke->GetDexPc();
2103 HInstruction* left = invoke->InputAt(0);
2104 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002105 if (!is_signum) {
2106 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002107 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002108 right = GetGraph()->GetLongConstant(0);
2109 } else {
2110 right = GetGraph()->GetIntConstant(0);
2111 }
2112 HCompare* compare = new (GetGraph()->GetArena())
2113 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2114 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2115}
2116
Aart Bik75a38b22016-02-17 10:41:50 -08002117void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2118 DCHECK(invoke->IsInvokeStaticOrDirect());
2119 uint32_t dex_pc = invoke->GetDexPc();
2120 // IsNaN(x) is the same as x != x.
2121 HInstruction* x = invoke->InputAt(0);
2122 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002123 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002124 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2125}
2126
Aart Bik2a6aad92016-02-25 11:32:32 -08002127void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2128 DCHECK(invoke->IsInvokeStaticOrDirect());
2129 uint32_t dex_pc = invoke->GetDexPc();
2130 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002131 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002132 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2133 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002134 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002135 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2136 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2137 kNeedsEnvironmentOrCache,
2138 kNoSideEffects,
2139 kNoThrow);
2140 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002141 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002142 nan = GetGraph()->GetIntConstant(0x7fc00000);
2143 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2144 kNeedsEnvironmentOrCache,
2145 kNoSideEffects,
2146 kNoThrow);
2147 }
2148 // Test IsNaN(x), which is the same as x != x.
2149 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
2150 condition->SetBias(ComparisonBias::kLtBias);
2151 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2152 // Select between the two.
2153 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
2154 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2155 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2156}
2157
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002158void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2159 HInstruction* str = invoke->InputAt(0);
2160 HInstruction* index = invoke->InputAt(1);
2161 uint32_t dex_pc = invoke->GetDexPc();
2162 ArenaAllocator* arena = GetGraph()->GetArena();
2163 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2164 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2165 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2166 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002167 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2168 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002169 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002170 HArrayGet* array_get = new (arena) HArrayGet(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002171 str, bounds_check, DataType::Type::kUint16, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002172 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2173 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2174 GetGraph()->SetHasBoundsChecks(true);
2175}
2176
Vladimir Markodce016e2016-04-28 13:10:02 +01002177void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2178 HInstruction* str = invoke->InputAt(0);
2179 uint32_t dex_pc = invoke->GetDexPc();
2180 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2181 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002182 HArrayLength* length =
2183 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002184 HInstruction* replacement;
2185 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2186 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2187 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2188 HIntConstant* zero = GetGraph()->GetIntConstant(0);
2189 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
2190 replacement = equal;
2191 } else {
2192 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2193 replacement = length;
2194 }
2195 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2196}
2197
Aart Bikff7d89c2016-11-07 08:49:28 -08002198// This method should only be used on intrinsics whose sole way of throwing an
2199// exception is raising a NPE when the nth argument is null. If that argument
2200// is provably non-null, we can clear the flag.
2201void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2202 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002203 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002204 invoke->SetCanThrow(false);
2205 }
2206}
2207
Aart Bik71bf7b42016-11-16 10:17:46 -08002208// Methods that return "this" can replace the returned value with the receiver.
2209void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2210 if (invoke->HasUses()) {
2211 HInstruction* receiver = invoke->InputAt(0);
2212 invoke->ReplaceWith(receiver);
2213 RecordSimplification();
2214 }
2215}
2216
2217// Helper method for StringBuffer escape analysis.
2218static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2219 if (user->IsInvokeStaticOrDirect()) {
2220 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002221 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2222 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002223 user->InputAt(0) == reference;
2224 } else if (user->IsInvokeVirtual()) {
2225 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2226 case Intrinsics::kStringBufferLength:
2227 case Intrinsics::kStringBufferToString:
2228 DCHECK_EQ(user->InputAt(0), reference);
2229 return true;
2230 case Intrinsics::kStringBufferAppend:
2231 // Returns "this", so only okay if no further uses.
2232 DCHECK_EQ(user->InputAt(0), reference);
2233 DCHECK_NE(user->InputAt(1), reference);
2234 return !user->HasUses();
2235 default:
2236 break;
2237 }
2238 }
2239 return false;
2240}
2241
2242// Certain allocation intrinsics are not removed by dead code elimination
2243// because of potentially throwing an OOM exception or other side effects.
2244// This method removes such intrinsics when special circumstances allow.
2245void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2246 if (!invoke->HasUses()) {
2247 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2248 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2249 // call does not escape since only thread-local synchronization may be removed.
2250 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2251 HInstruction* receiver = invoke->InputAt(0);
2252 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2253 invoke->GetBlock()->RemoveInstruction(invoke);
2254 RecordSimplification();
2255 }
2256 }
2257}
2258
Aart Bik11932592016-03-08 12:42:25 -08002259void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2260 uint32_t dex_pc = invoke->GetDexPc();
2261 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2262 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2263}
2264
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002265void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002266 switch (instruction->GetIntrinsic()) {
2267 case Intrinsics::kStringEquals:
2268 SimplifyStringEquals(instruction);
2269 break;
2270 case Intrinsics::kSystemArrayCopy:
2271 SimplifySystemArrayCopy(instruction);
2272 break;
2273 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002274 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002275 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002276 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002277 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002278 break;
2279 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002280 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002281 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002282 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002283 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002284 break;
2285 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002286 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002287 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002288 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002289 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002290 break;
2291 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002292 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002293 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002294 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002295 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002296 break;
2297 case Intrinsics::kFloatIsNaN:
2298 case Intrinsics::kDoubleIsNaN:
2299 SimplifyIsNaN(instruction);
2300 break;
2301 case Intrinsics::kFloatFloatToIntBits:
2302 case Intrinsics::kDoubleDoubleToLongBits:
2303 SimplifyFP2Int(instruction);
2304 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002305 case Intrinsics::kStringCharAt:
2306 SimplifyStringCharAt(instruction);
2307 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002308 case Intrinsics::kStringIsEmpty:
2309 case Intrinsics::kStringLength:
2310 SimplifyStringIsEmptyOrLength(instruction);
2311 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002312 case Intrinsics::kStringStringIndexOf:
2313 case Intrinsics::kStringStringIndexOfAfter:
2314 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2315 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002316 case Intrinsics::kStringBufferAppend:
2317 case Intrinsics::kStringBuilderAppend:
2318 SimplifyReturnThis(instruction);
2319 break;
2320 case Intrinsics::kStringBufferToString:
2321 case Intrinsics::kStringBuilderToString:
2322 SimplifyAllocationIntrinsic(instruction);
2323 break;
Aart Bik11932592016-03-08 12:42:25 -08002324 case Intrinsics::kUnsafeLoadFence:
2325 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2326 break;
2327 case Intrinsics::kUnsafeStoreFence:
2328 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2329 break;
2330 case Intrinsics::kUnsafeFullFence:
2331 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2332 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002333 case Intrinsics::kVarHandleFullFence:
2334 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2335 break;
2336 case Intrinsics::kVarHandleAcquireFence:
2337 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2338 break;
2339 case Intrinsics::kVarHandleReleaseFence:
2340 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2341 break;
2342 case Intrinsics::kVarHandleLoadLoadFence:
2343 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2344 break;
2345 case Intrinsics::kVarHandleStoreStoreFence:
2346 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2347 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002348 default:
2349 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002350 }
2351}
2352
Aart Bikbb245d12015-10-19 11:05:03 -07002353void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2354 HInstruction* cond = deoptimize->InputAt(0);
2355 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002356 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002357 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002358 if (deoptimize->GuardsAnInput()) {
2359 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2360 }
Aart Bikbb245d12015-10-19 11:05:03 -07002361 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2362 } else {
2363 // Always deopt.
2364 }
2365 }
2366}
2367
Anton Kirilove14dc862016-05-13 17:56:15 +01002368// Replace code looking like
2369// OP y, x, const1
2370// OP z, y, const2
2371// with
2372// OP z, x, const3
2373// where OP is both an associative and a commutative operation.
2374bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2375 HBinaryOperation* instruction) {
2376 DCHECK(instruction->IsCommutative());
2377
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002378 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002379 return false;
2380 }
2381
2382 HInstruction* left = instruction->GetLeft();
2383 HInstruction* right = instruction->GetRight();
2384 // Variable names as described above.
2385 HConstant* const2;
2386 HBinaryOperation* y;
2387
2388 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2389 const2 = right->AsConstant();
2390 y = left->AsBinaryOperation();
2391 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2392 const2 = left->AsConstant();
2393 y = right->AsBinaryOperation();
2394 } else {
2395 // The node does not match the pattern.
2396 return false;
2397 }
2398
2399 // If `y` has more than one use, we do not perform the optimization
2400 // because it might increase code size (e.g. if the new constant is
2401 // no longer encodable as an immediate operand in the target ISA).
2402 if (!y->HasOnlyOneNonEnvironmentUse()) {
2403 return false;
2404 }
2405
2406 // GetConstantRight() can return both left and right constants
2407 // for commutative operations.
2408 HConstant* const1 = y->GetConstantRight();
2409 if (const1 == nullptr) {
2410 return false;
2411 }
2412
2413 instruction->ReplaceInput(const1, 0);
2414 instruction->ReplaceInput(const2, 1);
2415 HConstant* const3 = instruction->TryStaticEvaluation();
2416 DCHECK(const3 != nullptr);
2417 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2418 instruction->ReplaceInput(const3, 1);
2419 RecordSimplification();
2420 return true;
2421}
2422
2423static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2424 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2425}
2426
2427// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002428static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002429 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002430 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002431 return HAdd::Compute<int32_t>(x, y);
2432 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002433 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002434 return HAdd::Compute<int64_t>(x, y);
2435 }
2436}
2437
2438// Helper function that handles the child classes of HConstant
2439// and returns an integer with the appropriate sign.
2440static int64_t GetValue(HConstant* constant, bool is_negated) {
2441 int64_t ret = Int64FromConstant(constant);
2442 return is_negated ? -ret : ret;
2443}
2444
2445// Replace code looking like
2446// OP1 y, x, const1
2447// OP2 z, y, const2
2448// with
2449// OP3 z, x, const3
2450// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2451bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2452 HBinaryOperation* instruction) {
2453 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2454
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002455 DataType::Type type = instruction->GetType();
2456 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002457 return false;
2458 }
2459
2460 HInstruction* left = instruction->GetLeft();
2461 HInstruction* right = instruction->GetRight();
2462 // Variable names as described above.
2463 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2464 if (const2 == nullptr) {
2465 return false;
2466 }
2467
2468 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2469 ? left->AsBinaryOperation()
2470 : AsAddOrSub(right);
2471 // If y has more than one use, we do not perform the optimization because
2472 // it might increase code size (e.g. if the new constant is no longer
2473 // encodable as an immediate operand in the target ISA).
2474 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2475 return false;
2476 }
2477
2478 left = y->GetLeft();
2479 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2480 if (const1 == nullptr) {
2481 return false;
2482 }
2483
2484 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2485 // If both inputs are constants, let the constant folding pass deal with it.
2486 if (x->IsConstant()) {
2487 return false;
2488 }
2489
2490 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2491 int64_t const2_val = GetValue(const2, is_const2_negated);
2492 bool is_y_negated = (y == right) && instruction->IsSub();
2493 right = y->GetRight();
2494 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2495 int64_t const1_val = GetValue(const1, is_const1_negated);
2496 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2497 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2498 HBasicBlock* block = instruction->GetBlock();
2499 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2500 ArenaAllocator* arena = instruction->GetArena();
2501 HInstruction* z;
2502
2503 if (is_x_negated) {
2504 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2505 } else {
2506 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2507 }
2508
2509 block->ReplaceAndRemoveInstructionWith(instruction, z);
2510 RecordSimplification();
2511 return true;
2512}
2513
Lena Djokicbc5460b2017-07-20 16:07:36 +02002514void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2515 if (TryCombineVecMultiplyAccumulate(instruction)) {
2516 RecordSimplification();
2517 }
2518}
2519
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002520} // namespace art