blob: f39acab3d742115572bc0c3a1d5bc9dc97260622 [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);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100189 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100190 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()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100228 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000229 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100230 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100234 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000235 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100236 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000237 }
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
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100277 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278
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 =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100310 new (allocator) HVecMultiplyAccumulate(allocator,
311 kind,
312 accumulator,
313 mul->GetLeft(),
314 mul->GetRight(),
315 binop->GetPackedType(),
316 binop->GetVectorLength(),
317 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200318
319 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
320 DCHECK(!mul->HasUses());
321 mul->GetBlock()->RemoveInstruction(mul);
322 return true;
323 }
324 }
325 }
326
327 return false;
328}
329
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000330void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
331 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100332 HInstruction* shift_amount = instruction->GetRight();
333 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000334
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100335 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100336 ? kMaxLongShiftDistance
337 : kMaxIntShiftDistance;
338
339 if (shift_amount->IsConstant()) {
340 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700341 int64_t masked_cst = cst & implicit_mask;
342 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400343 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100344 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400345 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100346 // value
347 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400348 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100349 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100350 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700351 } else if (masked_cst != cst) {
352 // Replace code looking like
353 // SHL dst, value, cst
354 // where cst exceeds maximum distance with the equivalent
355 // SHL dst, value, cst & implicit_mask
356 // (as defined by shift semantics). This ensures other
357 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100358 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700359 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
360 RecordSimplification();
361 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100362 }
363 }
364
365 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100366 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
367 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100368 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100369 // AND adjusted_shift, shift, <superset of implicit mask>
370 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
371 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
372 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100373 // with
374 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100375 if (shift_amount->IsAnd() ||
376 shift_amount->IsOr() ||
377 shift_amount->IsXor() ||
378 shift_amount->IsAdd() ||
379 shift_amount->IsSub()) {
380 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
381 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
382 HConstant* mask = bin_op->GetConstantRight();
383 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
384 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100385 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 return;
387 }
388 } else if (shift_amount->IsTypeConversion()) {
389 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
390 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
391 // Non-integral and 64-bit source types require an explicit type conversion.
392 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
393 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
394 RecordSimplification();
395 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400396 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000397 }
398}
399
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000400static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
401 return (sub->GetRight() == other &&
402 sub->GetLeft()->IsConstant() &&
403 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
404}
405
406bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
407 HUShr* ushr,
408 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000409 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100410 HRor* ror =
411 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000412 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
413 if (!ushr->HasUses()) {
414 ushr->GetBlock()->RemoveInstruction(ushr);
415 }
416 if (!ushr->GetRight()->HasUses()) {
417 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
418 }
419 if (!shl->HasUses()) {
420 shl->GetBlock()->RemoveInstruction(shl);
421 }
422 if (!shl->GetRight()->HasUses()) {
423 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
424 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100425 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000426 return true;
427}
428
429// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
430bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000431 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
432 HInstruction* left = op->GetLeft();
433 HInstruction* right = op->GetRight();
434 // If we have an UShr and a Shl (in either order).
435 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
436 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
437 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100438 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000439 if (ushr->GetType() == shl->GetType() &&
440 ushr->GetLeft() == shl->GetLeft()) {
441 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
442 // Shift distances are both constant, try replacing with Ror if they
443 // add up to the register size.
444 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
445 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
446 // Shift distances are potentially of the form x and (reg_size - x).
447 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
448 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
449 // Shift distances are potentially of the form d and -d.
450 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
451 }
452 }
453 }
454 return false;
455}
456
457// Try replacing code looking like (x >>> #rdist OP x << #ldist):
458// UShr dst, x, #rdist
459// Shl tmp, x, #ldist
460// OP dst, dst, tmp
461// or like (x >>> #rdist OP x << #-ldist):
462// UShr dst, x, #rdist
463// Shl tmp, x, #-ldist
464// OP dst, dst, tmp
465// with
466// Ror dst, x, #rdist
467bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
468 HUShr* ushr,
469 HShl* shl) {
470 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100471 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000472 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
473 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
474 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
475 ReplaceRotateWithRor(op, ushr, shl);
476 return true;
477 }
478 return false;
479}
480
481// Replace code looking like (x >>> -d OP x << d):
482// Neg neg, d
483// UShr dst, x, neg
484// Shl tmp, x, d
485// OP dst, dst, tmp
486// with
487// Neg neg, d
488// Ror dst, x, neg
489// *** OR ***
490// Replace code looking like (x >>> d OP x << -d):
491// UShr dst, x, d
492// Neg neg, d
493// Shl tmp, x, neg
494// OP dst, dst, tmp
495// with
496// Ror dst, x, d
497bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
498 HUShr* ushr,
499 HShl* shl) {
500 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
501 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
502 bool neg_is_left = shl->GetRight()->IsNeg();
503 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
504 // And the shift distance being negated is the distance being shifted the other way.
505 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
506 ReplaceRotateWithRor(op, ushr, shl);
507 }
508 return false;
509}
510
511// Try replacing code looking like (x >>> d OP x << (#bits - d)):
512// UShr dst, x, d
513// Sub ld, #bits, d
514// Shl tmp, x, ld
515// OP dst, dst, tmp
516// with
517// Ror dst, x, d
518// *** OR ***
519// Replace code looking like (x >>> (#bits - d) OP x << d):
520// Sub rd, #bits, d
521// UShr dst, x, rd
522// Shl tmp, x, d
523// OP dst, dst, tmp
524// with
525// Neg neg, d
526// Ror dst, x, neg
527bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
528 HUShr* ushr,
529 HShl* shl) {
530 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
531 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100532 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000533 HInstruction* shl_shift = shl->GetRight();
534 HInstruction* ushr_shift = ushr->GetRight();
535 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
536 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
537 return ReplaceRotateWithRor(op, ushr, shl);
538 }
539 return false;
540}
541
Calin Juravle10e244f2015-01-26 18:54:32 +0000542void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
543 HInstruction* obj = null_check->InputAt(0);
544 if (!obj->CanBeNull()) {
545 null_check->ReplaceWith(obj);
546 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000547 if (stats_ != nullptr) {
548 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
549 }
550 }
551}
552
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100553bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
554 if (!input->CanBeNull()) {
555 return true;
556 }
557
Vladimir Marko46817b82016-03-29 12:21:58 +0100558 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
559 HInstruction* user = use.GetUser();
560 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100561 return true;
562 }
563 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100564
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100565 return false;
566}
567
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100568// Returns whether doing a type test between the class of `object` against `klass` has
569// a statically known outcome. The result of the test is stored in `outcome`.
570static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000571 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
572 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
573 ScopedObjectAccess soa(Thread::Current());
574 if (!obj_rti.IsValid()) {
575 // We run the simplifier before the reference type propagation so type info might not be
576 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000578 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100579
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100580 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100581 if (!class_rti.IsValid()) {
582 // Happens when the loaded class is unresolved.
583 return false;
584 }
585 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000586 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100587 *outcome = true;
588 return true;
589 } else if (obj_rti.IsExact()) {
590 // The test failed at compile time so will also fail at runtime.
591 *outcome = false;
592 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100593 } else if (!class_rti.IsInterface()
594 && !obj_rti.IsInterface()
595 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 // Different type hierarchy. The test will fail.
597 *outcome = false;
598 return true;
599 }
600 return false;
601}
602
603void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
604 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100605 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
606 if (load_class->NeedsAccessCheck()) {
607 // If we need to perform an access check we cannot remove the instruction.
608 return;
609 }
610
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100611 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100612 check_cast->ClearMustDoNullCheck();
613 }
614
615 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000616 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700617 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100618 return;
619 }
620
Vladimir Markoa65ed302016-03-14 21:21:29 +0000621 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
622 // the return value check with the `outcome` check, b/27651442 .
623 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700624 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100625 if (outcome) {
626 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700627 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700628 if (!load_class->HasUses()) {
629 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
630 // However, here we know that it cannot because the checkcast was successfull, hence
631 // the class was already loaded.
632 load_class->GetBlock()->RemoveInstruction(load_class);
633 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100634 } else {
635 // Don't do anything for exceptional cases for now. Ideally we should remove
636 // all instructions and blocks this instruction dominates.
637 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000638 }
639}
640
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100641void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100642 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100643 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
644 if (load_class->NeedsAccessCheck()) {
645 // If we need to perform an access check we cannot remove the instruction.
646 return;
647 }
648
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100649 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100650 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100651 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100652 instruction->ClearMustDoNullCheck();
653 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654
655 HGraph* graph = GetGraph();
656 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700657 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100658 instruction->ReplaceWith(graph->GetIntConstant(0));
659 instruction->GetBlock()->RemoveInstruction(instruction);
660 RecordSimplification();
661 return;
662 }
663
Vladimir Marko24bd8952016-03-15 10:40:33 +0000664 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
665 // the return value check with the `outcome` check, b/27651442 .
666 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700667 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700668 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100669 if (outcome && can_be_null) {
670 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100671 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
673 instruction->ReplaceWith(test);
674 } else {
675 // We've statically determined the result of the instanceof.
676 instruction->ReplaceWith(graph->GetIntConstant(outcome));
677 }
678 RecordSimplification();
679 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700680 if (outcome && !load_class->HasUses()) {
681 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
682 // However, here we know that it cannot because the instanceof check was successfull, hence
683 // the class was already loaded.
684 load_class->GetBlock()->RemoveInstruction(load_class);
685 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100686 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100687}
688
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100689void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100690 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100691 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100692 instruction->ClearValueCanBeNull();
693 }
694}
695
696void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100697 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100698 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100699 instruction->ClearValueCanBeNull();
700 }
701}
702
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100703static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600704 HInstruction *lhs = cond->InputAt(0);
705 HInstruction *rhs = cond->InputAt(1);
706 switch (cond->GetKind()) {
707 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100708 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600709 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100710 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600711 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100712 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600713 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100714 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600715 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100716 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600717 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100718 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600719 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100720 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600721 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100722 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600723 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100724 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600725 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100726 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600727 default:
728 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
729 }
730 return nullptr;
731}
732
Aart Bik2767f4b2016-10-28 15:03:53 -0700733static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100734 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700735 return true; // input has direct boolean type
736 } else if (cmp->GetUses().HasExactlyOneElement()) {
737 // Comparison also has boolean type if both its input and the instruction
738 // itself feed into the same phi node.
739 HInstruction* user = cmp->GetUses().front().GetUser();
740 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
741 }
742 return false;
743}
744
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000745void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100746 HInstruction* input_const = equal->GetConstantRight();
747 if (input_const != nullptr) {
748 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700749 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100750 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100751 // We are comparing the boolean to a constant which is of type int and can
752 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000753 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100754 // Replace (bool_value == true) with bool_value
755 equal->ReplaceWith(input_value);
756 block->RemoveInstruction(equal);
757 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000758 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700759 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500760 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
761 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100763 } else {
764 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
765 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
766 block->RemoveInstruction(equal);
767 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100768 }
Mark Mendellc4701932015-04-10 13:18:51 -0400769 } else {
770 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100771 }
Mark Mendellc4701932015-04-10 13:18:51 -0400772 } else {
773 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100774 }
775}
776
David Brazdil0d13fee2015-04-17 14:52:19 +0100777void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
778 HInstruction* input_const = not_equal->GetConstantRight();
779 if (input_const != nullptr) {
780 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700781 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100782 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100783 // We are comparing the boolean to a constant which is of type int and can
784 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000785 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700786 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500787 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
788 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000790 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100791 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100792 not_equal->ReplaceWith(input_value);
793 block->RemoveInstruction(not_equal);
794 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100795 } else {
796 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
797 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
798 block->RemoveInstruction(not_equal);
799 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100800 }
Mark Mendellc4701932015-04-10 13:18:51 -0400801 } else {
802 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100803 }
Mark Mendellc4701932015-04-10 13:18:51 -0400804 } else {
805 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100806 }
807}
808
809void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000810 HInstruction* input = bool_not->InputAt(0);
811 HInstruction* replace_with = nullptr;
812
813 if (input->IsIntConstant()) {
814 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000815 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000816 replace_with = GetGraph()->GetIntConstant(0);
817 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000818 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000819 replace_with = GetGraph()->GetIntConstant(1);
820 }
821 } else if (input->IsBooleanNot()) {
822 // Replace (!(!bool_value)) with bool_value.
823 replace_with = input->InputAt(0);
824 } else if (input->IsCondition() &&
825 // Don't change FP compares. The definition of compares involving
826 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100827 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000828 // Replace condition with its opposite.
829 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
830 }
831
832 if (replace_with != nullptr) {
833 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100834 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 RecordSimplification();
836 }
837}
838
Aart Bik4f7dd342017-09-12 13:12:57 -0700839// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100840static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
841 HInstruction* x,
842 HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100843 DataType::Type type = x->GetType();
844 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700845 // Construct a fake intrinsic with as much context as is needed to allocate one.
846 // The intrinsic will always be lowered into code later anyway.
847 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
848 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
849 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
850 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
851 0u
852 };
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100853 HInvokeStaticOrDirect* invoke = new (allocator) HInvokeStaticOrDirect(
854 allocator,
Aart Bik4f7dd342017-09-12 13:12:57 -0700855 1,
856 type,
857 x->GetDexPc(),
858 /*method_idx*/ -1,
859 /*resolved_method*/ nullptr,
860 dispatch_info,
861 kStatic,
862 MethodReference(nullptr, dex::kDexNoIndex),
863 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
864 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100865 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
866 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700867 kNoEnvironmentOrCache,
868 kNoSideEffects,
869 kNoThrow);
870 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
871 return invoke;
872}
873
874// Returns true if operands a and b consists of widening type conversions
875// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100876static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700877 if (a->IsTypeConversion() && a->GetType() == to_type) {
878 a = a->InputAt(0);
879 }
880 if (b->IsTypeConversion() && b->GetType() == to_type) {
881 b = b->InputAt(0);
882 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100883 DataType::Type type1 = a->GetType();
884 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100885 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
886 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
887 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
888 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
889 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100890 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700891}
892
David Brazdil74eb1b22015-12-14 11:44:01 +0000893void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
894 HInstruction* replace_with = nullptr;
895 HInstruction* condition = select->GetCondition();
896 HInstruction* true_value = select->GetTrueValue();
897 HInstruction* false_value = select->GetFalseValue();
898
899 if (condition->IsBooleanNot()) {
900 // Change ((!cond) ? x : y) to (cond ? y : x).
901 condition = condition->InputAt(0);
902 std::swap(true_value, false_value);
903 select->ReplaceInput(false_value, 0);
904 select->ReplaceInput(true_value, 1);
905 select->ReplaceInput(condition, 2);
906 RecordSimplification();
907 }
908
909 if (true_value == false_value) {
910 // Replace (cond ? x : x) with (x).
911 replace_with = true_value;
912 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000913 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000914 // Replace (true ? x : y) with (x).
915 replace_with = true_value;
916 } else {
917 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000918 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000919 replace_with = false_value;
920 }
921 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000922 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000923 // Replace (cond ? true : false) with (cond).
924 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000925 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000926 // Replace (cond ? false : true) with (!cond).
927 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
928 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700929 } else if (condition->IsCondition()) {
930 IfCondition cmp = condition->AsCondition()->GetCondition();
931 HInstruction* a = condition->InputAt(0);
932 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100933 DataType::Type t_type = true_value->GetType();
934 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700935 // Here we have a <cmp> b ? true_value : false_value.
936 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100937 if (t_type == f_type &&
938 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700939 // Try to replace typical integral ABS constructs.
940 if (true_value->IsNeg()) {
941 HInstruction* negated = true_value->InputAt(0);
942 if ((cmp == kCondLT || cmp == kCondLE) &&
943 (a == negated && a == false_value && IsInt64Value(b, 0))) {
944 // Found a < 0 ? -a : a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100945 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), false_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700946 }
947 } else if (false_value->IsNeg()) {
948 HInstruction* negated = false_value->InputAt(0);
949 if ((cmp == kCondGT || cmp == kCondGE) &&
950 (a == true_value && a == negated && IsInt64Value(b, 0))) {
951 // Found a > 0 ? a : -a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100952 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700953 }
954 } else if (true_value->IsSub() && false_value->IsSub()) {
955 HInstruction* true_sub1 = true_value->InputAt(0);
956 HInstruction* true_sub2 = true_value->InputAt(1);
957 HInstruction* false_sub1 = false_value->InputAt(0);
958 HInstruction* false_sub2 = false_value->InputAt(1);
959 if ((((cmp == kCondGT || cmp == kCondGE) &&
960 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
961 ((cmp == kCondLT || cmp == kCondLE) &&
962 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
963 AreLowerPrecisionArgs(t_type, a, b)) {
964 // Found a > b ? a - b : b - a or
965 // a < b ? b - a : a - b
966 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100967 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700968 }
969 }
970 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000971 }
972
973 if (replace_with != nullptr) {
974 select->ReplaceWith(replace_with);
975 select->GetBlock()->RemoveInstruction(select);
976 RecordSimplification();
977 }
978}
979
980void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
981 HInstruction* condition = instruction->InputAt(0);
982 if (condition->IsBooleanNot()) {
983 // Swap successors if input is negated.
984 instruction->ReplaceInput(condition->InputAt(0), 0);
985 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100986 RecordSimplification();
987 }
988}
989
Mingyao Yang0304e182015-01-30 16:41:29 -0800990void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
991 HInstruction* input = instruction->InputAt(0);
992 // If the array is a NewArray with constant size, replace the array length
993 // with the constant instruction. This helps the bounds check elimination phase.
994 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000995 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800996 if (input->IsIntConstant()) {
997 instruction->ReplaceWith(input);
998 }
999 }
1000}
1001
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001002void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001003 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001004 if (value->GetType() != DataType::Type::kReference) {
1005 return;
1006 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001007
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001008 if (CanEnsureNotNullAt(value, instruction)) {
1009 instruction->ClearValueCanBeNull();
1010 }
1011
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001012 if (value->IsArrayGet()) {
1013 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1014 // If the code is just swapping elements in the array, no need for a type check.
1015 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001016 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001017 }
1018 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001019
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001020 if (value->IsNullConstant()) {
1021 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001022 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001023 }
1024
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001025 ScopedObjectAccess soa(Thread::Current());
1026 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1027 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1028 if (!array_rti.IsValid()) {
1029 return;
1030 }
1031
1032 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1033 instruction->ClearNeedsTypeCheck();
1034 return;
1035 }
1036
1037 if (array_rti.IsObjectArray()) {
1038 if (array_rti.IsExact()) {
1039 instruction->ClearNeedsTypeCheck();
1040 return;
1041 }
1042 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001043 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001044}
1045
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001046static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001047 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001048 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001049 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1050 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001051 // Note: The size check excludes Uint8 as the result type.
1052 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001053 return DataType::Size(result_type) > DataType::Size(input_type) &&
1054 result_type != DataType::Type::kUint16 &&
1055 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001056}
1057
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001058void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001059 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001060 DataType::Type input_type = input->GetType();
1061 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001062 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001063 // Remove the implicit conversion; this includes conversion to the same type.
1064 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001065 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001066 RecordSimplification();
1067 return;
1068 }
1069
1070 if (input->IsTypeConversion()) {
1071 HTypeConversion* input_conversion = input->AsTypeConversion();
1072 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001073 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001074
1075 // When the first conversion is lossless, a direct conversion from the original type
1076 // to the final type yields the same result, even for a lossy second conversion, for
1077 // example float->double->int or int->double->float.
1078 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1079
1080 // For integral conversions, see if the first conversion loses only bits that the second
1081 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1082 // conversion yields the same result, for example long->int->short or int->char->short.
1083 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001084 DataType::IsIntegralType(input_type) &&
1085 DataType::IsIntegralType(original_type) &&
1086 DataType::IsIntegralType(result_type) &&
1087 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001088
1089 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1090 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001091 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001092 instruction->ReplaceWith(original_input);
1093 instruction->GetBlock()->RemoveInstruction(instruction);
1094 if (!input_conversion->HasUses()) {
1095 // Don't wait for DCE.
1096 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1097 }
1098 RecordSimplification();
1099 return;
1100 }
1101 // Otherwise simplify only if the first conversion has no other use.
1102 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1103 input_conversion->ReplaceWith(original_input);
1104 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1105 RecordSimplification();
1106 return;
1107 }
1108 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001109 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1110 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001111 HAnd* input_and = input->AsAnd();
1112 HConstant* constant = input_and->GetConstantRight();
1113 if (constant != nullptr) {
1114 int64_t value = Int64FromConstant(constant);
1115 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1116 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001117 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001118 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001119 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001120 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001121 instruction->ReplaceWith(original_input);
1122 instruction->GetBlock()->RemoveInstruction(instruction);
1123 RecordSimplification();
1124 return;
1125 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1126 input_and->ReplaceWith(original_input);
1127 input_and->GetBlock()->RemoveInstruction(input_and);
1128 RecordSimplification();
1129 return;
1130 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001131 }
1132 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001133 }
1134}
1135
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001136void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1137 HConstant* input_cst = instruction->GetConstantRight();
1138 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001139 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001140 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001141 // Replace code looking like
1142 // ADD dst, src, 0
1143 // with
1144 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001145 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1146 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1147 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001148 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001149 instruction->ReplaceWith(input_other);
1150 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001151 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001152 return;
1153 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001154 }
1155
1156 HInstruction* left = instruction->GetLeft();
1157 HInstruction* right = instruction->GetRight();
1158 bool left_is_neg = left->IsNeg();
1159 bool right_is_neg = right->IsNeg();
1160
1161 if (left_is_neg && right_is_neg) {
1162 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1163 return;
1164 }
1165 }
1166
1167 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1168 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1169 // Replace code looking like
1170 // NEG tmp, b
1171 // ADD dst, a, tmp
1172 // with
1173 // SUB dst, a, b
1174 // We do not perform the optimization if the input negation has environment
1175 // uses or multiple non-environment uses as it could lead to worse code. In
1176 // particular, we do not want the live range of `b` to be extended if we are
1177 // not sure the initial 'NEG' instruction can be removed.
1178 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001179 HSub* sub =
1180 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001181 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1182 RecordSimplification();
1183 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001184 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001185 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001186
Anton Kirilove14dc862016-05-13 17:56:15 +01001187 if (TryReplaceWithRotate(instruction)) {
1188 return;
1189 }
1190
1191 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1192 // so no need to return.
1193 TryHandleAssociativeAndCommutativeOperation(instruction);
1194
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001195 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001196 TrySubtractionChainSimplification(instruction)) {
1197 return;
1198 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001199
1200 if (integral_type) {
1201 // Replace code patterns looking like
1202 // SUB dst1, x, y SUB dst1, x, y
1203 // ADD dst2, dst1, y ADD dst2, y, dst1
1204 // with
1205 // SUB dst1, x, y
1206 // ADD instruction is not needed in this case, we may use
1207 // one of inputs of SUB instead.
1208 if (left->IsSub() && left->InputAt(1) == right) {
1209 instruction->ReplaceWith(left->InputAt(0));
1210 RecordSimplification();
1211 instruction->GetBlock()->RemoveInstruction(instruction);
1212 return;
1213 } else if (right->IsSub() && right->InputAt(1) == left) {
1214 instruction->ReplaceWith(right->InputAt(0));
1215 RecordSimplification();
1216 instruction->GetBlock()->RemoveInstruction(instruction);
1217 return;
1218 }
1219 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001220}
1221
1222void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1223 HConstant* input_cst = instruction->GetConstantRight();
1224 HInstruction* input_other = instruction->GetLeastConstantLeft();
1225
Vladimir Marko452c1b62015-09-25 14:44:17 +01001226 if (input_cst != nullptr) {
1227 int64_t value = Int64FromConstant(input_cst);
1228 if (value == -1) {
1229 // Replace code looking like
1230 // AND dst, src, 0xFFF...FF
1231 // with
1232 // src
1233 instruction->ReplaceWith(input_other);
1234 instruction->GetBlock()->RemoveInstruction(instruction);
1235 RecordSimplification();
1236 return;
1237 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001238 if (input_other->IsTypeConversion() &&
1239 input_other->GetType() == DataType::Type::kInt64 &&
1240 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1241 IsInt<32>(value) &&
1242 input_other->HasOnlyOneNonEnvironmentUse()) {
1243 // The AND can be reordered before the TypeConversion. Replace
1244 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1245 // TypeConversion<Int64> tmp, src
1246 // AND dst, tmp, cst
1247 // with
1248 // IntConstant cst, <32-bit-constant>
1249 // AND tmp, src, cst
1250 // TypeConversion<Int64> dst, tmp
1251 // This helps 32-bit targets and does not hurt 64-bit targets.
1252 // This also simplifies detection of other patterns, such as Uint8 loads.
1253 HInstruction* new_and_input = input_other->InputAt(0);
1254 // Implicit conversion Int64->Int64 would have been removed previously.
1255 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1256 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1257 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001258 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001259 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1260 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001261 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001262 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1263 input_other->GetBlock()->RemoveInstruction(input_other);
1264 RecordSimplification();
1265 // Try to process the new And now, do not wait for the next round of simplifications.
1266 instruction = new_and;
1267 input_other = new_and_input;
1268 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001269 // Eliminate And from UShr+And if the And-mask contains all the bits that
1270 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1271 // precisely clears the shifted-in sign bits.
1272 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001273 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001274 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1275 size_t num_tail_bits_set = CTZ(value + 1);
1276 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1277 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1278 instruction->ReplaceWith(input_other);
1279 instruction->GetBlock()->RemoveInstruction(instruction);
1280 RecordSimplification();
1281 return;
1282 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1283 input_other->HasOnlyOneNonEnvironmentUse()) {
1284 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1285 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001286 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko452c1b62015-09-25 14:44:17 +01001287 input_other->InputAt(0),
1288 input_other->InputAt(1),
1289 input_other->GetDexPc());
1290 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1291 input_other->GetBlock()->RemoveInstruction(input_other);
1292 RecordSimplification();
1293 return;
1294 }
1295 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001296 }
1297
1298 // We assume that GVN has run before, so we only perform a pointer comparison.
1299 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001300 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001301 if (instruction->GetLeft() == instruction->GetRight()) {
1302 // Replace code looking like
1303 // AND dst, src, src
1304 // with
1305 // src
1306 instruction->ReplaceWith(instruction->GetLeft());
1307 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001308 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001309 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001310 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001311
Anton Kirilove14dc862016-05-13 17:56:15 +01001312 if (TryDeMorganNegationFactoring(instruction)) {
1313 return;
1314 }
1315
1316 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1317 // so no need to return.
1318 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001319}
1320
Mark Mendellc4701932015-04-10 13:18:51 -04001321void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1322 VisitCondition(condition);
1323}
1324
1325void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1326 VisitCondition(condition);
1327}
1328
1329void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1330 VisitCondition(condition);
1331}
1332
1333void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1334 VisitCondition(condition);
1335}
1336
Anton Shaminbdd79352016-02-15 12:48:36 +06001337void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1338 VisitCondition(condition);
1339}
1340
1341void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1342 VisitCondition(condition);
1343}
1344
1345void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1346 VisitCondition(condition);
1347}
1348
1349void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1350 VisitCondition(condition);
1351}
Aart Bike9f37602015-10-09 11:15:55 -07001352
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001353// Recognize the following pattern:
1354// obj.getClass() ==/!= Foo.class
1355// And replace it with a constant value if the type of `obj` is statically known.
1356static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1357 HInstruction* input_one = condition->InputAt(0);
1358 HInstruction* input_two = condition->InputAt(1);
1359 HLoadClass* load_class = input_one->IsLoadClass()
1360 ? input_one->AsLoadClass()
1361 : input_two->AsLoadClass();
1362 if (load_class == nullptr) {
1363 return false;
1364 }
1365
1366 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1367 if (!class_rti.IsValid()) {
1368 // Unresolved class.
1369 return false;
1370 }
1371
1372 HInstanceFieldGet* field_get = (load_class == input_one)
1373 ? input_two->AsInstanceFieldGet()
1374 : input_one->AsInstanceFieldGet();
1375 if (field_get == nullptr) {
1376 return false;
1377 }
1378
1379 HInstruction* receiver = field_get->InputAt(0);
1380 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1381 if (!receiver_type.IsExact()) {
1382 return false;
1383 }
1384
1385 {
1386 ScopedObjectAccess soa(Thread::Current());
1387 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1388 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1389 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1390 if (field_get->GetFieldInfo().GetField() != field) {
1391 return false;
1392 }
1393
1394 // We can replace the compare.
1395 int value = 0;
1396 if (receiver_type.IsEqual(class_rti)) {
1397 value = condition->IsEqual() ? 1 : 0;
1398 } else {
1399 value = condition->IsNotEqual() ? 1 : 0;
1400 }
1401 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1402 return true;
1403 }
1404}
1405
Mark Mendellc4701932015-04-10 13:18:51 -04001406void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001407 if (condition->IsEqual() || condition->IsNotEqual()) {
1408 if (RecognizeAndSimplifyClassCheck(condition)) {
1409 return;
1410 }
1411 }
1412
Anton Shaminbdd79352016-02-15 12:48:36 +06001413 // Reverse condition if left is constant. Our code generators prefer constant
1414 // on the right hand side.
1415 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1416 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001417 HCondition* replacement =
1418 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001419 // If it is a fp we must set the opposite bias.
1420 if (replacement != nullptr) {
1421 if (condition->IsLtBias()) {
1422 replacement->SetBias(ComparisonBias::kGtBias);
1423 } else if (condition->IsGtBias()) {
1424 replacement->SetBias(ComparisonBias::kLtBias);
1425 }
1426 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1427 RecordSimplification();
1428
1429 condition = replacement;
1430 }
1431 }
Mark Mendellc4701932015-04-10 13:18:51 -04001432
Mark Mendellc4701932015-04-10 13:18:51 -04001433 HInstruction* left = condition->GetLeft();
1434 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001435
1436 // Try to fold an HCompare into this HCondition.
1437
Mark Mendellc4701932015-04-10 13:18:51 -04001438 // We can only replace an HCondition which compares a Compare to 0.
1439 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1440 // condition with a long, float or double comparison as input.
1441 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1442 // Conversion is not possible.
1443 return;
1444 }
1445
1446 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001447 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001448 // Someone else also wants the result of the compare.
1449 return;
1450 }
1451
Vladimir Marko46817b82016-03-29 12:21:58 +01001452 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001453 // There is a reference to the compare result in an environment. Do we really need it?
1454 if (GetGraph()->IsDebuggable()) {
1455 return;
1456 }
1457
1458 // We have to ensure that there are no deopt points in the sequence.
1459 if (left->HasAnyEnvironmentUseBefore(condition)) {
1460 return;
1461 }
1462 }
1463
1464 // Clean up any environment uses from the HCompare, if any.
1465 left->RemoveEnvironmentUsers();
1466
1467 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1468 condition->SetBias(left->AsCompare()->GetBias());
1469
1470 // Replace the operands of the HCondition.
1471 condition->ReplaceInput(left->InputAt(0), 0);
1472 condition->ReplaceInput(left->InputAt(1), 1);
1473
1474 // Remove the HCompare.
1475 left->GetBlock()->RemoveInstruction(left);
1476
1477 RecordSimplification();
1478}
1479
Andreas Gampe9186ced2016-12-12 14:28:21 -08001480// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1481static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1482 // True, if the most significant bits of divisor are 0.
1483 return ((divisor & 0x7fffff) == 0);
1484}
1485
1486// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1487static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1488 // True, if the most significant bits of divisor are 0.
1489 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1490}
1491
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001492void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1493 HConstant* input_cst = instruction->GetConstantRight();
1494 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001495 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001496
1497 if ((input_cst != nullptr) && input_cst->IsOne()) {
1498 // Replace code looking like
1499 // DIV dst, src, 1
1500 // with
1501 // src
1502 instruction->ReplaceWith(input_other);
1503 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001504 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001505 return;
1506 }
1507
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001508 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001509 // Replace code looking like
1510 // DIV dst, src, -1
1511 // with
1512 // NEG dst, src
1513 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001514 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001515 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001516 return;
1517 }
1518
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001520 // Try replacing code looking like
1521 // DIV dst, src, constant
1522 // with
1523 // MUL dst, src, 1 / constant
1524 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001525 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001526 double value = input_cst->AsDoubleConstant()->GetValue();
1527 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1528 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1529 }
1530 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001531 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001532 float value = input_cst->AsFloatConstant()->GetValue();
1533 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1534 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1535 }
1536 }
1537
1538 if (reciprocal != nullptr) {
1539 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001540 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001541 RecordSimplification();
1542 return;
1543 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001544 }
1545}
1546
1547void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1548 HConstant* input_cst = instruction->GetConstantRight();
1549 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001550 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001551 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001552 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001553
1554 if (input_cst == nullptr) {
1555 return;
1556 }
1557
1558 if (input_cst->IsOne()) {
1559 // Replace code looking like
1560 // MUL dst, src, 1
1561 // with
1562 // src
1563 instruction->ReplaceWith(input_other);
1564 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001565 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001566 return;
1567 }
1568
1569 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001570 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001571 // Replace code looking like
1572 // MUL dst, src, -1
1573 // with
1574 // NEG dst, src
1575 HNeg* neg = new (allocator) HNeg(type, input_other);
1576 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001577 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001578 return;
1579 }
1580
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001582 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1583 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1584 // Replace code looking like
1585 // FP_MUL dst, src, 2.0
1586 // with
1587 // FP_ADD dst, src, src
1588 // The 'int' and 'long' cases are handled below.
1589 block->ReplaceAndRemoveInstructionWith(instruction,
1590 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001591 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001592 return;
1593 }
1594
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001595 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001596 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001597 // Even though constant propagation also takes care of the zero case, other
1598 // optimizations can lead to having a zero multiplication.
1599 if (factor == 0) {
1600 // Replace code looking like
1601 // MUL dst, src, 0
1602 // with
1603 // 0
1604 instruction->ReplaceWith(input_cst);
1605 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001606 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001607 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001608 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001609 // Replace code looking like
1610 // MUL dst, src, pow_of_2
1611 // with
1612 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001613 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001614 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001615 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001616 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001617 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001618 } else if (IsPowerOfTwo(factor - 1)) {
1619 // Transform code looking like
1620 // MUL dst, src, (2^n + 1)
1621 // into
1622 // SHL tmp, src, n
1623 // ADD dst, src, tmp
1624 HShl* shl = new (allocator) HShl(type,
1625 input_other,
1626 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1627 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1628
1629 block->InsertInstructionBefore(shl, instruction);
1630 block->ReplaceAndRemoveInstructionWith(instruction, add);
1631 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001632 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001633 } else if (IsPowerOfTwo(factor + 1)) {
1634 // Transform code looking like
1635 // MUL dst, src, (2^n - 1)
1636 // into
1637 // SHL tmp, src, n
1638 // SUB dst, tmp, src
1639 HShl* shl = new (allocator) HShl(type,
1640 input_other,
1641 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1642 HSub* sub = new (allocator) HSub(type, shl, input_other);
1643
1644 block->InsertInstructionBefore(shl, instruction);
1645 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1646 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001647 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001648 }
1649 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001650
1651 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1652 // so no need to return.
1653 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001654}
1655
Alexandre Rames188d4312015-04-09 18:30:21 +01001656void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1657 HInstruction* input = instruction->GetInput();
1658 if (input->IsNeg()) {
1659 // Replace code looking like
1660 // NEG tmp, src
1661 // NEG dst, tmp
1662 // with
1663 // src
1664 HNeg* previous_neg = input->AsNeg();
1665 instruction->ReplaceWith(previous_neg->GetInput());
1666 instruction->GetBlock()->RemoveInstruction(instruction);
1667 // We perform the optimization even if the input negation has environment
1668 // uses since it allows removing the current instruction. But we only delete
1669 // the input negation only if it is does not have any uses left.
1670 if (!previous_neg->HasUses()) {
1671 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1672 }
1673 RecordSimplification();
1674 return;
1675 }
1676
Serguei Katkov339dfc22015-04-20 12:29:32 +06001677 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001679 // Replace code looking like
1680 // SUB tmp, a, b
1681 // NEG dst, tmp
1682 // with
1683 // SUB dst, b, a
1684 // We do not perform the optimization if the input subtraction has
1685 // environment uses or multiple non-environment uses as it could lead to
1686 // worse code. In particular, we do not want the live ranges of `a` and `b`
1687 // to be extended if we are not sure the initial 'SUB' instruction can be
1688 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001689 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001690 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001691 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1692 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001693 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1694 if (!sub->HasUses()) {
1695 sub->GetBlock()->RemoveInstruction(sub);
1696 }
1697 RecordSimplification();
1698 }
1699}
1700
1701void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1702 HInstruction* input = instruction->GetInput();
1703 if (input->IsNot()) {
1704 // Replace code looking like
1705 // NOT tmp, src
1706 // NOT dst, tmp
1707 // with
1708 // src
1709 // We perform the optimization even if the input negation has environment
1710 // uses since it allows removing the current instruction. But we only delete
1711 // the input negation only if it is does not have any uses left.
1712 HNot* previous_not = input->AsNot();
1713 instruction->ReplaceWith(previous_not->GetInput());
1714 instruction->GetBlock()->RemoveInstruction(instruction);
1715 if (!previous_not->HasUses()) {
1716 previous_not->GetBlock()->RemoveInstruction(previous_not);
1717 }
1718 RecordSimplification();
1719 }
1720}
1721
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001722void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1723 HConstant* input_cst = instruction->GetConstantRight();
1724 HInstruction* input_other = instruction->GetLeastConstantLeft();
1725
Roland Levillain1a653882016-03-18 18:05:57 +00001726 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001727 // Replace code looking like
1728 // OR dst, src, 0
1729 // with
1730 // src
1731 instruction->ReplaceWith(input_other);
1732 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001733 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001734 return;
1735 }
1736
1737 // We assume that GVN has run before, so we only perform a pointer comparison.
1738 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001739 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001740 if (instruction->GetLeft() == instruction->GetRight()) {
1741 // Replace code looking like
1742 // OR dst, src, src
1743 // with
1744 // src
1745 instruction->ReplaceWith(instruction->GetLeft());
1746 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001747 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001748 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001749 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001750
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001751 if (TryDeMorganNegationFactoring(instruction)) return;
1752
Anton Kirilove14dc862016-05-13 17:56:15 +01001753 if (TryReplaceWithRotate(instruction)) {
1754 return;
1755 }
1756
1757 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1758 // so no need to return.
1759 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001760}
1761
1762void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1763 VisitShift(instruction);
1764}
1765
1766void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1767 VisitShift(instruction);
1768}
1769
1770void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1771 HConstant* input_cst = instruction->GetConstantRight();
1772 HInstruction* input_other = instruction->GetLeastConstantLeft();
1773
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 DataType::Type type = instruction->GetType();
1775 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001776 return;
1777 }
1778
Roland Levillain1a653882016-03-18 18:05:57 +00001779 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001780 // Replace code looking like
1781 // SUB dst, src, 0
1782 // with
1783 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001784 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1785 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1786 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001787 instruction->ReplaceWith(input_other);
1788 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001789 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001790 return;
1791 }
1792
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001793 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001794 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001795
Alexandre Rames188d4312015-04-09 18:30:21 +01001796 HInstruction* left = instruction->GetLeft();
1797 HInstruction* right = instruction->GetRight();
1798 if (left->IsConstant()) {
1799 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001800 // Replace code looking like
1801 // SUB dst, 0, src
1802 // with
1803 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001804 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001805 // `x` is `0.0`, the former expression yields `0.0`, while the later
1806 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001807 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001808 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001809 RecordSimplification();
1810 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001811 }
1812 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001813
1814 if (left->IsNeg() && right->IsNeg()) {
1815 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1816 return;
1817 }
1818 }
1819
1820 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1821 // Replace code looking like
1822 // NEG tmp, b
1823 // SUB dst, a, tmp
1824 // with
1825 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001826 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001827 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1828 RecordSimplification();
1829 right->GetBlock()->RemoveInstruction(right);
1830 return;
1831 }
1832
1833 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1834 // Replace code looking like
1835 // NEG tmp, a
1836 // SUB dst, tmp, b
1837 // with
1838 // ADD tmp, a, b
1839 // NEG dst, tmp
1840 // The second version is not intrinsically better, but enables more
1841 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001842 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01001843 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001844 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01001845 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1846 instruction->ReplaceWith(neg);
1847 instruction->GetBlock()->RemoveInstruction(instruction);
1848 RecordSimplification();
1849 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001850 return;
1851 }
1852
1853 if (TrySubtractionChainSimplification(instruction)) {
1854 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001855 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001856
1857 if (left->IsAdd()) {
1858 // Replace code patterns looking like
1859 // ADD dst1, x, y ADD dst1, x, y
1860 // SUB dst2, dst1, y SUB dst2, dst1, x
1861 // with
1862 // ADD dst1, x, y
1863 // SUB instruction is not needed in this case, we may use
1864 // one of inputs of ADD instead.
1865 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001866 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001867 if (left->InputAt(1) == right) {
1868 instruction->ReplaceWith(left->InputAt(0));
1869 RecordSimplification();
1870 instruction->GetBlock()->RemoveInstruction(instruction);
1871 return;
1872 } else if (left->InputAt(0) == right) {
1873 instruction->ReplaceWith(left->InputAt(1));
1874 RecordSimplification();
1875 instruction->GetBlock()->RemoveInstruction(instruction);
1876 return;
1877 }
1878 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001879}
1880
1881void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1882 VisitShift(instruction);
1883}
1884
1885void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1886 HConstant* input_cst = instruction->GetConstantRight();
1887 HInstruction* input_other = instruction->GetLeastConstantLeft();
1888
Roland Levillain1a653882016-03-18 18:05:57 +00001889 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001890 // Replace code looking like
1891 // XOR dst, src, 0
1892 // with
1893 // src
1894 instruction->ReplaceWith(input_other);
1895 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001896 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001897 return;
1898 }
1899
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001900 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001901 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001902 // Replace code looking like
1903 // XOR dst, src, 1
1904 // with
1905 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001906 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001907 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1908 RecordSimplification();
1909 return;
1910 }
1911
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001912 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1913 // Replace code looking like
1914 // XOR dst, src, 0xFFF...FF
1915 // with
1916 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001917 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001918 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001919 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001920 return;
1921 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001922
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001923 HInstruction* left = instruction->GetLeft();
1924 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001925 if (((left->IsNot() && right->IsNot()) ||
1926 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001927 left->HasOnlyOneNonEnvironmentUse() &&
1928 right->HasOnlyOneNonEnvironmentUse()) {
1929 // Replace code looking like
1930 // NOT nota, a
1931 // NOT notb, b
1932 // XOR dst, nota, notb
1933 // with
1934 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001935 instruction->ReplaceInput(left->InputAt(0), 0);
1936 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001937 left->GetBlock()->RemoveInstruction(left);
1938 right->GetBlock()->RemoveInstruction(right);
1939 RecordSimplification();
1940 return;
1941 }
1942
Anton Kirilove14dc862016-05-13 17:56:15 +01001943 if (TryReplaceWithRotate(instruction)) {
1944 return;
1945 }
1946
1947 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1948 // so no need to return.
1949 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001950}
1951
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001952void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1953 HInstruction* argument = instruction->InputAt(1);
1954 HInstruction* receiver = instruction->InputAt(0);
1955 if (receiver == argument) {
1956 // Because String.equals is an instance call, the receiver is
1957 // a null check if we don't know it's null. The argument however, will
1958 // be the actual object. So we cannot end up in a situation where both
1959 // are equal but could be null.
1960 DCHECK(CanEnsureNotNullAt(argument, instruction));
1961 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1962 instruction->GetBlock()->RemoveInstruction(instruction);
1963 } else {
1964 StringEqualsOptimizations optimizations(instruction);
1965 if (CanEnsureNotNullAt(argument, instruction)) {
1966 optimizations.SetArgumentNotNull();
1967 }
1968 ScopedObjectAccess soa(Thread::Current());
1969 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1970 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1971 optimizations.SetArgumentIsString();
1972 }
1973 }
1974}
1975
Roland Levillain22c49222016-03-18 14:04:28 +00001976void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1977 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001978 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001979 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001980 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001981 HInstruction* value = invoke->InputAt(0);
1982 HInstruction* distance = invoke->InputAt(1);
1983 // Replace the invoke with an HRor.
1984 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001985 // Unconditionally set the type of the negated distance to `int`,
1986 // as shift and rotate operations expect a 32-bit (or narrower)
1987 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001988 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001989 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1990 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001991 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001992 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1993 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001994 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001995 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1996 clinit->GetBlock()->RemoveInstruction(clinit);
1997 HInstruction* ldclass = clinit->InputAt(0);
1998 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1999 ldclass->GetBlock()->RemoveInstruction(ldclass);
2000 }
2001 }
2002}
2003
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002004static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2005 if (potential_length->IsArrayLength()) {
2006 return potential_length->InputAt(0) == potential_array;
2007 }
2008
2009 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002010 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002011 }
2012
2013 return false;
2014}
2015
2016void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2017 HInstruction* source = instruction->InputAt(0);
2018 HInstruction* destination = instruction->InputAt(2);
2019 HInstruction* count = instruction->InputAt(4);
2020 SystemArrayCopyOptimizations optimizations(instruction);
2021 if (CanEnsureNotNullAt(source, instruction)) {
2022 optimizations.SetSourceIsNotNull();
2023 }
2024 if (CanEnsureNotNullAt(destination, instruction)) {
2025 optimizations.SetDestinationIsNotNull();
2026 }
2027 if (destination == source) {
2028 optimizations.SetDestinationIsSource();
2029 }
2030
2031 if (IsArrayLengthOf(count, source)) {
2032 optimizations.SetCountIsSourceLength();
2033 }
2034
2035 if (IsArrayLengthOf(count, destination)) {
2036 optimizations.SetCountIsDestinationLength();
2037 }
2038
2039 {
2040 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002041 DataType::Type source_component_type = DataType::Type::kVoid;
2042 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002043 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2044 if (destination_rti.IsValid()) {
2045 if (destination_rti.IsObjectArray()) {
2046 if (destination_rti.IsExact()) {
2047 optimizations.SetDoesNotNeedTypeCheck();
2048 }
2049 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002050 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002051 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002052 destination_component_type = DataTypeFromPrimitive(
2053 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002054 optimizations.SetDestinationIsPrimitiveArray();
2055 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2056 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002057 }
2058 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002059 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2060 if (source_rti.IsValid()) {
2061 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2062 optimizations.SetDoesNotNeedTypeCheck();
2063 }
2064 if (source_rti.IsPrimitiveArrayClass()) {
2065 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002066 source_component_type = DataTypeFromPrimitive(
2067 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002068 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2069 optimizations.SetSourceIsNonPrimitiveArray();
2070 }
2071 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002072 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002073 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002074 (source_component_type == destination_component_type)) {
2075 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2076 PointerSize image_size = class_linker->GetImagePointerSize();
2077 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2078 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2079 ArtMethod* method = nullptr;
2080 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002081 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002082 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002083 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002084 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002085 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002086 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002087 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002088 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002089 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002090 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002091 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002092 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002093 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002094 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002095 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002096 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002097 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002098 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002099 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002100 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002101 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002102 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002103 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002104 break;
2105 default:
2106 LOG(FATAL) << "Unreachable";
2107 }
2108 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002109 DCHECK(method->IsStatic());
2110 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002111 invoke->SetResolvedMethod(method);
2112 // Sharpen the new invoke. Note that we do not update the dex method index of
2113 // the invoke, as we would need to look it up in the current dex file, and it
2114 // is unlikely that it exists. The most usual situation for such typed
2115 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002116 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002117 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002118 }
2119}
2120
Roland Levillaina5c4a402016-03-15 15:02:50 +00002121void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2122 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002123 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002124 DCHECK(invoke->IsInvokeStaticOrDirect());
2125 uint32_t dex_pc = invoke->GetDexPc();
2126 HInstruction* left = invoke->InputAt(0);
2127 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002128 if (!is_signum) {
2129 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002130 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002131 right = GetGraph()->GetLongConstant(0);
2132 } else {
2133 right = GetGraph()->GetIntConstant(0);
2134 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002135 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002136 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2137 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2138}
2139
Aart Bik75a38b22016-02-17 10:41:50 -08002140void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2141 DCHECK(invoke->IsInvokeStaticOrDirect());
2142 uint32_t dex_pc = invoke->GetDexPc();
2143 // IsNaN(x) is the same as x != x.
2144 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002145 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002146 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002147 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2148}
2149
Aart Bik2a6aad92016-02-25 11:32:32 -08002150void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2151 DCHECK(invoke->IsInvokeStaticOrDirect());
2152 uint32_t dex_pc = invoke->GetDexPc();
2153 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002154 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002155 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2156 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002157 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002158 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2159 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2160 kNeedsEnvironmentOrCache,
2161 kNoSideEffects,
2162 kNoThrow);
2163 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002164 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002165 nan = GetGraph()->GetIntConstant(0x7fc00000);
2166 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2167 kNeedsEnvironmentOrCache,
2168 kNoSideEffects,
2169 kNoThrow);
2170 }
2171 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002172 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002173 condition->SetBias(ComparisonBias::kLtBias);
2174 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2175 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002176 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002177 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2178 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2179}
2180
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002181void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2182 HInstruction* str = invoke->InputAt(0);
2183 HInstruction* index = invoke->InputAt(1);
2184 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002185 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002186 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2187 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002188 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002189 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002190 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002191 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002192 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002193 HArrayGet* array_get = new (allocator) HArrayGet(str,
2194 bounds_check,
2195 DataType::Type::kUint16,
2196 SideEffects::None(), // Strings are immutable.
2197 dex_pc,
2198 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002199 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2200 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2201 GetGraph()->SetHasBoundsChecks(true);
2202}
2203
Vladimir Markodce016e2016-04-28 13:10:02 +01002204void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2205 HInstruction* str = invoke->InputAt(0);
2206 uint32_t dex_pc = invoke->GetDexPc();
2207 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2208 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002209 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002210 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002211 HInstruction* replacement;
2212 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2213 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2214 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2215 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002216 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002217 replacement = equal;
2218 } else {
2219 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2220 replacement = length;
2221 }
2222 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2223}
2224
Aart Bikff7d89c2016-11-07 08:49:28 -08002225// This method should only be used on intrinsics whose sole way of throwing an
2226// exception is raising a NPE when the nth argument is null. If that argument
2227// is provably non-null, we can clear the flag.
2228void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2229 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002230 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002231 invoke->SetCanThrow(false);
2232 }
2233}
2234
Aart Bik71bf7b42016-11-16 10:17:46 -08002235// Methods that return "this" can replace the returned value with the receiver.
2236void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2237 if (invoke->HasUses()) {
2238 HInstruction* receiver = invoke->InputAt(0);
2239 invoke->ReplaceWith(receiver);
2240 RecordSimplification();
2241 }
2242}
2243
2244// Helper method for StringBuffer escape analysis.
2245static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2246 if (user->IsInvokeStaticOrDirect()) {
2247 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002248 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2249 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002250 user->InputAt(0) == reference;
2251 } else if (user->IsInvokeVirtual()) {
2252 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2253 case Intrinsics::kStringBufferLength:
2254 case Intrinsics::kStringBufferToString:
2255 DCHECK_EQ(user->InputAt(0), reference);
2256 return true;
2257 case Intrinsics::kStringBufferAppend:
2258 // Returns "this", so only okay if no further uses.
2259 DCHECK_EQ(user->InputAt(0), reference);
2260 DCHECK_NE(user->InputAt(1), reference);
2261 return !user->HasUses();
2262 default:
2263 break;
2264 }
2265 }
2266 return false;
2267}
2268
2269// Certain allocation intrinsics are not removed by dead code elimination
2270// because of potentially throwing an OOM exception or other side effects.
2271// This method removes such intrinsics when special circumstances allow.
2272void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2273 if (!invoke->HasUses()) {
2274 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2275 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2276 // call does not escape since only thread-local synchronization may be removed.
2277 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2278 HInstruction* receiver = invoke->InputAt(0);
2279 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2280 invoke->GetBlock()->RemoveInstruction(invoke);
2281 RecordSimplification();
2282 }
2283 }
2284}
2285
Vladimir Markoca6fff82017-10-03 14:49:14 +01002286void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2287 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002288 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002289 HMemoryBarrier* mem_barrier =
2290 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002291 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2292}
2293
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002294void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002295 switch (instruction->GetIntrinsic()) {
2296 case Intrinsics::kStringEquals:
2297 SimplifyStringEquals(instruction);
2298 break;
2299 case Intrinsics::kSystemArrayCopy:
2300 SimplifySystemArrayCopy(instruction);
2301 break;
2302 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002303 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002304 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002305 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002306 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002307 break;
2308 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002309 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002310 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002311 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002312 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002313 break;
2314 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002315 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002316 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002317 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002318 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002319 break;
2320 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002321 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002322 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002323 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002324 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002325 break;
2326 case Intrinsics::kFloatIsNaN:
2327 case Intrinsics::kDoubleIsNaN:
2328 SimplifyIsNaN(instruction);
2329 break;
2330 case Intrinsics::kFloatFloatToIntBits:
2331 case Intrinsics::kDoubleDoubleToLongBits:
2332 SimplifyFP2Int(instruction);
2333 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002334 case Intrinsics::kStringCharAt:
2335 SimplifyStringCharAt(instruction);
2336 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002337 case Intrinsics::kStringIsEmpty:
2338 case Intrinsics::kStringLength:
2339 SimplifyStringIsEmptyOrLength(instruction);
2340 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002341 case Intrinsics::kStringStringIndexOf:
2342 case Intrinsics::kStringStringIndexOfAfter:
2343 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2344 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002345 case Intrinsics::kStringBufferAppend:
2346 case Intrinsics::kStringBuilderAppend:
2347 SimplifyReturnThis(instruction);
2348 break;
2349 case Intrinsics::kStringBufferToString:
2350 case Intrinsics::kStringBuilderToString:
2351 SimplifyAllocationIntrinsic(instruction);
2352 break;
Aart Bik11932592016-03-08 12:42:25 -08002353 case Intrinsics::kUnsafeLoadFence:
2354 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2355 break;
2356 case Intrinsics::kUnsafeStoreFence:
2357 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2358 break;
2359 case Intrinsics::kUnsafeFullFence:
2360 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2361 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002362 case Intrinsics::kVarHandleFullFence:
2363 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2364 break;
2365 case Intrinsics::kVarHandleAcquireFence:
2366 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2367 break;
2368 case Intrinsics::kVarHandleReleaseFence:
2369 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2370 break;
2371 case Intrinsics::kVarHandleLoadLoadFence:
2372 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2373 break;
2374 case Intrinsics::kVarHandleStoreStoreFence:
2375 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2376 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002377 default:
2378 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002379 }
2380}
2381
Aart Bikbb245d12015-10-19 11:05:03 -07002382void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2383 HInstruction* cond = deoptimize->InputAt(0);
2384 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002385 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002386 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002387 if (deoptimize->GuardsAnInput()) {
2388 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2389 }
Aart Bikbb245d12015-10-19 11:05:03 -07002390 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2391 } else {
2392 // Always deopt.
2393 }
2394 }
2395}
2396
Anton Kirilove14dc862016-05-13 17:56:15 +01002397// Replace code looking like
2398// OP y, x, const1
2399// OP z, y, const2
2400// with
2401// OP z, x, const3
2402// where OP is both an associative and a commutative operation.
2403bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2404 HBinaryOperation* instruction) {
2405 DCHECK(instruction->IsCommutative());
2406
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002407 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002408 return false;
2409 }
2410
2411 HInstruction* left = instruction->GetLeft();
2412 HInstruction* right = instruction->GetRight();
2413 // Variable names as described above.
2414 HConstant* const2;
2415 HBinaryOperation* y;
2416
2417 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2418 const2 = right->AsConstant();
2419 y = left->AsBinaryOperation();
2420 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2421 const2 = left->AsConstant();
2422 y = right->AsBinaryOperation();
2423 } else {
2424 // The node does not match the pattern.
2425 return false;
2426 }
2427
2428 // If `y` has more than one use, we do not perform the optimization
2429 // because it might increase code size (e.g. if the new constant is
2430 // no longer encodable as an immediate operand in the target ISA).
2431 if (!y->HasOnlyOneNonEnvironmentUse()) {
2432 return false;
2433 }
2434
2435 // GetConstantRight() can return both left and right constants
2436 // for commutative operations.
2437 HConstant* const1 = y->GetConstantRight();
2438 if (const1 == nullptr) {
2439 return false;
2440 }
2441
2442 instruction->ReplaceInput(const1, 0);
2443 instruction->ReplaceInput(const2, 1);
2444 HConstant* const3 = instruction->TryStaticEvaluation();
2445 DCHECK(const3 != nullptr);
2446 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2447 instruction->ReplaceInput(const3, 1);
2448 RecordSimplification();
2449 return true;
2450}
2451
2452static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2453 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2454}
2455
2456// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002457static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002458 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002459 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002460 return HAdd::Compute<int32_t>(x, y);
2461 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002462 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002463 return HAdd::Compute<int64_t>(x, y);
2464 }
2465}
2466
2467// Helper function that handles the child classes of HConstant
2468// and returns an integer with the appropriate sign.
2469static int64_t GetValue(HConstant* constant, bool is_negated) {
2470 int64_t ret = Int64FromConstant(constant);
2471 return is_negated ? -ret : ret;
2472}
2473
2474// Replace code looking like
2475// OP1 y, x, const1
2476// OP2 z, y, const2
2477// with
2478// OP3 z, x, const3
2479// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2480bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2481 HBinaryOperation* instruction) {
2482 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2483
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002484 DataType::Type type = instruction->GetType();
2485 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002486 return false;
2487 }
2488
2489 HInstruction* left = instruction->GetLeft();
2490 HInstruction* right = instruction->GetRight();
2491 // Variable names as described above.
2492 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2493 if (const2 == nullptr) {
2494 return false;
2495 }
2496
2497 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2498 ? left->AsBinaryOperation()
2499 : AsAddOrSub(right);
2500 // If y has more than one use, we do not perform the optimization because
2501 // it might increase code size (e.g. if the new constant is no longer
2502 // encodable as an immediate operand in the target ISA).
2503 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2504 return false;
2505 }
2506
2507 left = y->GetLeft();
2508 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2509 if (const1 == nullptr) {
2510 return false;
2511 }
2512
2513 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2514 // If both inputs are constants, let the constant folding pass deal with it.
2515 if (x->IsConstant()) {
2516 return false;
2517 }
2518
2519 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2520 int64_t const2_val = GetValue(const2, is_const2_negated);
2521 bool is_y_negated = (y == right) && instruction->IsSub();
2522 right = y->GetRight();
2523 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2524 int64_t const1_val = GetValue(const1, is_const1_negated);
2525 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2526 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2527 HBasicBlock* block = instruction->GetBlock();
2528 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002529 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002530 HInstruction* z;
2531
2532 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002533 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002534 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002535 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002536 }
2537
2538 block->ReplaceAndRemoveInstructionWith(instruction, z);
2539 RecordSimplification();
2540 return true;
2541}
2542
Lena Djokicbc5460b2017-07-20 16:07:36 +02002543void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2544 if (TryCombineVecMultiplyAccumulate(instruction)) {
2545 RecordSimplification();
2546 }
2547}
2548
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002549} // namespace art