blob: 36ff2a9ac35667bec5250419ac2dd3d081b0fb98 [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 Markod5d2f2c2017-09-26 12:37:26 +0100254 if (!(type == DataType::Type::kUint8 ||
255 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100256 type == DataType::Type::kUint16 ||
257 type == DataType::Type::kInt16 ||
258 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200259 return false;
260 }
261 break;
262 case kMips:
263 case kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 if (!(type == DataType::Type::kUint8 ||
265 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 type == DataType::Type::kUint16 ||
267 type == DataType::Type::kInt16 ||
268 type == DataType::Type::kInt32 ||
269 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200270 return false;
271 }
272 break;
273 default:
274 return false;
275 }
276
277 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetArena();
278
279 if (mul->HasOnlyOneNonEnvironmentUse()) {
280 HInstruction* use = mul->GetUses().front().GetUser();
281 if (use->IsVecAdd() || use->IsVecSub()) {
282 // Replace code looking like
283 // VECMUL tmp, x, y
284 // VECADD/SUB dst, acc, tmp
285 // with
286 // VECMULACC dst, acc, x, y
287 // Note that we do not want to (unconditionally) perform the merge when the
288 // multiplication has multiple uses and it can be merged in all of them.
289 // Multiple uses could happen on the same control-flow path, and we would
290 // then increase the amount of work. In the future we could try to evaluate
291 // whether all uses are on different control-flow paths (using dominance and
292 // reverse-dominance information) and only perform the merge when they are.
293 HInstruction* accumulator = nullptr;
294 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
295 HInstruction* binop_left = binop->GetLeft();
296 HInstruction* binop_right = binop->GetRight();
297 // This is always true since the `HVecMul` has only one use (which is checked above).
298 DCHECK_NE(binop_left, binop_right);
299 if (binop_right == mul) {
300 accumulator = binop_left;
301 } else if (use->IsVecAdd()) {
302 DCHECK_EQ(binop_left, mul);
303 accumulator = binop_right;
304 }
305
306 HInstruction::InstructionKind kind =
307 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
308 if (accumulator != nullptr) {
309 HVecMultiplyAccumulate* mulacc =
310 new (arena) HVecMultiplyAccumulate(arena,
311 kind,
312 accumulator,
313 mul->GetLeft(),
314 mul->GetRight(),
315 binop->GetPackedType(),
316 binop->GetVectorLength());
317
318 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
319 DCHECK(!mul->HasUses());
320 mul->GetBlock()->RemoveInstruction(mul);
321 return true;
322 }
323 }
324 }
325
326 return false;
327}
328
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000329void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
330 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100331 HInstruction* shift_amount = instruction->GetRight();
332 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000333
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100334 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100335 ? kMaxLongShiftDistance
336 : kMaxIntShiftDistance;
337
338 if (shift_amount->IsConstant()) {
339 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700340 int64_t masked_cst = cst & implicit_mask;
341 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400342 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100343 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400344 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100345 // value
346 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400347 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100348 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100349 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700350 } else if (masked_cst != cst) {
351 // Replace code looking like
352 // SHL dst, value, cst
353 // where cst exceeds maximum distance with the equivalent
354 // SHL dst, value, cst & implicit_mask
355 // (as defined by shift semantics). This ensures other
356 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100357 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700358 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
359 RecordSimplification();
360 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100361 }
362 }
363
364 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100365 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
366 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100367 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100368 // AND adjusted_shift, shift, <superset of implicit mask>
369 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
370 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
371 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100372 // with
373 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100374 if (shift_amount->IsAnd() ||
375 shift_amount->IsOr() ||
376 shift_amount->IsXor() ||
377 shift_amount->IsAdd() ||
378 shift_amount->IsSub()) {
379 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
380 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
381 HConstant* mask = bin_op->GetConstantRight();
382 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
383 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100384 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100385 return;
386 }
387 } else if (shift_amount->IsTypeConversion()) {
388 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
389 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
390 // Non-integral and 64-bit source types require an explicit type conversion.
391 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
392 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
393 RecordSimplification();
394 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400395 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000396 }
397}
398
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000399static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
400 return (sub->GetRight() == other &&
401 sub->GetLeft()->IsConstant() &&
402 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
403}
404
405bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
406 HUShr* ushr,
407 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000408 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
409 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000410 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
411 if (!ushr->HasUses()) {
412 ushr->GetBlock()->RemoveInstruction(ushr);
413 }
414 if (!ushr->GetRight()->HasUses()) {
415 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
416 }
417 if (!shl->HasUses()) {
418 shl->GetBlock()->RemoveInstruction(shl);
419 }
420 if (!shl->GetRight()->HasUses()) {
421 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
422 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100423 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000424 return true;
425}
426
427// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
428bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000429 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
430 HInstruction* left = op->GetLeft();
431 HInstruction* right = op->GetRight();
432 // If we have an UShr and a Shl (in either order).
433 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
434 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
435 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100436 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000437 if (ushr->GetType() == shl->GetType() &&
438 ushr->GetLeft() == shl->GetLeft()) {
439 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
440 // Shift distances are both constant, try replacing with Ror if they
441 // add up to the register size.
442 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
443 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
444 // Shift distances are potentially of the form x and (reg_size - x).
445 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
446 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
447 // Shift distances are potentially of the form d and -d.
448 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
449 }
450 }
451 }
452 return false;
453}
454
455// Try replacing code looking like (x >>> #rdist OP x << #ldist):
456// UShr dst, x, #rdist
457// Shl tmp, x, #ldist
458// OP dst, dst, tmp
459// or like (x >>> #rdist OP x << #-ldist):
460// UShr dst, x, #rdist
461// Shl tmp, x, #-ldist
462// OP dst, dst, tmp
463// with
464// Ror dst, x, #rdist
465bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
466 HUShr* ushr,
467 HShl* shl) {
468 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100469 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000470 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
471 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
472 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
473 ReplaceRotateWithRor(op, ushr, shl);
474 return true;
475 }
476 return false;
477}
478
479// Replace code looking like (x >>> -d OP x << d):
480// Neg neg, d
481// UShr dst, x, neg
482// Shl tmp, x, d
483// OP dst, dst, tmp
484// with
485// Neg neg, d
486// Ror dst, x, neg
487// *** OR ***
488// Replace code looking like (x >>> d OP x << -d):
489// UShr dst, x, d
490// Neg neg, d
491// Shl tmp, x, neg
492// OP dst, dst, tmp
493// with
494// Ror dst, x, d
495bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
496 HUShr* ushr,
497 HShl* shl) {
498 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
499 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
500 bool neg_is_left = shl->GetRight()->IsNeg();
501 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
502 // And the shift distance being negated is the distance being shifted the other way.
503 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
504 ReplaceRotateWithRor(op, ushr, shl);
505 }
506 return false;
507}
508
509// Try replacing code looking like (x >>> d OP x << (#bits - d)):
510// UShr dst, x, d
511// Sub ld, #bits, d
512// Shl tmp, x, ld
513// OP dst, dst, tmp
514// with
515// Ror dst, x, d
516// *** OR ***
517// Replace code looking like (x >>> (#bits - d) OP x << d):
518// Sub rd, #bits, d
519// UShr dst, x, rd
520// Shl tmp, x, d
521// OP dst, dst, tmp
522// with
523// Neg neg, d
524// Ror dst, x, neg
525bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
526 HUShr* ushr,
527 HShl* shl) {
528 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
529 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100530 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000531 HInstruction* shl_shift = shl->GetRight();
532 HInstruction* ushr_shift = ushr->GetRight();
533 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
534 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
535 return ReplaceRotateWithRor(op, ushr, shl);
536 }
537 return false;
538}
539
Calin Juravle10e244f2015-01-26 18:54:32 +0000540void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
541 HInstruction* obj = null_check->InputAt(0);
542 if (!obj->CanBeNull()) {
543 null_check->ReplaceWith(obj);
544 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000545 if (stats_ != nullptr) {
546 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
547 }
548 }
549}
550
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100551bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
552 if (!input->CanBeNull()) {
553 return true;
554 }
555
Vladimir Marko46817b82016-03-29 12:21:58 +0100556 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
557 HInstruction* user = use.GetUser();
558 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100559 return true;
560 }
561 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100562
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100563 return false;
564}
565
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100566// Returns whether doing a type test between the class of `object` against `klass` has
567// a statically known outcome. The result of the test is stored in `outcome`.
568static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000569 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
570 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
571 ScopedObjectAccess soa(Thread::Current());
572 if (!obj_rti.IsValid()) {
573 // We run the simplifier before the reference type propagation so type info might not be
574 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100575 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000576 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100578 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100579 if (!class_rti.IsValid()) {
580 // Happens when the loaded class is unresolved.
581 return false;
582 }
583 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000584 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100585 *outcome = true;
586 return true;
587 } else if (obj_rti.IsExact()) {
588 // The test failed at compile time so will also fail at runtime.
589 *outcome = false;
590 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100591 } else if (!class_rti.IsInterface()
592 && !obj_rti.IsInterface()
593 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100594 // Different type hierarchy. The test will fail.
595 *outcome = false;
596 return true;
597 }
598 return false;
599}
600
601void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
602 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100603 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
604 if (load_class->NeedsAccessCheck()) {
605 // If we need to perform an access check we cannot remove the instruction.
606 return;
607 }
608
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100609 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100610 check_cast->ClearMustDoNullCheck();
611 }
612
613 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000614 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700615 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100616 return;
617 }
618
Vladimir Markoa65ed302016-03-14 21:21:29 +0000619 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
620 // the return value check with the `outcome` check, b/27651442 .
621 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700622 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100623 if (outcome) {
624 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700625 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700626 if (!load_class->HasUses()) {
627 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
628 // However, here we know that it cannot because the checkcast was successfull, hence
629 // the class was already loaded.
630 load_class->GetBlock()->RemoveInstruction(load_class);
631 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100632 } else {
633 // Don't do anything for exceptional cases for now. Ideally we should remove
634 // all instructions and blocks this instruction dominates.
635 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000636 }
637}
638
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100639void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100640 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100641 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
642 if (load_class->NeedsAccessCheck()) {
643 // If we need to perform an access check we cannot remove the instruction.
644 return;
645 }
646
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100647 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100648 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100649 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100650 instruction->ClearMustDoNullCheck();
651 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100652
653 HGraph* graph = GetGraph();
654 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700655 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100656 instruction->ReplaceWith(graph->GetIntConstant(0));
657 instruction->GetBlock()->RemoveInstruction(instruction);
658 RecordSimplification();
659 return;
660 }
661
Vladimir Marko24bd8952016-03-15 10:40:33 +0000662 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
663 // the return value check with the `outcome` check, b/27651442 .
664 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700665 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700666 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100667 if (outcome && can_be_null) {
668 // Type test will succeed, we just need a null test.
669 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
670 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
671 instruction->ReplaceWith(test);
672 } else {
673 // We've statically determined the result of the instanceof.
674 instruction->ReplaceWith(graph->GetIntConstant(outcome));
675 }
676 RecordSimplification();
677 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700678 if (outcome && !load_class->HasUses()) {
679 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
680 // However, here we know that it cannot because the instanceof check was successfull, hence
681 // the class was already loaded.
682 load_class->GetBlock()->RemoveInstruction(load_class);
683 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100684 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100685}
686
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100687void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100688 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100689 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100690 instruction->ClearValueCanBeNull();
691 }
692}
693
694void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100695 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100696 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100697 instruction->ClearValueCanBeNull();
698 }
699}
700
Anton Shaminbdd79352016-02-15 12:48:36 +0600701static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
702 HInstruction *lhs = cond->InputAt(0);
703 HInstruction *rhs = cond->InputAt(1);
704 switch (cond->GetKind()) {
705 case HInstruction::kEqual:
706 return new (arena) HEqual(rhs, lhs);
707 case HInstruction::kNotEqual:
708 return new (arena) HNotEqual(rhs, lhs);
709 case HInstruction::kLessThan:
710 return new (arena) HGreaterThan(rhs, lhs);
711 case HInstruction::kLessThanOrEqual:
712 return new (arena) HGreaterThanOrEqual(rhs, lhs);
713 case HInstruction::kGreaterThan:
714 return new (arena) HLessThan(rhs, lhs);
715 case HInstruction::kGreaterThanOrEqual:
716 return new (arena) HLessThanOrEqual(rhs, lhs);
717 case HInstruction::kBelow:
718 return new (arena) HAbove(rhs, lhs);
719 case HInstruction::kBelowOrEqual:
720 return new (arena) HAboveOrEqual(rhs, lhs);
721 case HInstruction::kAbove:
722 return new (arena) HBelow(rhs, lhs);
723 case HInstruction::kAboveOrEqual:
724 return new (arena) HBelowOrEqual(rhs, lhs);
725 default:
726 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
727 }
728 return nullptr;
729}
730
Aart Bik2767f4b2016-10-28 15:03:53 -0700731static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100732 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700733 return true; // input has direct boolean type
734 } else if (cmp->GetUses().HasExactlyOneElement()) {
735 // Comparison also has boolean type if both its input and the instruction
736 // itself feed into the same phi node.
737 HInstruction* user = cmp->GetUses().front().GetUser();
738 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
739 }
740 return false;
741}
742
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000743void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100744 HInstruction* input_const = equal->GetConstantRight();
745 if (input_const != nullptr) {
746 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700747 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100748 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100749 // We are comparing the boolean to a constant which is of type int and can
750 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000751 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100752 // Replace (bool_value == true) with bool_value
753 equal->ReplaceWith(input_value);
754 block->RemoveInstruction(equal);
755 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000756 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700757 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500758 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
759 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100760 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100761 } else {
762 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
763 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
764 block->RemoveInstruction(equal);
765 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100766 }
Mark Mendellc4701932015-04-10 13:18:51 -0400767 } else {
768 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100769 }
Mark Mendellc4701932015-04-10 13:18:51 -0400770 } else {
771 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100772 }
773}
774
David Brazdil0d13fee2015-04-17 14:52:19 +0100775void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
776 HInstruction* input_const = not_equal->GetConstantRight();
777 if (input_const != nullptr) {
778 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700779 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100780 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100781 // We are comparing the boolean to a constant which is of type int and can
782 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000783 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700784 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500785 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
786 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000788 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100790 not_equal->ReplaceWith(input_value);
791 block->RemoveInstruction(not_equal);
792 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100793 } else {
794 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
795 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
796 block->RemoveInstruction(not_equal);
797 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100798 }
Mark Mendellc4701932015-04-10 13:18:51 -0400799 } else {
800 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 }
Mark Mendellc4701932015-04-10 13:18:51 -0400802 } else {
803 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100804 }
805}
806
807void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000808 HInstruction* input = bool_not->InputAt(0);
809 HInstruction* replace_with = nullptr;
810
811 if (input->IsIntConstant()) {
812 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000813 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000814 replace_with = GetGraph()->GetIntConstant(0);
815 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000816 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000817 replace_with = GetGraph()->GetIntConstant(1);
818 }
819 } else if (input->IsBooleanNot()) {
820 // Replace (!(!bool_value)) with bool_value.
821 replace_with = input->InputAt(0);
822 } else if (input->IsCondition() &&
823 // Don't change FP compares. The definition of compares involving
824 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100825 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000826 // Replace condition with its opposite.
827 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
828 }
829
830 if (replace_with != nullptr) {
831 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100832 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000833 RecordSimplification();
834 }
835}
836
Aart Bik4f7dd342017-09-12 13:12:57 -0700837// Constructs a new ABS(x) node in the HIR.
838static HInstruction* NewIntegralAbs(ArenaAllocator* arena, HInstruction* x, HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100839 DataType::Type type = x->GetType();
840 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700841 // Construct a fake intrinsic with as much context as is needed to allocate one.
842 // The intrinsic will always be lowered into code later anyway.
843 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
844 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
845 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
846 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
847 0u
848 };
849 HInvokeStaticOrDirect* invoke = new (arena) HInvokeStaticOrDirect(
850 arena,
851 1,
852 type,
853 x->GetDexPc(),
854 /*method_idx*/ -1,
855 /*resolved_method*/ nullptr,
856 dispatch_info,
857 kStatic,
858 MethodReference(nullptr, dex::kDexNoIndex),
859 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
860 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100861 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
862 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700863 kNoEnvironmentOrCache,
864 kNoSideEffects,
865 kNoThrow);
866 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
867 return invoke;
868}
869
870// Returns true if operands a and b consists of widening type conversions
871// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100872static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700873 if (a->IsTypeConversion() && a->GetType() == to_type) {
874 a = a->InputAt(0);
875 }
876 if (b->IsTypeConversion() && b->GetType() == to_type) {
877 b = b->InputAt(0);
878 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100879 DataType::Type type1 = a->GetType();
880 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100881 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
882 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
883 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
884 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
885 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100886 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700887}
888
David Brazdil74eb1b22015-12-14 11:44:01 +0000889void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
890 HInstruction* replace_with = nullptr;
891 HInstruction* condition = select->GetCondition();
892 HInstruction* true_value = select->GetTrueValue();
893 HInstruction* false_value = select->GetFalseValue();
894
895 if (condition->IsBooleanNot()) {
896 // Change ((!cond) ? x : y) to (cond ? y : x).
897 condition = condition->InputAt(0);
898 std::swap(true_value, false_value);
899 select->ReplaceInput(false_value, 0);
900 select->ReplaceInput(true_value, 1);
901 select->ReplaceInput(condition, 2);
902 RecordSimplification();
903 }
904
905 if (true_value == false_value) {
906 // Replace (cond ? x : x) with (x).
907 replace_with = true_value;
908 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000909 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000910 // Replace (true ? x : y) with (x).
911 replace_with = true_value;
912 } else {
913 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000914 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000915 replace_with = false_value;
916 }
917 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000918 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000919 // Replace (cond ? true : false) with (cond).
920 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000921 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000922 // Replace (cond ? false : true) with (!cond).
923 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
924 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700925 } else if (condition->IsCondition()) {
926 IfCondition cmp = condition->AsCondition()->GetCondition();
927 HInstruction* a = condition->InputAt(0);
928 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100929 DataType::Type t_type = true_value->GetType();
930 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700931 // Here we have a <cmp> b ? true_value : false_value.
932 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100933 if (t_type == f_type &&
934 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700935 // Try to replace typical integral ABS constructs.
936 if (true_value->IsNeg()) {
937 HInstruction* negated = true_value->InputAt(0);
938 if ((cmp == kCondLT || cmp == kCondLE) &&
939 (a == negated && a == false_value && IsInt64Value(b, 0))) {
940 // Found a < 0 ? -a : a which can be replaced by ABS(a).
941 replace_with = NewIntegralAbs(GetGraph()->GetArena(), false_value, select);
942 }
943 } else if (false_value->IsNeg()) {
944 HInstruction* negated = false_value->InputAt(0);
945 if ((cmp == kCondGT || cmp == kCondGE) &&
946 (a == true_value && a == negated && IsInt64Value(b, 0))) {
947 // Found a > 0 ? a : -a which can be replaced by ABS(a).
948 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
949 }
950 } else if (true_value->IsSub() && false_value->IsSub()) {
951 HInstruction* true_sub1 = true_value->InputAt(0);
952 HInstruction* true_sub2 = true_value->InputAt(1);
953 HInstruction* false_sub1 = false_value->InputAt(0);
954 HInstruction* false_sub2 = false_value->InputAt(1);
955 if ((((cmp == kCondGT || cmp == kCondGE) &&
956 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
957 ((cmp == kCondLT || cmp == kCondLE) &&
958 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
959 AreLowerPrecisionArgs(t_type, a, b)) {
960 // Found a > b ? a - b : b - a or
961 // a < b ? b - a : a - b
962 // which can be replaced by ABS(a - b) for lower precision operands a, b.
963 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
964 }
965 }
966 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000967 }
968
969 if (replace_with != nullptr) {
970 select->ReplaceWith(replace_with);
971 select->GetBlock()->RemoveInstruction(select);
972 RecordSimplification();
973 }
974}
975
976void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
977 HInstruction* condition = instruction->InputAt(0);
978 if (condition->IsBooleanNot()) {
979 // Swap successors if input is negated.
980 instruction->ReplaceInput(condition->InputAt(0), 0);
981 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100982 RecordSimplification();
983 }
984}
985
Mingyao Yang0304e182015-01-30 16:41:29 -0800986void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
987 HInstruction* input = instruction->InputAt(0);
988 // If the array is a NewArray with constant size, replace the array length
989 // with the constant instruction. This helps the bounds check elimination phase.
990 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000991 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800992 if (input->IsIntConstant()) {
993 instruction->ReplaceWith(input);
994 }
995 }
996}
997
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000998void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000999 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001000 if (value->GetType() != DataType::Type::kReference) {
1001 return;
1002 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001003
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001004 if (CanEnsureNotNullAt(value, instruction)) {
1005 instruction->ClearValueCanBeNull();
1006 }
1007
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001008 if (value->IsArrayGet()) {
1009 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1010 // If the code is just swapping elements in the array, no need for a type check.
1011 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001012 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001013 }
1014 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001015
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001016 if (value->IsNullConstant()) {
1017 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001018 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001019 }
1020
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001021 ScopedObjectAccess soa(Thread::Current());
1022 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1023 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1024 if (!array_rti.IsValid()) {
1025 return;
1026 }
1027
1028 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1029 instruction->ClearNeedsTypeCheck();
1030 return;
1031 }
1032
1033 if (array_rti.IsObjectArray()) {
1034 if (array_rti.IsExact()) {
1035 instruction->ClearNeedsTypeCheck();
1036 return;
1037 }
1038 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001039 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001040}
1041
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001042static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001043 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001044 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001045 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1046 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001047 // Note: The size check excludes Uint8 as the result type.
1048 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001049 return DataType::Size(result_type) > DataType::Size(input_type) &&
1050 result_type != DataType::Type::kUint16 &&
1051 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001052}
1053
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001054void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001055 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001056 DataType::Type input_type = input->GetType();
1057 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001058 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001059 // Remove the implicit conversion; this includes conversion to the same type.
1060 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001061 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001062 RecordSimplification();
1063 return;
1064 }
1065
1066 if (input->IsTypeConversion()) {
1067 HTypeConversion* input_conversion = input->AsTypeConversion();
1068 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001069 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001070
1071 // When the first conversion is lossless, a direct conversion from the original type
1072 // to the final type yields the same result, even for a lossy second conversion, for
1073 // example float->double->int or int->double->float.
1074 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1075
1076 // For integral conversions, see if the first conversion loses only bits that the second
1077 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1078 // conversion yields the same result, for example long->int->short or int->char->short.
1079 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001080 DataType::IsIntegralType(input_type) &&
1081 DataType::IsIntegralType(original_type) &&
1082 DataType::IsIntegralType(result_type) &&
1083 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001084
1085 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1086 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001087 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001088 instruction->ReplaceWith(original_input);
1089 instruction->GetBlock()->RemoveInstruction(instruction);
1090 if (!input_conversion->HasUses()) {
1091 // Don't wait for DCE.
1092 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1093 }
1094 RecordSimplification();
1095 return;
1096 }
1097 // Otherwise simplify only if the first conversion has no other use.
1098 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1099 input_conversion->ReplaceWith(original_input);
1100 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1101 RecordSimplification();
1102 return;
1103 }
1104 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001105 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1106 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001107 HAnd* input_and = input->AsAnd();
1108 HConstant* constant = input_and->GetConstantRight();
1109 if (constant != nullptr) {
1110 int64_t value = Int64FromConstant(constant);
1111 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1112 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001113 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001114 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001115 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001116 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001117 instruction->ReplaceWith(original_input);
1118 instruction->GetBlock()->RemoveInstruction(instruction);
1119 RecordSimplification();
1120 return;
1121 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1122 input_and->ReplaceWith(original_input);
1123 input_and->GetBlock()->RemoveInstruction(input_and);
1124 RecordSimplification();
1125 return;
1126 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001127 }
1128 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001129 }
1130}
1131
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001132void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1133 HConstant* input_cst = instruction->GetConstantRight();
1134 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001135 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001136 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001137 // Replace code looking like
1138 // ADD dst, src, 0
1139 // with
1140 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001141 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1142 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1143 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001144 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001145 instruction->ReplaceWith(input_other);
1146 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001147 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001148 return;
1149 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001150 }
1151
1152 HInstruction* left = instruction->GetLeft();
1153 HInstruction* right = instruction->GetRight();
1154 bool left_is_neg = left->IsNeg();
1155 bool right_is_neg = right->IsNeg();
1156
1157 if (left_is_neg && right_is_neg) {
1158 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1159 return;
1160 }
1161 }
1162
1163 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1164 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1165 // Replace code looking like
1166 // NEG tmp, b
1167 // ADD dst, a, tmp
1168 // with
1169 // SUB dst, a, b
1170 // We do not perform the optimization if the input negation has environment
1171 // uses or multiple non-environment uses as it could lead to worse code. In
1172 // particular, we do not want the live range of `b` to be extended if we are
1173 // not sure the initial 'NEG' instruction can be removed.
1174 HInstruction* other = left_is_neg ? right : left;
1175 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
1176 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1177 RecordSimplification();
1178 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001179 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001180 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001181
Anton Kirilove14dc862016-05-13 17:56:15 +01001182 if (TryReplaceWithRotate(instruction)) {
1183 return;
1184 }
1185
1186 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1187 // so no need to return.
1188 TryHandleAssociativeAndCommutativeOperation(instruction);
1189
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001190 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001191 TrySubtractionChainSimplification(instruction)) {
1192 return;
1193 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001194
1195 if (integral_type) {
1196 // Replace code patterns looking like
1197 // SUB dst1, x, y SUB dst1, x, y
1198 // ADD dst2, dst1, y ADD dst2, y, dst1
1199 // with
1200 // SUB dst1, x, y
1201 // ADD instruction is not needed in this case, we may use
1202 // one of inputs of SUB instead.
1203 if (left->IsSub() && left->InputAt(1) == right) {
1204 instruction->ReplaceWith(left->InputAt(0));
1205 RecordSimplification();
1206 instruction->GetBlock()->RemoveInstruction(instruction);
1207 return;
1208 } else if (right->IsSub() && right->InputAt(1) == left) {
1209 instruction->ReplaceWith(right->InputAt(0));
1210 RecordSimplification();
1211 instruction->GetBlock()->RemoveInstruction(instruction);
1212 return;
1213 }
1214 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001215}
1216
1217void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1218 HConstant* input_cst = instruction->GetConstantRight();
1219 HInstruction* input_other = instruction->GetLeastConstantLeft();
1220
Vladimir Marko452c1b62015-09-25 14:44:17 +01001221 if (input_cst != nullptr) {
1222 int64_t value = Int64FromConstant(input_cst);
1223 if (value == -1) {
1224 // Replace code looking like
1225 // AND dst, src, 0xFFF...FF
1226 // with
1227 // src
1228 instruction->ReplaceWith(input_other);
1229 instruction->GetBlock()->RemoveInstruction(instruction);
1230 RecordSimplification();
1231 return;
1232 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001233 if (input_other->IsTypeConversion() &&
1234 input_other->GetType() == DataType::Type::kInt64 &&
1235 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1236 IsInt<32>(value) &&
1237 input_other->HasOnlyOneNonEnvironmentUse()) {
1238 // The AND can be reordered before the TypeConversion. Replace
1239 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1240 // TypeConversion<Int64> tmp, src
1241 // AND dst, tmp, cst
1242 // with
1243 // IntConstant cst, <32-bit-constant>
1244 // AND tmp, src, cst
1245 // TypeConversion<Int64> dst, tmp
1246 // This helps 32-bit targets and does not hurt 64-bit targets.
1247 // This also simplifies detection of other patterns, such as Uint8 loads.
1248 HInstruction* new_and_input = input_other->InputAt(0);
1249 // Implicit conversion Int64->Int64 would have been removed previously.
1250 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1251 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1252 HAnd* new_and =
1253 new (GetGraph()->GetArena()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
1254 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1255 HTypeConversion* new_conversion =
1256 new (GetGraph()->GetArena()) HTypeConversion(DataType::Type::kInt64, new_and);
1257 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1258 input_other->GetBlock()->RemoveInstruction(input_other);
1259 RecordSimplification();
1260 // Try to process the new And now, do not wait for the next round of simplifications.
1261 instruction = new_and;
1262 input_other = new_and_input;
1263 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001264 // Eliminate And from UShr+And if the And-mask contains all the bits that
1265 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1266 // precisely clears the shifted-in sign bits.
1267 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001268 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001269 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1270 size_t num_tail_bits_set = CTZ(value + 1);
1271 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1272 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1273 instruction->ReplaceWith(input_other);
1274 instruction->GetBlock()->RemoveInstruction(instruction);
1275 RecordSimplification();
1276 return;
1277 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1278 input_other->HasOnlyOneNonEnvironmentUse()) {
1279 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1280 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1281 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1282 input_other->InputAt(0),
1283 input_other->InputAt(1),
1284 input_other->GetDexPc());
1285 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1286 input_other->GetBlock()->RemoveInstruction(input_other);
1287 RecordSimplification();
1288 return;
1289 }
1290 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001291 }
1292
1293 // We assume that GVN has run before, so we only perform a pointer comparison.
1294 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001295 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001296 if (instruction->GetLeft() == instruction->GetRight()) {
1297 // Replace code looking like
1298 // AND dst, src, src
1299 // with
1300 // src
1301 instruction->ReplaceWith(instruction->GetLeft());
1302 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001303 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001304 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001305 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001306
Anton Kirilove14dc862016-05-13 17:56:15 +01001307 if (TryDeMorganNegationFactoring(instruction)) {
1308 return;
1309 }
1310
1311 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1312 // so no need to return.
1313 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001314}
1315
Mark Mendellc4701932015-04-10 13:18:51 -04001316void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1317 VisitCondition(condition);
1318}
1319
1320void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1321 VisitCondition(condition);
1322}
1323
1324void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1325 VisitCondition(condition);
1326}
1327
1328void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1329 VisitCondition(condition);
1330}
1331
Anton Shaminbdd79352016-02-15 12:48:36 +06001332void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1333 VisitCondition(condition);
1334}
1335
1336void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1337 VisitCondition(condition);
1338}
1339
1340void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1341 VisitCondition(condition);
1342}
1343
1344void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1345 VisitCondition(condition);
1346}
Aart Bike9f37602015-10-09 11:15:55 -07001347
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001348// Recognize the following pattern:
1349// obj.getClass() ==/!= Foo.class
1350// And replace it with a constant value if the type of `obj` is statically known.
1351static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1352 HInstruction* input_one = condition->InputAt(0);
1353 HInstruction* input_two = condition->InputAt(1);
1354 HLoadClass* load_class = input_one->IsLoadClass()
1355 ? input_one->AsLoadClass()
1356 : input_two->AsLoadClass();
1357 if (load_class == nullptr) {
1358 return false;
1359 }
1360
1361 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1362 if (!class_rti.IsValid()) {
1363 // Unresolved class.
1364 return false;
1365 }
1366
1367 HInstanceFieldGet* field_get = (load_class == input_one)
1368 ? input_two->AsInstanceFieldGet()
1369 : input_one->AsInstanceFieldGet();
1370 if (field_get == nullptr) {
1371 return false;
1372 }
1373
1374 HInstruction* receiver = field_get->InputAt(0);
1375 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1376 if (!receiver_type.IsExact()) {
1377 return false;
1378 }
1379
1380 {
1381 ScopedObjectAccess soa(Thread::Current());
1382 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1383 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1384 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1385 if (field_get->GetFieldInfo().GetField() != field) {
1386 return false;
1387 }
1388
1389 // We can replace the compare.
1390 int value = 0;
1391 if (receiver_type.IsEqual(class_rti)) {
1392 value = condition->IsEqual() ? 1 : 0;
1393 } else {
1394 value = condition->IsNotEqual() ? 1 : 0;
1395 }
1396 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1397 return true;
1398 }
1399}
1400
Mark Mendellc4701932015-04-10 13:18:51 -04001401void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001402 if (condition->IsEqual() || condition->IsNotEqual()) {
1403 if (RecognizeAndSimplifyClassCheck(condition)) {
1404 return;
1405 }
1406 }
1407
Anton Shaminbdd79352016-02-15 12:48:36 +06001408 // Reverse condition if left is constant. Our code generators prefer constant
1409 // on the right hand side.
1410 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1411 HBasicBlock* block = condition->GetBlock();
1412 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1413 // If it is a fp we must set the opposite bias.
1414 if (replacement != nullptr) {
1415 if (condition->IsLtBias()) {
1416 replacement->SetBias(ComparisonBias::kGtBias);
1417 } else if (condition->IsGtBias()) {
1418 replacement->SetBias(ComparisonBias::kLtBias);
1419 }
1420 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1421 RecordSimplification();
1422
1423 condition = replacement;
1424 }
1425 }
Mark Mendellc4701932015-04-10 13:18:51 -04001426
Mark Mendellc4701932015-04-10 13:18:51 -04001427 HInstruction* left = condition->GetLeft();
1428 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001429
1430 // Try to fold an HCompare into this HCondition.
1431
Mark Mendellc4701932015-04-10 13:18:51 -04001432 // We can only replace an HCondition which compares a Compare to 0.
1433 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1434 // condition with a long, float or double comparison as input.
1435 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1436 // Conversion is not possible.
1437 return;
1438 }
1439
1440 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001441 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001442 // Someone else also wants the result of the compare.
1443 return;
1444 }
1445
Vladimir Marko46817b82016-03-29 12:21:58 +01001446 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001447 // There is a reference to the compare result in an environment. Do we really need it?
1448 if (GetGraph()->IsDebuggable()) {
1449 return;
1450 }
1451
1452 // We have to ensure that there are no deopt points in the sequence.
1453 if (left->HasAnyEnvironmentUseBefore(condition)) {
1454 return;
1455 }
1456 }
1457
1458 // Clean up any environment uses from the HCompare, if any.
1459 left->RemoveEnvironmentUsers();
1460
1461 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1462 condition->SetBias(left->AsCompare()->GetBias());
1463
1464 // Replace the operands of the HCondition.
1465 condition->ReplaceInput(left->InputAt(0), 0);
1466 condition->ReplaceInput(left->InputAt(1), 1);
1467
1468 // Remove the HCompare.
1469 left->GetBlock()->RemoveInstruction(left);
1470
1471 RecordSimplification();
1472}
1473
Andreas Gampe9186ced2016-12-12 14:28:21 -08001474// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1475static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1476 // True, if the most significant bits of divisor are 0.
1477 return ((divisor & 0x7fffff) == 0);
1478}
1479
1480// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1481static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1482 // True, if the most significant bits of divisor are 0.
1483 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1484}
1485
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001486void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1487 HConstant* input_cst = instruction->GetConstantRight();
1488 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001489 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001490
1491 if ((input_cst != nullptr) && input_cst->IsOne()) {
1492 // Replace code looking like
1493 // DIV dst, src, 1
1494 // with
1495 // src
1496 instruction->ReplaceWith(input_other);
1497 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001498 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001499 return;
1500 }
1501
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001502 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001503 // Replace code looking like
1504 // DIV dst, src, -1
1505 // with
1506 // NEG dst, src
1507 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001508 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001509 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001510 return;
1511 }
1512
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001514 // Try replacing code looking like
1515 // DIV dst, src, constant
1516 // with
1517 // MUL dst, src, 1 / constant
1518 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001520 double value = input_cst->AsDoubleConstant()->GetValue();
1521 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1522 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1523 }
1524 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001525 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001526 float value = input_cst->AsFloatConstant()->GetValue();
1527 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1528 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1529 }
1530 }
1531
1532 if (reciprocal != nullptr) {
1533 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1534 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1535 RecordSimplification();
1536 return;
1537 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001538 }
1539}
1540
1541void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1542 HConstant* input_cst = instruction->GetConstantRight();
1543 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001545 HBasicBlock* block = instruction->GetBlock();
1546 ArenaAllocator* allocator = GetGraph()->GetArena();
1547
1548 if (input_cst == nullptr) {
1549 return;
1550 }
1551
1552 if (input_cst->IsOne()) {
1553 // Replace code looking like
1554 // MUL dst, src, 1
1555 // with
1556 // src
1557 instruction->ReplaceWith(input_other);
1558 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001559 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001560 return;
1561 }
1562
1563 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001565 // Replace code looking like
1566 // MUL dst, src, -1
1567 // with
1568 // NEG dst, src
1569 HNeg* neg = new (allocator) HNeg(type, input_other);
1570 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001571 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001572 return;
1573 }
1574
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001575 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001576 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1577 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1578 // Replace code looking like
1579 // FP_MUL dst, src, 2.0
1580 // with
1581 // FP_ADD dst, src, src
1582 // The 'int' and 'long' cases are handled below.
1583 block->ReplaceAndRemoveInstructionWith(instruction,
1584 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001585 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001586 return;
1587 }
1588
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001590 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001591 // Even though constant propagation also takes care of the zero case, other
1592 // optimizations can lead to having a zero multiplication.
1593 if (factor == 0) {
1594 // Replace code looking like
1595 // MUL dst, src, 0
1596 // with
1597 // 0
1598 instruction->ReplaceWith(input_cst);
1599 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001600 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001601 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001602 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001603 // Replace code looking like
1604 // MUL dst, src, pow_of_2
1605 // with
1606 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001607 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001608 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001609 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001610 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001611 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001612 } else if (IsPowerOfTwo(factor - 1)) {
1613 // Transform code looking like
1614 // MUL dst, src, (2^n + 1)
1615 // into
1616 // SHL tmp, src, n
1617 // ADD dst, src, tmp
1618 HShl* shl = new (allocator) HShl(type,
1619 input_other,
1620 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1621 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1622
1623 block->InsertInstructionBefore(shl, instruction);
1624 block->ReplaceAndRemoveInstructionWith(instruction, add);
1625 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001626 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001627 } else if (IsPowerOfTwo(factor + 1)) {
1628 // Transform code looking like
1629 // MUL dst, src, (2^n - 1)
1630 // into
1631 // SHL tmp, src, n
1632 // SUB dst, tmp, src
1633 HShl* shl = new (allocator) HShl(type,
1634 input_other,
1635 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1636 HSub* sub = new (allocator) HSub(type, shl, input_other);
1637
1638 block->InsertInstructionBefore(shl, instruction);
1639 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1640 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001641 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001642 }
1643 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001644
1645 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1646 // so no need to return.
1647 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001648}
1649
Alexandre Rames188d4312015-04-09 18:30:21 +01001650void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1651 HInstruction* input = instruction->GetInput();
1652 if (input->IsNeg()) {
1653 // Replace code looking like
1654 // NEG tmp, src
1655 // NEG dst, tmp
1656 // with
1657 // src
1658 HNeg* previous_neg = input->AsNeg();
1659 instruction->ReplaceWith(previous_neg->GetInput());
1660 instruction->GetBlock()->RemoveInstruction(instruction);
1661 // We perform the optimization even if the input negation has environment
1662 // uses since it allows removing the current instruction. But we only delete
1663 // the input negation only if it is does not have any uses left.
1664 if (!previous_neg->HasUses()) {
1665 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1666 }
1667 RecordSimplification();
1668 return;
1669 }
1670
Serguei Katkov339dfc22015-04-20 12:29:32 +06001671 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001673 // Replace code looking like
1674 // SUB tmp, a, b
1675 // NEG dst, tmp
1676 // with
1677 // SUB dst, b, a
1678 // We do not perform the optimization if the input subtraction has
1679 // environment uses or multiple non-environment uses as it could lead to
1680 // worse code. In particular, we do not want the live ranges of `a` and `b`
1681 // to be extended if we are not sure the initial 'SUB' instruction can be
1682 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001683 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001684 HSub* sub = input->AsSub();
1685 HSub* new_sub =
1686 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1687 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1688 if (!sub->HasUses()) {
1689 sub->GetBlock()->RemoveInstruction(sub);
1690 }
1691 RecordSimplification();
1692 }
1693}
1694
1695void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1696 HInstruction* input = instruction->GetInput();
1697 if (input->IsNot()) {
1698 // Replace code looking like
1699 // NOT tmp, src
1700 // NOT dst, tmp
1701 // with
1702 // src
1703 // We perform the optimization even if the input negation has environment
1704 // uses since it allows removing the current instruction. But we only delete
1705 // the input negation only if it is does not have any uses left.
1706 HNot* previous_not = input->AsNot();
1707 instruction->ReplaceWith(previous_not->GetInput());
1708 instruction->GetBlock()->RemoveInstruction(instruction);
1709 if (!previous_not->HasUses()) {
1710 previous_not->GetBlock()->RemoveInstruction(previous_not);
1711 }
1712 RecordSimplification();
1713 }
1714}
1715
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001716void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1717 HConstant* input_cst = instruction->GetConstantRight();
1718 HInstruction* input_other = instruction->GetLeastConstantLeft();
1719
Roland Levillain1a653882016-03-18 18:05:57 +00001720 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001721 // Replace code looking like
1722 // OR dst, src, 0
1723 // with
1724 // src
1725 instruction->ReplaceWith(input_other);
1726 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001727 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001728 return;
1729 }
1730
1731 // We assume that GVN has run before, so we only perform a pointer comparison.
1732 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001733 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001734 if (instruction->GetLeft() == instruction->GetRight()) {
1735 // Replace code looking like
1736 // OR dst, src, src
1737 // with
1738 // src
1739 instruction->ReplaceWith(instruction->GetLeft());
1740 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001741 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001742 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001743 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001744
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001745 if (TryDeMorganNegationFactoring(instruction)) return;
1746
Anton Kirilove14dc862016-05-13 17:56:15 +01001747 if (TryReplaceWithRotate(instruction)) {
1748 return;
1749 }
1750
1751 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1752 // so no need to return.
1753 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001754}
1755
1756void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1757 VisitShift(instruction);
1758}
1759
1760void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1761 VisitShift(instruction);
1762}
1763
1764void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1765 HConstant* input_cst = instruction->GetConstantRight();
1766 HInstruction* input_other = instruction->GetLeastConstantLeft();
1767
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001768 DataType::Type type = instruction->GetType();
1769 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001770 return;
1771 }
1772
Roland Levillain1a653882016-03-18 18:05:57 +00001773 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001774 // Replace code looking like
1775 // SUB dst, src, 0
1776 // with
1777 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001778 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1779 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1780 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001781 instruction->ReplaceWith(input_other);
1782 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001783 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001784 return;
1785 }
1786
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001787 HBasicBlock* block = instruction->GetBlock();
1788 ArenaAllocator* allocator = GetGraph()->GetArena();
1789
Alexandre Rames188d4312015-04-09 18:30:21 +01001790 HInstruction* left = instruction->GetLeft();
1791 HInstruction* right = instruction->GetRight();
1792 if (left->IsConstant()) {
1793 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001794 // Replace code looking like
1795 // SUB dst, 0, src
1796 // with
1797 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001798 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001799 // `x` is `0.0`, the former expression yields `0.0`, while the later
1800 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001801 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001802 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001803 RecordSimplification();
1804 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001805 }
1806 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001807
1808 if (left->IsNeg() && right->IsNeg()) {
1809 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1810 return;
1811 }
1812 }
1813
1814 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1815 // Replace code looking like
1816 // NEG tmp, b
1817 // SUB dst, a, tmp
1818 // with
1819 // ADD dst, a, b
1820 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1821 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1822 RecordSimplification();
1823 right->GetBlock()->RemoveInstruction(right);
1824 return;
1825 }
1826
1827 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1828 // Replace code looking like
1829 // NEG tmp, a
1830 // SUB dst, tmp, b
1831 // with
1832 // ADD tmp, a, b
1833 // NEG dst, tmp
1834 // The second version is not intrinsically better, but enables more
1835 // transformations.
1836 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1837 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1838 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1839 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1840 instruction->ReplaceWith(neg);
1841 instruction->GetBlock()->RemoveInstruction(instruction);
1842 RecordSimplification();
1843 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001844 return;
1845 }
1846
1847 if (TrySubtractionChainSimplification(instruction)) {
1848 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001849 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001850
1851 if (left->IsAdd()) {
1852 // Replace code patterns looking like
1853 // ADD dst1, x, y ADD dst1, x, y
1854 // SUB dst2, dst1, y SUB dst2, dst1, x
1855 // with
1856 // ADD dst1, x, y
1857 // SUB instruction is not needed in this case, we may use
1858 // one of inputs of ADD instead.
1859 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001860 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001861 if (left->InputAt(1) == right) {
1862 instruction->ReplaceWith(left->InputAt(0));
1863 RecordSimplification();
1864 instruction->GetBlock()->RemoveInstruction(instruction);
1865 return;
1866 } else if (left->InputAt(0) == right) {
1867 instruction->ReplaceWith(left->InputAt(1));
1868 RecordSimplification();
1869 instruction->GetBlock()->RemoveInstruction(instruction);
1870 return;
1871 }
1872 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001873}
1874
1875void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1876 VisitShift(instruction);
1877}
1878
1879void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1880 HConstant* input_cst = instruction->GetConstantRight();
1881 HInstruction* input_other = instruction->GetLeastConstantLeft();
1882
Roland Levillain1a653882016-03-18 18:05:57 +00001883 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001884 // Replace code looking like
1885 // XOR dst, src, 0
1886 // with
1887 // src
1888 instruction->ReplaceWith(input_other);
1889 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001890 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001891 return;
1892 }
1893
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001894 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001895 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001896 // Replace code looking like
1897 // XOR dst, src, 1
1898 // with
1899 // BOOLEAN_NOT dst, src
1900 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1901 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1902 RecordSimplification();
1903 return;
1904 }
1905
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001906 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1907 // Replace code looking like
1908 // XOR dst, src, 0xFFF...FF
1909 // with
1910 // NOT dst, src
1911 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1912 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001913 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001914 return;
1915 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001916
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001917 HInstruction* left = instruction->GetLeft();
1918 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001919 if (((left->IsNot() && right->IsNot()) ||
1920 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001921 left->HasOnlyOneNonEnvironmentUse() &&
1922 right->HasOnlyOneNonEnvironmentUse()) {
1923 // Replace code looking like
1924 // NOT nota, a
1925 // NOT notb, b
1926 // XOR dst, nota, notb
1927 // with
1928 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001929 instruction->ReplaceInput(left->InputAt(0), 0);
1930 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001931 left->GetBlock()->RemoveInstruction(left);
1932 right->GetBlock()->RemoveInstruction(right);
1933 RecordSimplification();
1934 return;
1935 }
1936
Anton Kirilove14dc862016-05-13 17:56:15 +01001937 if (TryReplaceWithRotate(instruction)) {
1938 return;
1939 }
1940
1941 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1942 // so no need to return.
1943 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001944}
1945
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001946void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1947 HInstruction* argument = instruction->InputAt(1);
1948 HInstruction* receiver = instruction->InputAt(0);
1949 if (receiver == argument) {
1950 // Because String.equals is an instance call, the receiver is
1951 // a null check if we don't know it's null. The argument however, will
1952 // be the actual object. So we cannot end up in a situation where both
1953 // are equal but could be null.
1954 DCHECK(CanEnsureNotNullAt(argument, instruction));
1955 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1956 instruction->GetBlock()->RemoveInstruction(instruction);
1957 } else {
1958 StringEqualsOptimizations optimizations(instruction);
1959 if (CanEnsureNotNullAt(argument, instruction)) {
1960 optimizations.SetArgumentNotNull();
1961 }
1962 ScopedObjectAccess soa(Thread::Current());
1963 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1964 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1965 optimizations.SetArgumentIsString();
1966 }
1967 }
1968}
1969
Roland Levillain22c49222016-03-18 14:04:28 +00001970void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1971 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001972 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001973 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001974 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001975 HInstruction* value = invoke->InputAt(0);
1976 HInstruction* distance = invoke->InputAt(1);
1977 // Replace the invoke with an HRor.
1978 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001979 // Unconditionally set the type of the negated distance to `int`,
1980 // as shift and rotate operations expect a 32-bit (or narrower)
1981 // value for their distance input.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001982 distance = new (GetGraph()->GetArena()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001983 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1984 }
Roland Levillain22c49222016-03-18 14:04:28 +00001985 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001986 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1987 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001988 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001989 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1990 clinit->GetBlock()->RemoveInstruction(clinit);
1991 HInstruction* ldclass = clinit->InputAt(0);
1992 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1993 ldclass->GetBlock()->RemoveInstruction(ldclass);
1994 }
1995 }
1996}
1997
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001998static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1999 if (potential_length->IsArrayLength()) {
2000 return potential_length->InputAt(0) == potential_array;
2001 }
2002
2003 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002004 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002005 }
2006
2007 return false;
2008}
2009
2010void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2011 HInstruction* source = instruction->InputAt(0);
2012 HInstruction* destination = instruction->InputAt(2);
2013 HInstruction* count = instruction->InputAt(4);
2014 SystemArrayCopyOptimizations optimizations(instruction);
2015 if (CanEnsureNotNullAt(source, instruction)) {
2016 optimizations.SetSourceIsNotNull();
2017 }
2018 if (CanEnsureNotNullAt(destination, instruction)) {
2019 optimizations.SetDestinationIsNotNull();
2020 }
2021 if (destination == source) {
2022 optimizations.SetDestinationIsSource();
2023 }
2024
2025 if (IsArrayLengthOf(count, source)) {
2026 optimizations.SetCountIsSourceLength();
2027 }
2028
2029 if (IsArrayLengthOf(count, destination)) {
2030 optimizations.SetCountIsDestinationLength();
2031 }
2032
2033 {
2034 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002035 DataType::Type source_component_type = DataType::Type::kVoid;
2036 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002037 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2038 if (destination_rti.IsValid()) {
2039 if (destination_rti.IsObjectArray()) {
2040 if (destination_rti.IsExact()) {
2041 optimizations.SetDoesNotNeedTypeCheck();
2042 }
2043 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002044 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002045 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002046 destination_component_type = DataTypeFromPrimitive(
2047 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002048 optimizations.SetDestinationIsPrimitiveArray();
2049 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2050 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002051 }
2052 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002053 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2054 if (source_rti.IsValid()) {
2055 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2056 optimizations.SetDoesNotNeedTypeCheck();
2057 }
2058 if (source_rti.IsPrimitiveArrayClass()) {
2059 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002060 source_component_type = DataTypeFromPrimitive(
2061 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002062 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2063 optimizations.SetSourceIsNonPrimitiveArray();
2064 }
2065 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002066 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002067 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002068 (source_component_type == destination_component_type)) {
2069 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2070 PointerSize image_size = class_linker->GetImagePointerSize();
2071 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2072 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2073 ArtMethod* method = nullptr;
2074 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002075 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002076 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002077 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002078 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002079 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002080 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002081 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002082 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002083 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002084 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002085 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002086 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002087 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002088 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002089 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002090 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002091 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002092 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002093 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002094 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002095 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002096 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002097 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002098 break;
2099 default:
2100 LOG(FATAL) << "Unreachable";
2101 }
2102 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002103 DCHECK(method->IsStatic());
2104 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002105 invoke->SetResolvedMethod(method);
2106 // Sharpen the new invoke. Note that we do not update the dex method index of
2107 // the invoke, as we would need to look it up in the current dex file, and it
2108 // is unlikely that it exists. The most usual situation for such typed
2109 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002110 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002111 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002112 }
2113}
2114
Roland Levillaina5c4a402016-03-15 15:02:50 +00002115void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2116 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002117 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002118 DCHECK(invoke->IsInvokeStaticOrDirect());
2119 uint32_t dex_pc = invoke->GetDexPc();
2120 HInstruction* left = invoke->InputAt(0);
2121 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002122 if (!is_signum) {
2123 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002124 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002125 right = GetGraph()->GetLongConstant(0);
2126 } else {
2127 right = GetGraph()->GetIntConstant(0);
2128 }
2129 HCompare* compare = new (GetGraph()->GetArena())
2130 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2131 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2132}
2133
Aart Bik75a38b22016-02-17 10:41:50 -08002134void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2135 DCHECK(invoke->IsInvokeStaticOrDirect());
2136 uint32_t dex_pc = invoke->GetDexPc();
2137 // IsNaN(x) is the same as x != x.
2138 HInstruction* x = invoke->InputAt(0);
2139 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002140 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002141 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2142}
2143
Aart Bik2a6aad92016-02-25 11:32:32 -08002144void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2145 DCHECK(invoke->IsInvokeStaticOrDirect());
2146 uint32_t dex_pc = invoke->GetDexPc();
2147 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002148 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002149 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2150 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002151 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002152 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2153 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2154 kNeedsEnvironmentOrCache,
2155 kNoSideEffects,
2156 kNoThrow);
2157 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002158 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002159 nan = GetGraph()->GetIntConstant(0x7fc00000);
2160 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2161 kNeedsEnvironmentOrCache,
2162 kNoSideEffects,
2163 kNoThrow);
2164 }
2165 // Test IsNaN(x), which is the same as x != x.
2166 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
2167 condition->SetBias(ComparisonBias::kLtBias);
2168 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2169 // Select between the two.
2170 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
2171 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2172 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2173}
2174
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002175void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2176 HInstruction* str = invoke->InputAt(0);
2177 HInstruction* index = invoke->InputAt(1);
2178 uint32_t dex_pc = invoke->GetDexPc();
2179 ArenaAllocator* arena = GetGraph()->GetArena();
2180 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2181 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2182 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2183 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002184 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2185 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002186 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002187 HArrayGet* array_get = new (arena) HArrayGet(str,
2188 bounds_check,
2189 DataType::Type::kUint16,
2190 SideEffects::None(), // Strings are immutable.
2191 dex_pc,
2192 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002193 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2194 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2195 GetGraph()->SetHasBoundsChecks(true);
2196}
2197
Vladimir Markodce016e2016-04-28 13:10:02 +01002198void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2199 HInstruction* str = invoke->InputAt(0);
2200 uint32_t dex_pc = invoke->GetDexPc();
2201 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2202 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002203 HArrayLength* length =
2204 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002205 HInstruction* replacement;
2206 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2207 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2208 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2209 HIntConstant* zero = GetGraph()->GetIntConstant(0);
2210 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
2211 replacement = equal;
2212 } else {
2213 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2214 replacement = length;
2215 }
2216 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2217}
2218
Aart Bikff7d89c2016-11-07 08:49:28 -08002219// This method should only be used on intrinsics whose sole way of throwing an
2220// exception is raising a NPE when the nth argument is null. If that argument
2221// is provably non-null, we can clear the flag.
2222void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2223 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002224 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002225 invoke->SetCanThrow(false);
2226 }
2227}
2228
Aart Bik71bf7b42016-11-16 10:17:46 -08002229// Methods that return "this" can replace the returned value with the receiver.
2230void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2231 if (invoke->HasUses()) {
2232 HInstruction* receiver = invoke->InputAt(0);
2233 invoke->ReplaceWith(receiver);
2234 RecordSimplification();
2235 }
2236}
2237
2238// Helper method for StringBuffer escape analysis.
2239static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2240 if (user->IsInvokeStaticOrDirect()) {
2241 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002242 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2243 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002244 user->InputAt(0) == reference;
2245 } else if (user->IsInvokeVirtual()) {
2246 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2247 case Intrinsics::kStringBufferLength:
2248 case Intrinsics::kStringBufferToString:
2249 DCHECK_EQ(user->InputAt(0), reference);
2250 return true;
2251 case Intrinsics::kStringBufferAppend:
2252 // Returns "this", so only okay if no further uses.
2253 DCHECK_EQ(user->InputAt(0), reference);
2254 DCHECK_NE(user->InputAt(1), reference);
2255 return !user->HasUses();
2256 default:
2257 break;
2258 }
2259 }
2260 return false;
2261}
2262
2263// Certain allocation intrinsics are not removed by dead code elimination
2264// because of potentially throwing an OOM exception or other side effects.
2265// This method removes such intrinsics when special circumstances allow.
2266void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2267 if (!invoke->HasUses()) {
2268 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2269 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2270 // call does not escape since only thread-local synchronization may be removed.
2271 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2272 HInstruction* receiver = invoke->InputAt(0);
2273 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2274 invoke->GetBlock()->RemoveInstruction(invoke);
2275 RecordSimplification();
2276 }
2277 }
2278}
2279
Aart Bik11932592016-03-08 12:42:25 -08002280void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2281 uint32_t dex_pc = invoke->GetDexPc();
2282 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2283 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2284}
2285
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002286void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002287 switch (instruction->GetIntrinsic()) {
2288 case Intrinsics::kStringEquals:
2289 SimplifyStringEquals(instruction);
2290 break;
2291 case Intrinsics::kSystemArrayCopy:
2292 SimplifySystemArrayCopy(instruction);
2293 break;
2294 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002295 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002296 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002297 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002298 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002299 break;
2300 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002301 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002302 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002303 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002304 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002305 break;
2306 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002307 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002308 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002309 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002310 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002311 break;
2312 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002313 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002314 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002315 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002316 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002317 break;
2318 case Intrinsics::kFloatIsNaN:
2319 case Intrinsics::kDoubleIsNaN:
2320 SimplifyIsNaN(instruction);
2321 break;
2322 case Intrinsics::kFloatFloatToIntBits:
2323 case Intrinsics::kDoubleDoubleToLongBits:
2324 SimplifyFP2Int(instruction);
2325 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002326 case Intrinsics::kStringCharAt:
2327 SimplifyStringCharAt(instruction);
2328 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002329 case Intrinsics::kStringIsEmpty:
2330 case Intrinsics::kStringLength:
2331 SimplifyStringIsEmptyOrLength(instruction);
2332 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002333 case Intrinsics::kStringStringIndexOf:
2334 case Intrinsics::kStringStringIndexOfAfter:
2335 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2336 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002337 case Intrinsics::kStringBufferAppend:
2338 case Intrinsics::kStringBuilderAppend:
2339 SimplifyReturnThis(instruction);
2340 break;
2341 case Intrinsics::kStringBufferToString:
2342 case Intrinsics::kStringBuilderToString:
2343 SimplifyAllocationIntrinsic(instruction);
2344 break;
Aart Bik11932592016-03-08 12:42:25 -08002345 case Intrinsics::kUnsafeLoadFence:
2346 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2347 break;
2348 case Intrinsics::kUnsafeStoreFence:
2349 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2350 break;
2351 case Intrinsics::kUnsafeFullFence:
2352 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2353 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002354 case Intrinsics::kVarHandleFullFence:
2355 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2356 break;
2357 case Intrinsics::kVarHandleAcquireFence:
2358 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2359 break;
2360 case Intrinsics::kVarHandleReleaseFence:
2361 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2362 break;
2363 case Intrinsics::kVarHandleLoadLoadFence:
2364 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2365 break;
2366 case Intrinsics::kVarHandleStoreStoreFence:
2367 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2368 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002369 default:
2370 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002371 }
2372}
2373
Aart Bikbb245d12015-10-19 11:05:03 -07002374void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2375 HInstruction* cond = deoptimize->InputAt(0);
2376 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002377 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002378 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002379 if (deoptimize->GuardsAnInput()) {
2380 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2381 }
Aart Bikbb245d12015-10-19 11:05:03 -07002382 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2383 } else {
2384 // Always deopt.
2385 }
2386 }
2387}
2388
Anton Kirilove14dc862016-05-13 17:56:15 +01002389// Replace code looking like
2390// OP y, x, const1
2391// OP z, y, const2
2392// with
2393// OP z, x, const3
2394// where OP is both an associative and a commutative operation.
2395bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2396 HBinaryOperation* instruction) {
2397 DCHECK(instruction->IsCommutative());
2398
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002399 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002400 return false;
2401 }
2402
2403 HInstruction* left = instruction->GetLeft();
2404 HInstruction* right = instruction->GetRight();
2405 // Variable names as described above.
2406 HConstant* const2;
2407 HBinaryOperation* y;
2408
2409 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2410 const2 = right->AsConstant();
2411 y = left->AsBinaryOperation();
2412 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2413 const2 = left->AsConstant();
2414 y = right->AsBinaryOperation();
2415 } else {
2416 // The node does not match the pattern.
2417 return false;
2418 }
2419
2420 // If `y` has more than one use, we do not perform the optimization
2421 // because it might increase code size (e.g. if the new constant is
2422 // no longer encodable as an immediate operand in the target ISA).
2423 if (!y->HasOnlyOneNonEnvironmentUse()) {
2424 return false;
2425 }
2426
2427 // GetConstantRight() can return both left and right constants
2428 // for commutative operations.
2429 HConstant* const1 = y->GetConstantRight();
2430 if (const1 == nullptr) {
2431 return false;
2432 }
2433
2434 instruction->ReplaceInput(const1, 0);
2435 instruction->ReplaceInput(const2, 1);
2436 HConstant* const3 = instruction->TryStaticEvaluation();
2437 DCHECK(const3 != nullptr);
2438 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2439 instruction->ReplaceInput(const3, 1);
2440 RecordSimplification();
2441 return true;
2442}
2443
2444static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2445 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2446}
2447
2448// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002449static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002450 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002451 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002452 return HAdd::Compute<int32_t>(x, y);
2453 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002454 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002455 return HAdd::Compute<int64_t>(x, y);
2456 }
2457}
2458
2459// Helper function that handles the child classes of HConstant
2460// and returns an integer with the appropriate sign.
2461static int64_t GetValue(HConstant* constant, bool is_negated) {
2462 int64_t ret = Int64FromConstant(constant);
2463 return is_negated ? -ret : ret;
2464}
2465
2466// Replace code looking like
2467// OP1 y, x, const1
2468// OP2 z, y, const2
2469// with
2470// OP3 z, x, const3
2471// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2472bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2473 HBinaryOperation* instruction) {
2474 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2475
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002476 DataType::Type type = instruction->GetType();
2477 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002478 return false;
2479 }
2480
2481 HInstruction* left = instruction->GetLeft();
2482 HInstruction* right = instruction->GetRight();
2483 // Variable names as described above.
2484 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2485 if (const2 == nullptr) {
2486 return false;
2487 }
2488
2489 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2490 ? left->AsBinaryOperation()
2491 : AsAddOrSub(right);
2492 // If y has more than one use, we do not perform the optimization because
2493 // it might increase code size (e.g. if the new constant is no longer
2494 // encodable as an immediate operand in the target ISA).
2495 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2496 return false;
2497 }
2498
2499 left = y->GetLeft();
2500 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2501 if (const1 == nullptr) {
2502 return false;
2503 }
2504
2505 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2506 // If both inputs are constants, let the constant folding pass deal with it.
2507 if (x->IsConstant()) {
2508 return false;
2509 }
2510
2511 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2512 int64_t const2_val = GetValue(const2, is_const2_negated);
2513 bool is_y_negated = (y == right) && instruction->IsSub();
2514 right = y->GetRight();
2515 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2516 int64_t const1_val = GetValue(const1, is_const1_negated);
2517 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2518 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2519 HBasicBlock* block = instruction->GetBlock();
2520 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2521 ArenaAllocator* arena = instruction->GetArena();
2522 HInstruction* z;
2523
2524 if (is_x_negated) {
2525 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2526 } else {
2527 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2528 }
2529
2530 block->ReplaceAndRemoveInstructionWith(instruction, z);
2531 RecordSimplification();
2532 return true;
2533}
2534
Lena Djokicbc5460b2017-07-20 16:07:36 +02002535void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2536 if (TryCombineVecMultiplyAccumulate(instruction)) {
2537 RecordSimplification();
2538 }
2539}
2540
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002541} // namespace art