blob: f493b66cfd170ade928fb45cf9ef8da079fd4548 [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 Markob4eb1b12018-05-24 11:09:38 +010021#include "class_root.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010022#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080023#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070026#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028
Nicolas Geoffray3c049742014-09-24 18:10:46 +010029namespace art {
30
Artem Serovcced8ba2017-07-19 18:18:09 +010031// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
32// is replaced with its copy if it is clonable.
33static constexpr bool kTestInstructionClonerExhaustively = false;
34
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010035class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000036 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 InstructionSimplifierVisitor(HGraph* graph,
38 CodeGenerator* codegen,
39 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010040 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000041 codegen_(codegen),
Alexandre Rames188d4312015-04-09 18:30:21 +010042 stats_(stats) {}
43
Aart Bik24773202018-04-26 10:28:51 -070044 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000045
46 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010047 void RecordSimplification() {
48 simplification_occurred_ = true;
49 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000050 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010051 }
52
Scott Wakeling40a04bf2015-12-11 09:50:36 +000053 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotate(HBinaryOperation* instruction);
55 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
56 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
57 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58
Alexandre Rames188d4312015-04-09 18:30:21 +010059 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000060 // `op` should be either HOr or HAnd.
61 // De Morgan's laws:
62 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
63 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010064 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
65 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020066 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010067
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000068 void VisitShift(HBinaryOperation* shift);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000069 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010070 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
71 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010072 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
73 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000074 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000075 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000076 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080077 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000078 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Aart Bikc6eec4b2018-03-29 17:22:00 -070079 void VisitAbs(HAbs* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000080 void VisitAdd(HAdd* instruction) OVERRIDE;
81 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040082 void VisitCondition(HCondition* instruction) OVERRIDE;
83 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
84 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
85 void VisitLessThan(HLessThan* condition) OVERRIDE;
86 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060087 void VisitBelow(HBelow* condition) OVERRIDE;
88 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
89 void VisitAbove(HAbove* condition) OVERRIDE;
90 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000091 void VisitDiv(HDiv* instruction) OVERRIDE;
92 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010093 void VisitNeg(HNeg* instruction) OVERRIDE;
94 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000095 void VisitOr(HOr* instruction) OVERRIDE;
96 void VisitShl(HShl* instruction) OVERRIDE;
97 void VisitShr(HShr* instruction) OVERRIDE;
98 void VisitSub(HSub* instruction) OVERRIDE;
99 void VisitUShr(HUShr* instruction) OVERRIDE;
100 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +0000101 void VisitSelect(HSelect* select) OVERRIDE;
102 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100103 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100104 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700105 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200106 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100107
108 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000109
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100111 void SimplifySystemArrayCopy(HInvoke* invoke);
112 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100113 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800114 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800115 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100116 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100117 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000118 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800119 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800120 void SimplifyReturnThis(HInvoke* invoke);
121 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800122 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800123 void SimplifyMin(HInvoke* invoke, DataType::Type type);
124 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800125 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100126
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000127 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000128 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100129 bool simplification_occurred_ = false;
130 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700131 // We ensure we do not loop infinitely. The value should not be too high, since that
132 // would allow looping around the same basic block too many times. The value should
133 // not be too low either, however, since we want to allow revisiting a basic block
134 // with many statements and simplifications at least once.
135 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000136};
137
Aart Bik24773202018-04-26 10:28:51 -0700138bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100139 if (kTestInstructionClonerExhaustively) {
140 CloneAndReplaceInstructionVisitor visitor(graph_);
141 visitor.VisitReversePostOrder();
142 }
143
Vladimir Markobb089b62018-06-28 17:30:16 +0100144 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700145 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100146}
147
Aart Bik24773202018-04-26 10:28:51 -0700148bool InstructionSimplifierVisitor::Run() {
149 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100150 // Iterate in reverse post order to open up more simplifications to users
151 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100152 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100153 // The simplification of an instruction to another instruction may yield
154 // possibilities for other simplifications. So although we perform a reverse
155 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100156 do {
157 simplification_occurred_ = false;
158 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700159 if (simplification_occurred_) {
160 didSimplify = true;
161 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100162 } while (simplification_occurred_ &&
163 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100164 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100165 }
Aart Bik24773202018-04-26 10:28:51 -0700166 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100167}
168
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000169namespace {
170
171bool AreAllBitsSet(HConstant* constant) {
172 return Int64FromConstant(constant) == -1;
173}
174
175} // namespace
176
Alexandre Rames188d4312015-04-09 18:30:21 +0100177// Returns true if the code was simplified to use only one negation operation
178// after the binary operation instead of one on each of the inputs.
179bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
180 DCHECK(binop->IsAdd() || binop->IsSub());
181 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
182 HNeg* left_neg = binop->GetLeft()->AsNeg();
183 HNeg* right_neg = binop->GetRight()->AsNeg();
184 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
185 !right_neg->HasOnlyOneNonEnvironmentUse()) {
186 return false;
187 }
188 // Replace code looking like
189 // NEG tmp1, a
190 // NEG tmp2, b
191 // ADD dst, tmp1, tmp2
192 // with
193 // ADD tmp, a, b
194 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600195 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
196 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
197 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100198 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600199 return false;
200 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100201 binop->ReplaceInput(left_neg->GetInput(), 0);
202 binop->ReplaceInput(right_neg->GetInput(), 1);
203 left_neg->GetBlock()->RemoveInstruction(left_neg);
204 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100205 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100206 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
207 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
208 RecordSimplification();
209 return true;
210}
211
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000212bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
213 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100214 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000215 HInstruction* left = op->GetLeft();
216 HInstruction* right = op->GetRight();
217
218 // We can apply De Morgan's laws if both inputs are Not's and are only used
219 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000220 if (((left->IsNot() && right->IsNot()) ||
221 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000222 left->HasOnlyOneNonEnvironmentUse() &&
223 right->HasOnlyOneNonEnvironmentUse()) {
224 // Replace code looking like
225 // NOT nota, a
226 // NOT notb, b
227 // AND dst, nota, notb (respectively OR)
228 // with
229 // OR or, a, b (respectively AND)
230 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000231 HInstruction* src_left = left->InputAt(0);
232 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000233 uint32_t dex_pc = op->GetDexPc();
234
235 // Remove the negations on the inputs.
236 left->ReplaceWith(src_left);
237 right->ReplaceWith(src_right);
238 left->GetBlock()->RemoveInstruction(left);
239 right->GetBlock()->RemoveInstruction(right);
240
241 // Replace the `HAnd` or `HOr`.
242 HBinaryOperation* hbin;
243 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100244 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000245 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100246 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000247 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000248 HInstruction* hnot;
249 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100250 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000251 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100252 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000253 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000254
255 op->GetBlock()->InsertInstructionBefore(hbin, op);
256 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
257
258 RecordSimplification();
259 return true;
260 }
261
262 return false;
263}
264
Lena Djokicbc5460b2017-07-20 16:07:36 +0200265bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200267 InstructionSet isa = codegen_->GetInstructionSet();
268 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000269 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100270 if (!(type == DataType::Type::kUint8 ||
271 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100272 type == DataType::Type::kUint16 ||
273 type == DataType::Type::kInt16 ||
274 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200275 return false;
276 }
277 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000278 case InstructionSet::kMips:
279 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100280 if (!(type == DataType::Type::kUint8 ||
281 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100282 type == DataType::Type::kUint16 ||
283 type == DataType::Type::kInt16 ||
284 type == DataType::Type::kInt32 ||
285 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200286 return false;
287 }
288 break;
289 default:
290 return false;
291 }
292
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100293 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200294
295 if (mul->HasOnlyOneNonEnvironmentUse()) {
296 HInstruction* use = mul->GetUses().front().GetUser();
297 if (use->IsVecAdd() || use->IsVecSub()) {
298 // Replace code looking like
299 // VECMUL tmp, x, y
300 // VECADD/SUB dst, acc, tmp
301 // with
302 // VECMULACC dst, acc, x, y
303 // Note that we do not want to (unconditionally) perform the merge when the
304 // multiplication has multiple uses and it can be merged in all of them.
305 // Multiple uses could happen on the same control-flow path, and we would
306 // then increase the amount of work. In the future we could try to evaluate
307 // whether all uses are on different control-flow paths (using dominance and
308 // reverse-dominance information) and only perform the merge when they are.
309 HInstruction* accumulator = nullptr;
310 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
311 HInstruction* binop_left = binop->GetLeft();
312 HInstruction* binop_right = binop->GetRight();
313 // This is always true since the `HVecMul` has only one use (which is checked above).
314 DCHECK_NE(binop_left, binop_right);
315 if (binop_right == mul) {
316 accumulator = binop_left;
317 } else if (use->IsVecAdd()) {
318 DCHECK_EQ(binop_left, mul);
319 accumulator = binop_right;
320 }
321
322 HInstruction::InstructionKind kind =
323 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
324 if (accumulator != nullptr) {
325 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100326 new (allocator) HVecMultiplyAccumulate(allocator,
327 kind,
328 accumulator,
329 mul->GetLeft(),
330 mul->GetRight(),
331 binop->GetPackedType(),
332 binop->GetVectorLength(),
333 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200334
335 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
336 DCHECK(!mul->HasUses());
337 mul->GetBlock()->RemoveInstruction(mul);
338 return true;
339 }
340 }
341 }
342
343 return false;
344}
345
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000346void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
347 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100348 HInstruction* shift_amount = instruction->GetRight();
349 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000350
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100351 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100352 ? kMaxLongShiftDistance
353 : kMaxIntShiftDistance;
354
355 if (shift_amount->IsConstant()) {
356 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700357 int64_t masked_cst = cst & implicit_mask;
358 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400359 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100360 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400361 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100362 // value
363 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400364 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100365 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100366 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700367 } else if (masked_cst != cst) {
368 // Replace code looking like
369 // SHL dst, value, cst
370 // where cst exceeds maximum distance with the equivalent
371 // SHL dst, value, cst & implicit_mask
372 // (as defined by shift semantics). This ensures other
373 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100374 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700375 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
376 RecordSimplification();
377 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100378 }
379 }
380
381 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100382 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
383 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100384 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100385 // AND adjusted_shift, shift, <superset of implicit mask>
386 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
387 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
388 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100389 // with
390 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100391 if (shift_amount->IsAnd() ||
392 shift_amount->IsOr() ||
393 shift_amount->IsXor() ||
394 shift_amount->IsAdd() ||
395 shift_amount->IsSub()) {
396 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
397 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
398 HConstant* mask = bin_op->GetConstantRight();
399 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
400 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100401 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100402 return;
403 }
404 } else if (shift_amount->IsTypeConversion()) {
405 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
406 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
407 // Non-integral and 64-bit source types require an explicit type conversion.
408 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
409 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
410 RecordSimplification();
411 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400412 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000413 }
414}
415
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000416static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
417 return (sub->GetRight() == other &&
418 sub->GetLeft()->IsConstant() &&
419 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
420}
421
422bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
423 HUShr* ushr,
424 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000425 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100426 HRor* ror =
427 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000428 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
429 if (!ushr->HasUses()) {
430 ushr->GetBlock()->RemoveInstruction(ushr);
431 }
432 if (!ushr->GetRight()->HasUses()) {
433 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
434 }
435 if (!shl->HasUses()) {
436 shl->GetBlock()->RemoveInstruction(shl);
437 }
438 if (!shl->GetRight()->HasUses()) {
439 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
440 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100441 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000442 return true;
443}
444
445// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
446bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000447 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
448 HInstruction* left = op->GetLeft();
449 HInstruction* right = op->GetRight();
450 // If we have an UShr and a Shl (in either order).
451 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
452 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
453 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100454 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000455 if (ushr->GetType() == shl->GetType() &&
456 ushr->GetLeft() == shl->GetLeft()) {
457 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
458 // Shift distances are both constant, try replacing with Ror if they
459 // add up to the register size.
460 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
461 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
462 // Shift distances are potentially of the form x and (reg_size - x).
463 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
464 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
465 // Shift distances are potentially of the form d and -d.
466 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
467 }
468 }
469 }
470 return false;
471}
472
473// Try replacing code looking like (x >>> #rdist OP x << #ldist):
474// UShr dst, x, #rdist
475// Shl tmp, x, #ldist
476// OP dst, dst, tmp
477// or like (x >>> #rdist OP x << #-ldist):
478// UShr dst, x, #rdist
479// Shl tmp, x, #-ldist
480// OP dst, dst, tmp
481// with
482// Ror dst, x, #rdist
483bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
484 HUShr* ushr,
485 HShl* shl) {
486 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100487 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000488 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
489 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
490 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
491 ReplaceRotateWithRor(op, ushr, shl);
492 return true;
493 }
494 return false;
495}
496
497// Replace code looking like (x >>> -d OP x << d):
498// Neg neg, d
499// UShr dst, x, neg
500// Shl tmp, x, d
501// OP dst, dst, tmp
502// with
503// Neg neg, d
504// Ror dst, x, neg
505// *** OR ***
506// Replace code looking like (x >>> d OP x << -d):
507// UShr dst, x, d
508// Neg neg, d
509// Shl tmp, x, neg
510// OP dst, dst, tmp
511// with
512// Ror dst, x, d
513bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
514 HUShr* ushr,
515 HShl* shl) {
516 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
517 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
518 bool neg_is_left = shl->GetRight()->IsNeg();
519 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
520 // And the shift distance being negated is the distance being shifted the other way.
521 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
522 ReplaceRotateWithRor(op, ushr, shl);
523 }
524 return false;
525}
526
527// Try replacing code looking like (x >>> d OP x << (#bits - d)):
528// UShr dst, x, d
529// Sub ld, #bits, d
530// Shl tmp, x, ld
531// OP dst, dst, tmp
532// with
533// Ror dst, x, d
534// *** OR ***
535// Replace code looking like (x >>> (#bits - d) OP x << d):
536// Sub rd, #bits, d
537// UShr dst, x, rd
538// Shl tmp, x, d
539// OP dst, dst, tmp
540// with
541// Neg neg, d
542// Ror dst, x, neg
543bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
544 HUShr* ushr,
545 HShl* shl) {
546 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
547 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100548 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000549 HInstruction* shl_shift = shl->GetRight();
550 HInstruction* ushr_shift = ushr->GetRight();
551 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
552 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
553 return ReplaceRotateWithRor(op, ushr, shl);
554 }
555 return false;
556}
557
Calin Juravle10e244f2015-01-26 18:54:32 +0000558void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
559 HInstruction* obj = null_check->InputAt(0);
560 if (!obj->CanBeNull()) {
561 null_check->ReplaceWith(obj);
562 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000563 if (stats_ != nullptr) {
564 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
565 }
566 }
567}
568
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100569bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
570 if (!input->CanBeNull()) {
571 return true;
572 }
573
Vladimir Marko46817b82016-03-29 12:21:58 +0100574 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
575 HInstruction* user = use.GetUser();
576 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100577 return true;
578 }
579 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100580
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100581 return false;
582}
583
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100584// Returns whether doing a type test between the class of `object` against `klass` has
585// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000586static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
587 HInstruction* object,
588 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000589 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
590 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
591 ScopedObjectAccess soa(Thread::Current());
592 if (!obj_rti.IsValid()) {
593 // We run the simplifier before the reference type propagation so type info might not be
594 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100595 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000596 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100597
Calin Juravle98893e12015-10-02 21:05:03 +0100598 if (!class_rti.IsValid()) {
599 // Happens when the loaded class is unresolved.
600 return false;
601 }
602 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000603 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100604 *outcome = true;
605 return true;
606 } else if (obj_rti.IsExact()) {
607 // The test failed at compile time so will also fail at runtime.
608 *outcome = false;
609 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100610 } else if (!class_rti.IsInterface()
611 && !obj_rti.IsInterface()
612 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100613 // Different type hierarchy. The test will fail.
614 *outcome = false;
615 return true;
616 }
617 return false;
618}
619
620void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
621 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000622 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
623 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100624 // If we need to perform an access check we cannot remove the instruction.
625 return;
626 }
627
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100628 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100629 check_cast->ClearMustDoNullCheck();
630 }
631
632 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000633 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700634 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100635 return;
636 }
637
Roland Levillain05e34f42018-05-24 13:19:05 +0000638 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
639 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000640 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000641 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100642 if (outcome) {
643 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700644 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000645 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
646 HLoadClass* load_class = check_cast->GetTargetClass();
647 if (!load_class->HasUses()) {
648 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
649 // However, here we know that it cannot because the checkcast was successfull, hence
650 // the class was already loaded.
651 load_class->GetBlock()->RemoveInstruction(load_class);
652 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700653 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654 } else {
655 // Don't do anything for exceptional cases for now. Ideally we should remove
656 // all instructions and blocks this instruction dominates.
657 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000658 }
659}
660
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100661void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100662 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000663 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
664 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100665 // If we need to perform an access check we cannot remove the instruction.
666 return;
667 }
668
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100669 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100670 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100671 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100672 instruction->ClearMustDoNullCheck();
673 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100674
675 HGraph* graph = GetGraph();
676 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000677 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100678 instruction->ReplaceWith(graph->GetIntConstant(0));
679 instruction->GetBlock()->RemoveInstruction(instruction);
680 RecordSimplification();
681 return;
682 }
683
Roland Levillain05e34f42018-05-24 13:19:05 +0000684 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
685 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000686 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000687 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000688 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100689 if (outcome && can_be_null) {
690 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100691 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100692 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
693 instruction->ReplaceWith(test);
694 } else {
695 // We've statically determined the result of the instanceof.
696 instruction->ReplaceWith(graph->GetIntConstant(outcome));
697 }
698 RecordSimplification();
699 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000700 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
701 HLoadClass* load_class = instruction->GetTargetClass();
702 if (!load_class->HasUses()) {
703 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
704 // However, here we know that it cannot because the instanceof check was successfull, hence
705 // the class was already loaded.
706 load_class->GetBlock()->RemoveInstruction(load_class);
707 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700708 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100709 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100710}
711
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100712void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100713 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100714 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100715 instruction->ClearValueCanBeNull();
716 }
717}
718
719void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100720 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100721 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100722 instruction->ClearValueCanBeNull();
723 }
724}
725
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100726static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600727 HInstruction *lhs = cond->InputAt(0);
728 HInstruction *rhs = cond->InputAt(1);
729 switch (cond->GetKind()) {
730 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100731 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600732 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100733 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600734 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100735 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600736 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100737 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600738 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100739 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600740 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100741 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600742 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100743 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600744 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100745 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600746 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100747 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600748 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100749 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600750 default:
751 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
752 }
753 return nullptr;
754}
755
Aart Bik2767f4b2016-10-28 15:03:53 -0700756static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100757 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700758 return true; // input has direct boolean type
759 } else if (cmp->GetUses().HasExactlyOneElement()) {
760 // Comparison also has boolean type if both its input and the instruction
761 // itself feed into the same phi node.
762 HInstruction* user = cmp->GetUses().front().GetUser();
763 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
764 }
765 return false;
766}
767
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000768void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100769 HInstruction* input_const = equal->GetConstantRight();
770 if (input_const != nullptr) {
771 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700772 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100773 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100774 // We are comparing the boolean to a constant which is of type int and can
775 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000776 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100777 // Replace (bool_value == true) with bool_value
778 equal->ReplaceWith(input_value);
779 block->RemoveInstruction(equal);
780 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000781 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700782 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500783 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
784 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100785 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100786 } else {
787 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
788 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
789 block->RemoveInstruction(equal);
790 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100791 }
Mark Mendellc4701932015-04-10 13:18:51 -0400792 } else {
793 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100794 }
Mark Mendellc4701932015-04-10 13:18:51 -0400795 } else {
796 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100797 }
798}
799
David Brazdil0d13fee2015-04-17 14:52:19 +0100800void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
801 HInstruction* input_const = not_equal->GetConstantRight();
802 if (input_const != nullptr) {
803 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700804 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100805 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100806 // We are comparing the boolean to a constant which is of type int and can
807 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000808 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700809 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500810 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
811 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100812 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000813 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100814 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100815 not_equal->ReplaceWith(input_value);
816 block->RemoveInstruction(not_equal);
817 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100818 } else {
819 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
820 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
821 block->RemoveInstruction(not_equal);
822 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100823 }
Mark Mendellc4701932015-04-10 13:18:51 -0400824 } else {
825 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100826 }
Mark Mendellc4701932015-04-10 13:18:51 -0400827 } else {
828 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100829 }
830}
831
832void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000833 HInstruction* input = bool_not->InputAt(0);
834 HInstruction* replace_with = nullptr;
835
836 if (input->IsIntConstant()) {
837 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000838 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000839 replace_with = GetGraph()->GetIntConstant(0);
840 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000841 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000842 replace_with = GetGraph()->GetIntConstant(1);
843 }
844 } else if (input->IsBooleanNot()) {
845 // Replace (!(!bool_value)) with bool_value.
846 replace_with = input->InputAt(0);
847 } else if (input->IsCondition() &&
848 // Don't change FP compares. The definition of compares involving
849 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100850 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000851 // Replace condition with its opposite.
852 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
853 }
854
855 if (replace_with != nullptr) {
856 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100857 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000858 RecordSimplification();
859 }
860}
861
Aart Bik4f7dd342017-09-12 13:12:57 -0700862// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100863static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
864 HInstruction* x,
865 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700866 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800867 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700868 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800869 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
870 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700871}
872
Aart Bik142b9132018-03-14 15:12:59 -0700873// Constructs a new MIN/MAX(x, y) node in the HIR.
874static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
875 HInstruction* x,
876 HInstruction* y,
877 HInstruction* cursor,
878 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700879 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700880 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
881 HBinaryOperation* minmax = nullptr;
882 if (is_min) {
883 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
884 } else {
885 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
886 }
887 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
888 return minmax;
889}
890
Aart Bik4f7dd342017-09-12 13:12:57 -0700891// Returns true if operands a and b consists of widening type conversions
892// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100893static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700894 if (a->IsTypeConversion() && a->GetType() == to_type) {
895 a = a->InputAt(0);
896 }
897 if (b->IsTypeConversion() && b->GetType() == to_type) {
898 b = b->InputAt(0);
899 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100900 DataType::Type type1 = a->GetType();
901 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100902 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
903 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
904 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
905 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
906 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100907 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700908}
909
Aart Bik1d746de2018-03-28 16:30:02 -0700910// Returns an acceptable substitution for "a" on the select
911// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
912static HInstruction* AllowInMinMax(IfCondition cmp,
913 HInstruction* a,
914 HInstruction* b,
915 HInstruction* c) {
916 int64_t value = 0;
917 if (IsInt64AndGet(b, /*out*/ &value) &&
918 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
919 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
920 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
921 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
922 int64_t other_value = Int64FromConstant(other);
923 bool is_max = (cmp == kCondLT || cmp == kCondLE);
924 // Allow the max for a < 100 ? max(a, -100) : ..
925 // or the min for a > -100 ? min(a, 100) : ..
926 if (is_max ? (value >= other_value) : (value <= other_value)) {
927 return c;
928 }
929 }
930 }
931 return nullptr;
932}
933
David Brazdil74eb1b22015-12-14 11:44:01 +0000934void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
935 HInstruction* replace_with = nullptr;
936 HInstruction* condition = select->GetCondition();
937 HInstruction* true_value = select->GetTrueValue();
938 HInstruction* false_value = select->GetFalseValue();
939
940 if (condition->IsBooleanNot()) {
941 // Change ((!cond) ? x : y) to (cond ? y : x).
942 condition = condition->InputAt(0);
943 std::swap(true_value, false_value);
944 select->ReplaceInput(false_value, 0);
945 select->ReplaceInput(true_value, 1);
946 select->ReplaceInput(condition, 2);
947 RecordSimplification();
948 }
949
950 if (true_value == false_value) {
951 // Replace (cond ? x : x) with (x).
952 replace_with = true_value;
953 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000954 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000955 // Replace (true ? x : y) with (x).
956 replace_with = true_value;
957 } else {
958 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000959 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000960 replace_with = false_value;
961 }
962 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000963 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000964 // Replace (cond ? true : false) with (cond).
965 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000966 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000967 // Replace (cond ? false : true) with (!cond).
968 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
969 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700970 } else if (condition->IsCondition()) {
971 IfCondition cmp = condition->AsCondition()->GetCondition();
972 HInstruction* a = condition->InputAt(0);
973 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100974 DataType::Type t_type = true_value->GetType();
975 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700976 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700977 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
978 // type will be int or long, like the condition). Replacements are general,
979 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700980 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700981 // Allow a < 100 ? max(a, -100) : ..
982 // or a > -100 ? min(a, 100) : ..
983 // to use min/max instead of a to detect nested min/max expressions.
984 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
985 if (new_a != nullptr) {
986 a = new_a;
987 }
Aart Bik142b9132018-03-14 15:12:59 -0700988 // Try to replace typical integral MIN/MAX/ABS constructs.
989 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
990 ((a == true_value && b == false_value) ||
991 (b == true_value && a == false_value))) {
992 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
993 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
994 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
995 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700996 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
997 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
998 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
999 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1000 HInstruction* not_negated = negLeft ? false_value : true_value;
1001 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1002 // Found a < 0 ? -a : a
1003 // or a > 0 ? a : -a
1004 // which can be replaced by ABS(a).
1005 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001006 }
1007 } else if (true_value->IsSub() && false_value->IsSub()) {
1008 HInstruction* true_sub1 = true_value->InputAt(0);
1009 HInstruction* true_sub2 = true_value->InputAt(1);
1010 HInstruction* false_sub1 = false_value->InputAt(0);
1011 HInstruction* false_sub2 = false_value->InputAt(1);
1012 if ((((cmp == kCondGT || cmp == kCondGE) &&
1013 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1014 ((cmp == kCondLT || cmp == kCondLE) &&
1015 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1016 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001017 // Found a > b ? a - b : b - a
1018 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001019 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001020 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001021 }
1022 }
1023 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001024 }
1025
1026 if (replace_with != nullptr) {
1027 select->ReplaceWith(replace_with);
1028 select->GetBlock()->RemoveInstruction(select);
1029 RecordSimplification();
1030 }
1031}
1032
1033void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1034 HInstruction* condition = instruction->InputAt(0);
1035 if (condition->IsBooleanNot()) {
1036 // Swap successors if input is negated.
1037 instruction->ReplaceInput(condition->InputAt(0), 0);
1038 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001039 RecordSimplification();
1040 }
1041}
1042
Mingyao Yang0304e182015-01-30 16:41:29 -08001043void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1044 HInstruction* input = instruction->InputAt(0);
1045 // If the array is a NewArray with constant size, replace the array length
1046 // with the constant instruction. This helps the bounds check elimination phase.
1047 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001048 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001049 if (input->IsIntConstant()) {
1050 instruction->ReplaceWith(input);
1051 }
1052 }
1053}
1054
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001055void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001056 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001057 if (value->GetType() != DataType::Type::kReference) {
1058 return;
1059 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001060
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001061 if (CanEnsureNotNullAt(value, instruction)) {
1062 instruction->ClearValueCanBeNull();
1063 }
1064
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001065 if (value->IsArrayGet()) {
1066 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1067 // If the code is just swapping elements in the array, no need for a type check.
1068 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001069 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001070 }
1071 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001072
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001073 if (value->IsNullConstant()) {
1074 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001075 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001076 }
1077
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001078 ScopedObjectAccess soa(Thread::Current());
1079 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1080 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1081 if (!array_rti.IsValid()) {
1082 return;
1083 }
1084
1085 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1086 instruction->ClearNeedsTypeCheck();
1087 return;
1088 }
1089
1090 if (array_rti.IsObjectArray()) {
1091 if (array_rti.IsExact()) {
1092 instruction->ClearNeedsTypeCheck();
1093 return;
1094 }
1095 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001096 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001097}
1098
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001099static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001100 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1101 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1102 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001103 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001104 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001105 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1106 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001107 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001108 return DataType::Size(result_type) > DataType::Size(input_type) &&
1109 result_type != DataType::Type::kUint16 &&
1110 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001111}
1112
Vladimir Marko61b92282017-10-11 13:23:17 +01001113static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1114 if (maybe_get->IsInstanceFieldGet()) {
1115 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1116 return true;
1117 } else if (maybe_get->IsStaticFieldGet()) {
1118 maybe_get->AsStaticFieldGet()->SetType(new_type);
1119 return true;
1120 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1121 maybe_get->AsArrayGet()->SetType(new_type);
1122 return true;
1123 } else {
1124 return false;
1125 }
1126}
1127
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001128// The type conversion is only used for storing into a field/element of the
1129// same/narrower size.
1130static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1131 if (type_conversion->HasEnvironmentUses()) {
1132 return false;
1133 }
1134 DataType::Type input_type = type_conversion->GetInputType();
1135 DataType::Type result_type = type_conversion->GetResultType();
1136 if (!DataType::IsIntegralType(input_type) ||
1137 !DataType::IsIntegralType(result_type) ||
1138 input_type == DataType::Type::kInt64 ||
1139 result_type == DataType::Type::kInt64) {
1140 // Type conversion is needed if non-integer types are involved, or 64-bit
1141 // types are involved, which may use different number of registers.
1142 return false;
1143 }
1144 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1145 // Type conversion is not necessary when storing to a field/element of the
1146 // same/smaller size.
1147 } else {
1148 // We do not handle this case here.
1149 return false;
1150 }
1151
1152 // Check if the converted value is only used for storing into heap.
1153 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1154 HInstruction* instruction = use.GetUser();
1155 if (instruction->IsInstanceFieldSet() &&
1156 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1157 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1158 continue;
1159 }
1160 if (instruction->IsStaticFieldSet() &&
1161 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1162 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1163 continue;
1164 }
1165 if (instruction->IsArraySet() &&
1166 instruction->AsArraySet()->GetComponentType() == result_type &&
1167 // not index use.
1168 instruction->AsArraySet()->GetIndex() != type_conversion) {
1169 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1170 continue;
1171 }
1172 // The use is not as a store value, or the field/element type is not the
1173 // same as the result_type, keep the type conversion.
1174 return false;
1175 }
1176 // Codegen automatically handles the type conversion during the store.
1177 return true;
1178}
1179
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001180void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001181 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001182 DataType::Type input_type = input->GetType();
1183 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001184 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001185 // Remove the implicit conversion; this includes conversion to the same type.
1186 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001187 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001188 RecordSimplification();
1189 return;
1190 }
1191
1192 if (input->IsTypeConversion()) {
1193 HTypeConversion* input_conversion = input->AsTypeConversion();
1194 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001195 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001196
1197 // When the first conversion is lossless, a direct conversion from the original type
1198 // to the final type yields the same result, even for a lossy second conversion, for
1199 // example float->double->int or int->double->float.
1200 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1201
1202 // For integral conversions, see if the first conversion loses only bits that the second
1203 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1204 // conversion yields the same result, for example long->int->short or int->char->short.
1205 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001206 DataType::IsIntegralType(input_type) &&
1207 DataType::IsIntegralType(original_type) &&
1208 DataType::IsIntegralType(result_type) &&
1209 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001210
1211 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1212 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001213 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001214 instruction->ReplaceWith(original_input);
1215 instruction->GetBlock()->RemoveInstruction(instruction);
1216 if (!input_conversion->HasUses()) {
1217 // Don't wait for DCE.
1218 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1219 }
1220 RecordSimplification();
1221 return;
1222 }
1223 // Otherwise simplify only if the first conversion has no other use.
1224 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1225 input_conversion->ReplaceWith(original_input);
1226 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1227 RecordSimplification();
1228 return;
1229 }
1230 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001231 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1232 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001233 HAnd* input_and = input->AsAnd();
1234 HConstant* constant = input_and->GetConstantRight();
1235 if (constant != nullptr) {
1236 int64_t value = Int64FromConstant(constant);
1237 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1238 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001239 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001240 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001241 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001242 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001243 instruction->ReplaceWith(original_input);
1244 instruction->GetBlock()->RemoveInstruction(instruction);
1245 RecordSimplification();
1246 return;
1247 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1248 input_and->ReplaceWith(original_input);
1249 input_and->GetBlock()->RemoveInstruction(input_and);
1250 RecordSimplification();
1251 return;
1252 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001253 }
1254 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001255 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1256 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1257 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1258 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1259 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1260 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1261 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1262 instruction->ReplaceWith(input);
1263 instruction->GetBlock()->RemoveInstruction(instruction);
1264 RecordSimplification();
1265 return;
1266 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001267 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001268
1269 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1270 instruction->ReplaceWith(input);
1271 instruction->GetBlock()->RemoveInstruction(instruction);
1272 RecordSimplification();
1273 return;
1274 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001275}
1276
Aart Bikc6eec4b2018-03-29 17:22:00 -07001277void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1278 HInstruction* input = instruction->GetInput();
1279 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1280 // Zero extension from narrow to wide can never set sign bit in the wider
1281 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1282 instruction->ReplaceWith(input);
1283 instruction->GetBlock()->RemoveInstruction(instruction);
1284 RecordSimplification();
1285 }
1286}
1287
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001288void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1289 HConstant* input_cst = instruction->GetConstantRight();
1290 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001291 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001292 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001293 // Replace code looking like
1294 // ADD dst, src, 0
1295 // with
1296 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001297 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1298 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1299 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001300 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001301 instruction->ReplaceWith(input_other);
1302 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001303 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001304 return;
1305 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001306 }
1307
1308 HInstruction* left = instruction->GetLeft();
1309 HInstruction* right = instruction->GetRight();
1310 bool left_is_neg = left->IsNeg();
1311 bool right_is_neg = right->IsNeg();
1312
1313 if (left_is_neg && right_is_neg) {
1314 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1315 return;
1316 }
1317 }
1318
1319 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1320 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1321 // Replace code looking like
1322 // NEG tmp, b
1323 // ADD dst, a, tmp
1324 // with
1325 // SUB dst, a, b
1326 // We do not perform the optimization if the input negation has environment
1327 // uses or multiple non-environment uses as it could lead to worse code. In
1328 // particular, we do not want the live range of `b` to be extended if we are
1329 // not sure the initial 'NEG' instruction can be removed.
1330 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001331 HSub* sub =
1332 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001333 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1334 RecordSimplification();
1335 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001336 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001337 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001338
Anton Kirilove14dc862016-05-13 17:56:15 +01001339 if (TryReplaceWithRotate(instruction)) {
1340 return;
1341 }
1342
1343 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1344 // so no need to return.
1345 TryHandleAssociativeAndCommutativeOperation(instruction);
1346
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001347 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001348 TrySubtractionChainSimplification(instruction)) {
1349 return;
1350 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001351
1352 if (integral_type) {
1353 // Replace code patterns looking like
1354 // SUB dst1, x, y SUB dst1, x, y
1355 // ADD dst2, dst1, y ADD dst2, y, dst1
1356 // with
1357 // SUB dst1, x, y
1358 // ADD instruction is not needed in this case, we may use
1359 // one of inputs of SUB instead.
1360 if (left->IsSub() && left->InputAt(1) == right) {
1361 instruction->ReplaceWith(left->InputAt(0));
1362 RecordSimplification();
1363 instruction->GetBlock()->RemoveInstruction(instruction);
1364 return;
1365 } else if (right->IsSub() && right->InputAt(1) == left) {
1366 instruction->ReplaceWith(right->InputAt(0));
1367 RecordSimplification();
1368 instruction->GetBlock()->RemoveInstruction(instruction);
1369 return;
1370 }
1371 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001372}
1373
1374void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001375 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001376 HConstant* input_cst = instruction->GetConstantRight();
1377 HInstruction* input_other = instruction->GetLeastConstantLeft();
1378
Vladimir Marko452c1b62015-09-25 14:44:17 +01001379 if (input_cst != nullptr) {
1380 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001381 if (value == -1 ||
1382 // Similar cases under zero extension.
1383 (DataType::IsUnsignedType(input_other->GetType()) &&
1384 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001385 // Replace code looking like
1386 // AND dst, src, 0xFFF...FF
1387 // with
1388 // src
1389 instruction->ReplaceWith(input_other);
1390 instruction->GetBlock()->RemoveInstruction(instruction);
1391 RecordSimplification();
1392 return;
1393 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001394 if (input_other->IsTypeConversion() &&
1395 input_other->GetType() == DataType::Type::kInt64 &&
1396 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1397 IsInt<32>(value) &&
1398 input_other->HasOnlyOneNonEnvironmentUse()) {
1399 // The AND can be reordered before the TypeConversion. Replace
1400 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1401 // TypeConversion<Int64> tmp, src
1402 // AND dst, tmp, cst
1403 // with
1404 // IntConstant cst, <32-bit-constant>
1405 // AND tmp, src, cst
1406 // TypeConversion<Int64> dst, tmp
1407 // This helps 32-bit targets and does not hurt 64-bit targets.
1408 // This also simplifies detection of other patterns, such as Uint8 loads.
1409 HInstruction* new_and_input = input_other->InputAt(0);
1410 // Implicit conversion Int64->Int64 would have been removed previously.
1411 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1412 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1413 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001414 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001415 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1416 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001417 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001418 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1419 input_other->GetBlock()->RemoveInstruction(input_other);
1420 RecordSimplification();
1421 // Try to process the new And now, do not wait for the next round of simplifications.
1422 instruction = new_and;
1423 input_other = new_and_input;
1424 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001425 // Eliminate And from UShr+And if the And-mask contains all the bits that
1426 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1427 // precisely clears the shifted-in sign bits.
1428 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001430 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1431 size_t num_tail_bits_set = CTZ(value + 1);
1432 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1433 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1434 instruction->ReplaceWith(input_other);
1435 instruction->GetBlock()->RemoveInstruction(instruction);
1436 RecordSimplification();
1437 return;
1438 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1439 input_other->HasOnlyOneNonEnvironmentUse()) {
1440 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1441 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001442 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001443 input_other->InputAt(0),
1444 input_other->InputAt(1),
1445 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001446 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1447 input_other->GetBlock()->RemoveInstruction(input_other);
1448 RecordSimplification();
1449 return;
1450 }
1451 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001452 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1453 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1454 // or array Get with only a single use, short-circuit the subsequent simplification
1455 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1456 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1457 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1458 if (input_other->GetType() == find_type &&
1459 input_other->HasOnlyOneNonEnvironmentUse() &&
1460 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1461 instruction->ReplaceWith(input_other);
1462 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001463 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1464 instruction->ReplaceWith(input_other);
1465 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001466 } else {
1467 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1468 new_type, input_other, instruction->GetDexPc());
1469 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1470 }
1471 RecordSimplification();
1472 return;
1473 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001474 }
1475
1476 // We assume that GVN has run before, so we only perform a pointer comparison.
1477 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001478 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001479 if (instruction->GetLeft() == instruction->GetRight()) {
1480 // Replace code looking like
1481 // AND dst, src, src
1482 // with
1483 // src
1484 instruction->ReplaceWith(instruction->GetLeft());
1485 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001486 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001487 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001488 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001489
Anton Kirilove14dc862016-05-13 17:56:15 +01001490 if (TryDeMorganNegationFactoring(instruction)) {
1491 return;
1492 }
1493
1494 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1495 // so no need to return.
1496 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001497}
1498
Mark Mendellc4701932015-04-10 13:18:51 -04001499void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1500 VisitCondition(condition);
1501}
1502
1503void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1504 VisitCondition(condition);
1505}
1506
1507void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1508 VisitCondition(condition);
1509}
1510
1511void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1512 VisitCondition(condition);
1513}
1514
Anton Shaminbdd79352016-02-15 12:48:36 +06001515void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1516 VisitCondition(condition);
1517}
1518
1519void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1520 VisitCondition(condition);
1521}
1522
1523void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1524 VisitCondition(condition);
1525}
1526
1527void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1528 VisitCondition(condition);
1529}
Aart Bike9f37602015-10-09 11:15:55 -07001530
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001531// Recognize the following pattern:
1532// obj.getClass() ==/!= Foo.class
1533// And replace it with a constant value if the type of `obj` is statically known.
1534static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1535 HInstruction* input_one = condition->InputAt(0);
1536 HInstruction* input_two = condition->InputAt(1);
1537 HLoadClass* load_class = input_one->IsLoadClass()
1538 ? input_one->AsLoadClass()
1539 : input_two->AsLoadClass();
1540 if (load_class == nullptr) {
1541 return false;
1542 }
1543
1544 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1545 if (!class_rti.IsValid()) {
1546 // Unresolved class.
1547 return false;
1548 }
1549
1550 HInstanceFieldGet* field_get = (load_class == input_one)
1551 ? input_two->AsInstanceFieldGet()
1552 : input_one->AsInstanceFieldGet();
1553 if (field_get == nullptr) {
1554 return false;
1555 }
1556
1557 HInstruction* receiver = field_get->InputAt(0);
1558 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1559 if (!receiver_type.IsExact()) {
1560 return false;
1561 }
1562
1563 {
1564 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001565 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001566 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1567 if (field_get->GetFieldInfo().GetField() != field) {
1568 return false;
1569 }
1570
1571 // We can replace the compare.
1572 int value = 0;
1573 if (receiver_type.IsEqual(class_rti)) {
1574 value = condition->IsEqual() ? 1 : 0;
1575 } else {
1576 value = condition->IsNotEqual() ? 1 : 0;
1577 }
1578 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1579 return true;
1580 }
1581}
1582
Mark Mendellc4701932015-04-10 13:18:51 -04001583void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001584 if (condition->IsEqual() || condition->IsNotEqual()) {
1585 if (RecognizeAndSimplifyClassCheck(condition)) {
1586 return;
1587 }
1588 }
1589
Anton Shaminbdd79352016-02-15 12:48:36 +06001590 // Reverse condition if left is constant. Our code generators prefer constant
1591 // on the right hand side.
1592 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1593 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001594 HCondition* replacement =
1595 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001596 // If it is a fp we must set the opposite bias.
1597 if (replacement != nullptr) {
1598 if (condition->IsLtBias()) {
1599 replacement->SetBias(ComparisonBias::kGtBias);
1600 } else if (condition->IsGtBias()) {
1601 replacement->SetBias(ComparisonBias::kLtBias);
1602 }
1603 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1604 RecordSimplification();
1605
1606 condition = replacement;
1607 }
1608 }
Mark Mendellc4701932015-04-10 13:18:51 -04001609
Mark Mendellc4701932015-04-10 13:18:51 -04001610 HInstruction* left = condition->GetLeft();
1611 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001612
1613 // Try to fold an HCompare into this HCondition.
1614
Mark Mendellc4701932015-04-10 13:18:51 -04001615 // We can only replace an HCondition which compares a Compare to 0.
1616 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1617 // condition with a long, float or double comparison as input.
1618 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1619 // Conversion is not possible.
1620 return;
1621 }
1622
1623 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001624 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001625 // Someone else also wants the result of the compare.
1626 return;
1627 }
1628
Vladimir Marko46817b82016-03-29 12:21:58 +01001629 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001630 // There is a reference to the compare result in an environment. Do we really need it?
1631 if (GetGraph()->IsDebuggable()) {
1632 return;
1633 }
1634
1635 // We have to ensure that there are no deopt points in the sequence.
1636 if (left->HasAnyEnvironmentUseBefore(condition)) {
1637 return;
1638 }
1639 }
1640
1641 // Clean up any environment uses from the HCompare, if any.
1642 left->RemoveEnvironmentUsers();
1643
1644 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1645 condition->SetBias(left->AsCompare()->GetBias());
1646
1647 // Replace the operands of the HCondition.
1648 condition->ReplaceInput(left->InputAt(0), 0);
1649 condition->ReplaceInput(left->InputAt(1), 1);
1650
1651 // Remove the HCompare.
1652 left->GetBlock()->RemoveInstruction(left);
1653
1654 RecordSimplification();
1655}
1656
Andreas Gampe9186ced2016-12-12 14:28:21 -08001657// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1658static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1659 // True, if the most significant bits of divisor are 0.
1660 return ((divisor & 0x7fffff) == 0);
1661}
1662
1663// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1664static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1665 // True, if the most significant bits of divisor are 0.
1666 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1667}
1668
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001669void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1670 HConstant* input_cst = instruction->GetConstantRight();
1671 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001673
1674 if ((input_cst != nullptr) && input_cst->IsOne()) {
1675 // Replace code looking like
1676 // DIV dst, src, 1
1677 // with
1678 // src
1679 instruction->ReplaceWith(input_other);
1680 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001681 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001682 return;
1683 }
1684
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001685 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001686 // Replace code looking like
1687 // DIV dst, src, -1
1688 // with
1689 // NEG dst, src
1690 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001691 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001692 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001693 return;
1694 }
1695
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001696 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001697 // Try replacing code looking like
1698 // DIV dst, src, constant
1699 // with
1700 // MUL dst, src, 1 / constant
1701 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001702 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001703 double value = input_cst->AsDoubleConstant()->GetValue();
1704 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1705 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1706 }
1707 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001708 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001709 float value = input_cst->AsFloatConstant()->GetValue();
1710 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1711 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1712 }
1713 }
1714
1715 if (reciprocal != nullptr) {
1716 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001717 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001718 RecordSimplification();
1719 return;
1720 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001721 }
1722}
1723
1724void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1725 HConstant* input_cst = instruction->GetConstantRight();
1726 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001727 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001728 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001729 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001730
1731 if (input_cst == nullptr) {
1732 return;
1733 }
1734
1735 if (input_cst->IsOne()) {
1736 // Replace code looking like
1737 // MUL dst, src, 1
1738 // with
1739 // src
1740 instruction->ReplaceWith(input_other);
1741 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001742 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001743 return;
1744 }
1745
1746 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001747 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001748 // Replace code looking like
1749 // MUL dst, src, -1
1750 // with
1751 // NEG dst, src
1752 HNeg* neg = new (allocator) HNeg(type, input_other);
1753 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001754 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001755 return;
1756 }
1757
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001758 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001759 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1760 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1761 // Replace code looking like
1762 // FP_MUL dst, src, 2.0
1763 // with
1764 // FP_ADD dst, src, src
1765 // The 'int' and 'long' cases are handled below.
1766 block->ReplaceAndRemoveInstructionWith(instruction,
1767 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001768 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001769 return;
1770 }
1771
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001772 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001773 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001774 // Even though constant propagation also takes care of the zero case, other
1775 // optimizations can lead to having a zero multiplication.
1776 if (factor == 0) {
1777 // Replace code looking like
1778 // MUL dst, src, 0
1779 // with
1780 // 0
1781 instruction->ReplaceWith(input_cst);
1782 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001783 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001784 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001785 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001786 // Replace code looking like
1787 // MUL dst, src, pow_of_2
1788 // with
1789 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001790 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001791 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001792 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001793 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001794 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001795 } else if (IsPowerOfTwo(factor - 1)) {
1796 // Transform code looking like
1797 // MUL dst, src, (2^n + 1)
1798 // into
1799 // SHL tmp, src, n
1800 // ADD dst, src, tmp
1801 HShl* shl = new (allocator) HShl(type,
1802 input_other,
1803 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1804 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1805
1806 block->InsertInstructionBefore(shl, instruction);
1807 block->ReplaceAndRemoveInstructionWith(instruction, add);
1808 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001809 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001810 } else if (IsPowerOfTwo(factor + 1)) {
1811 // Transform code looking like
1812 // MUL dst, src, (2^n - 1)
1813 // into
1814 // SHL tmp, src, n
1815 // SUB dst, tmp, src
1816 HShl* shl = new (allocator) HShl(type,
1817 input_other,
1818 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1819 HSub* sub = new (allocator) HSub(type, shl, input_other);
1820
1821 block->InsertInstructionBefore(shl, instruction);
1822 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1823 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001824 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001825 }
1826 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001827
1828 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1829 // so no need to return.
1830 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001831}
1832
Alexandre Rames188d4312015-04-09 18:30:21 +01001833void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1834 HInstruction* input = instruction->GetInput();
1835 if (input->IsNeg()) {
1836 // Replace code looking like
1837 // NEG tmp, src
1838 // NEG dst, tmp
1839 // with
1840 // src
1841 HNeg* previous_neg = input->AsNeg();
1842 instruction->ReplaceWith(previous_neg->GetInput());
1843 instruction->GetBlock()->RemoveInstruction(instruction);
1844 // We perform the optimization even if the input negation has environment
1845 // uses since it allows removing the current instruction. But we only delete
1846 // the input negation only if it is does not have any uses left.
1847 if (!previous_neg->HasUses()) {
1848 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1849 }
1850 RecordSimplification();
1851 return;
1852 }
1853
Serguei Katkov339dfc22015-04-20 12:29:32 +06001854 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001855 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001856 // Replace code looking like
1857 // SUB tmp, a, b
1858 // NEG dst, tmp
1859 // with
1860 // SUB dst, b, a
1861 // We do not perform the optimization if the input subtraction has
1862 // environment uses or multiple non-environment uses as it could lead to
1863 // worse code. In particular, we do not want the live ranges of `a` and `b`
1864 // to be extended if we are not sure the initial 'SUB' instruction can be
1865 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001866 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001867 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001868 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1869 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001870 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1871 if (!sub->HasUses()) {
1872 sub->GetBlock()->RemoveInstruction(sub);
1873 }
1874 RecordSimplification();
1875 }
1876}
1877
1878void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1879 HInstruction* input = instruction->GetInput();
1880 if (input->IsNot()) {
1881 // Replace code looking like
1882 // NOT tmp, src
1883 // NOT dst, tmp
1884 // with
1885 // src
1886 // We perform the optimization even if the input negation has environment
1887 // uses since it allows removing the current instruction. But we only delete
1888 // the input negation only if it is does not have any uses left.
1889 HNot* previous_not = input->AsNot();
1890 instruction->ReplaceWith(previous_not->GetInput());
1891 instruction->GetBlock()->RemoveInstruction(instruction);
1892 if (!previous_not->HasUses()) {
1893 previous_not->GetBlock()->RemoveInstruction(previous_not);
1894 }
1895 RecordSimplification();
1896 }
1897}
1898
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001899void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1900 HConstant* input_cst = instruction->GetConstantRight();
1901 HInstruction* input_other = instruction->GetLeastConstantLeft();
1902
Roland Levillain1a653882016-03-18 18:05:57 +00001903 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001904 // Replace code looking like
1905 // OR dst, src, 0
1906 // with
1907 // src
1908 instruction->ReplaceWith(input_other);
1909 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001910 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001911 return;
1912 }
1913
1914 // We assume that GVN has run before, so we only perform a pointer comparison.
1915 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001916 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001917 if (instruction->GetLeft() == instruction->GetRight()) {
1918 // Replace code looking like
1919 // OR dst, src, src
1920 // with
1921 // src
1922 instruction->ReplaceWith(instruction->GetLeft());
1923 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001924 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001925 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001926 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001927
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001928 if (TryDeMorganNegationFactoring(instruction)) return;
1929
Anton Kirilove14dc862016-05-13 17:56:15 +01001930 if (TryReplaceWithRotate(instruction)) {
1931 return;
1932 }
1933
1934 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1935 // so no need to return.
1936 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001937}
1938
1939void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1940 VisitShift(instruction);
1941}
1942
1943void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1944 VisitShift(instruction);
1945}
1946
1947void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1948 HConstant* input_cst = instruction->GetConstantRight();
1949 HInstruction* input_other = instruction->GetLeastConstantLeft();
1950
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001951 DataType::Type type = instruction->GetType();
1952 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001953 return;
1954 }
1955
Roland Levillain1a653882016-03-18 18:05:57 +00001956 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001957 // Replace code looking like
1958 // SUB dst, src, 0
1959 // with
1960 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001961 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1962 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1963 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001964 instruction->ReplaceWith(input_other);
1965 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001966 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001967 return;
1968 }
1969
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001970 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001971 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001972
Alexandre Rames188d4312015-04-09 18:30:21 +01001973 HInstruction* left = instruction->GetLeft();
1974 HInstruction* right = instruction->GetRight();
1975 if (left->IsConstant()) {
1976 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001977 // Replace code looking like
1978 // SUB dst, 0, src
1979 // with
1980 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001981 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001982 // `x` is `0.0`, the former expression yields `0.0`, while the later
1983 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001984 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001985 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001986 RecordSimplification();
1987 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001988 }
1989 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001990
1991 if (left->IsNeg() && right->IsNeg()) {
1992 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1993 return;
1994 }
1995 }
1996
1997 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1998 // Replace code looking like
1999 // NEG tmp, b
2000 // SUB dst, a, tmp
2001 // with
2002 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002003 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002004 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2005 RecordSimplification();
2006 right->GetBlock()->RemoveInstruction(right);
2007 return;
2008 }
2009
2010 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2011 // Replace code looking like
2012 // NEG tmp, a
2013 // SUB dst, tmp, b
2014 // with
2015 // ADD tmp, a, b
2016 // NEG dst, tmp
2017 // The second version is not intrinsically better, but enables more
2018 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002019 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002020 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002021 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002022 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2023 instruction->ReplaceWith(neg);
2024 instruction->GetBlock()->RemoveInstruction(instruction);
2025 RecordSimplification();
2026 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002027 return;
2028 }
2029
2030 if (TrySubtractionChainSimplification(instruction)) {
2031 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002032 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002033
2034 if (left->IsAdd()) {
2035 // Replace code patterns looking like
2036 // ADD dst1, x, y ADD dst1, x, y
2037 // SUB dst2, dst1, y SUB dst2, dst1, x
2038 // with
2039 // ADD dst1, x, y
2040 // SUB instruction is not needed in this case, we may use
2041 // one of inputs of ADD instead.
2042 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002043 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002044 if (left->InputAt(1) == right) {
2045 instruction->ReplaceWith(left->InputAt(0));
2046 RecordSimplification();
2047 instruction->GetBlock()->RemoveInstruction(instruction);
2048 return;
2049 } else if (left->InputAt(0) == right) {
2050 instruction->ReplaceWith(left->InputAt(1));
2051 RecordSimplification();
2052 instruction->GetBlock()->RemoveInstruction(instruction);
2053 return;
2054 }
2055 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002056}
2057
2058void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2059 VisitShift(instruction);
2060}
2061
2062void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2063 HConstant* input_cst = instruction->GetConstantRight();
2064 HInstruction* input_other = instruction->GetLeastConstantLeft();
2065
Roland Levillain1a653882016-03-18 18:05:57 +00002066 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002067 // Replace code looking like
2068 // XOR dst, src, 0
2069 // with
2070 // src
2071 instruction->ReplaceWith(input_other);
2072 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002073 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002074 return;
2075 }
2076
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002077 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002078 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002079 // Replace code looking like
2080 // XOR dst, src, 1
2081 // with
2082 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002083 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002084 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2085 RecordSimplification();
2086 return;
2087 }
2088
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002089 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2090 // Replace code looking like
2091 // XOR dst, src, 0xFFF...FF
2092 // with
2093 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002094 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002095 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002096 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002097 return;
2098 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002099
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002100 HInstruction* left = instruction->GetLeft();
2101 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002102 if (((left->IsNot() && right->IsNot()) ||
2103 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002104 left->HasOnlyOneNonEnvironmentUse() &&
2105 right->HasOnlyOneNonEnvironmentUse()) {
2106 // Replace code looking like
2107 // NOT nota, a
2108 // NOT notb, b
2109 // XOR dst, nota, notb
2110 // with
2111 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002112 instruction->ReplaceInput(left->InputAt(0), 0);
2113 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002114 left->GetBlock()->RemoveInstruction(left);
2115 right->GetBlock()->RemoveInstruction(right);
2116 RecordSimplification();
2117 return;
2118 }
2119
Anton Kirilove14dc862016-05-13 17:56:15 +01002120 if (TryReplaceWithRotate(instruction)) {
2121 return;
2122 }
2123
2124 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2125 // so no need to return.
2126 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002127}
2128
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002129void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2130 HInstruction* argument = instruction->InputAt(1);
2131 HInstruction* receiver = instruction->InputAt(0);
2132 if (receiver == argument) {
2133 // Because String.equals is an instance call, the receiver is
2134 // a null check if we don't know it's null. The argument however, will
2135 // be the actual object. So we cannot end up in a situation where both
2136 // are equal but could be null.
2137 DCHECK(CanEnsureNotNullAt(argument, instruction));
2138 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2139 instruction->GetBlock()->RemoveInstruction(instruction);
2140 } else {
2141 StringEqualsOptimizations optimizations(instruction);
2142 if (CanEnsureNotNullAt(argument, instruction)) {
2143 optimizations.SetArgumentNotNull();
2144 }
2145 ScopedObjectAccess soa(Thread::Current());
2146 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2147 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2148 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002149 } else if (kUseReadBarrier) {
2150 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002151 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2152 // Object.equals() can be devirtualized to String.equals().
2153 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002154 Runtime* runtime = Runtime::Current();
2155 // For AOT, we always assume that the boot image shall contain the String.class and
2156 // we do not need a read barrier for boot image classes as they are non-moveable.
2157 // For JIT, check if we actually have a boot image; if we do, the String.class
2158 // should also be non-moveable.
2159 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2160 DCHECK(runtime->IsAotCompiler() ||
2161 !runtime->GetHeap()->IsMovableObject(
2162 instruction->GetResolvedMethod()->GetDeclaringClass()));
2163 optimizations.SetNoReadBarrierForStringClass();
2164 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002165 }
2166 }
2167}
2168
Roland Levillain22c49222016-03-18 14:04:28 +00002169void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2170 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002171 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002172 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002173 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002174 HInstruction* value = invoke->InputAt(0);
2175 HInstruction* distance = invoke->InputAt(1);
2176 // Replace the invoke with an HRor.
2177 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002178 // Unconditionally set the type of the negated distance to `int`,
2179 // as shift and rotate operations expect a 32-bit (or narrower)
2180 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002181 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002182 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2183 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002184 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002185 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2186 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002187 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002188 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2189 clinit->GetBlock()->RemoveInstruction(clinit);
2190 HInstruction* ldclass = clinit->InputAt(0);
2191 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2192 ldclass->GetBlock()->RemoveInstruction(ldclass);
2193 }
2194 }
2195}
2196
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002197static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2198 if (potential_length->IsArrayLength()) {
2199 return potential_length->InputAt(0) == potential_array;
2200 }
2201
2202 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002203 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002204 }
2205
2206 return false;
2207}
2208
2209void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2210 HInstruction* source = instruction->InputAt(0);
2211 HInstruction* destination = instruction->InputAt(2);
2212 HInstruction* count = instruction->InputAt(4);
2213 SystemArrayCopyOptimizations optimizations(instruction);
2214 if (CanEnsureNotNullAt(source, instruction)) {
2215 optimizations.SetSourceIsNotNull();
2216 }
2217 if (CanEnsureNotNullAt(destination, instruction)) {
2218 optimizations.SetDestinationIsNotNull();
2219 }
2220 if (destination == source) {
2221 optimizations.SetDestinationIsSource();
2222 }
2223
2224 if (IsArrayLengthOf(count, source)) {
2225 optimizations.SetCountIsSourceLength();
2226 }
2227
2228 if (IsArrayLengthOf(count, destination)) {
2229 optimizations.SetCountIsDestinationLength();
2230 }
2231
2232 {
2233 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002234 DataType::Type source_component_type = DataType::Type::kVoid;
2235 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002236 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2237 if (destination_rti.IsValid()) {
2238 if (destination_rti.IsObjectArray()) {
2239 if (destination_rti.IsExact()) {
2240 optimizations.SetDoesNotNeedTypeCheck();
2241 }
2242 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002243 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002244 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002245 destination_component_type = DataTypeFromPrimitive(
2246 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002247 optimizations.SetDestinationIsPrimitiveArray();
2248 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2249 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002250 }
2251 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002252 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2253 if (source_rti.IsValid()) {
2254 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2255 optimizations.SetDoesNotNeedTypeCheck();
2256 }
2257 if (source_rti.IsPrimitiveArrayClass()) {
2258 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002259 source_component_type = DataTypeFromPrimitive(
2260 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002261 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2262 optimizations.SetSourceIsNonPrimitiveArray();
2263 }
2264 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002265 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002266 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002267 (source_component_type == destination_component_type)) {
2268 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2269 PointerSize image_size = class_linker->GetImagePointerSize();
2270 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
Vladimir Markod93e3742018-07-18 10:58:13 +01002271 ObjPtr<mirror::Class> system = invoke->GetResolvedMethod()->GetDeclaringClass();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002272 ArtMethod* method = nullptr;
2273 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002274 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002275 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002276 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002277 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002278 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002279 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002280 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002281 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002282 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002283 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002284 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002285 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002286 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002287 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002288 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002289 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002290 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002291 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002292 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002293 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002294 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002295 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002296 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002297 break;
2298 default:
2299 LOG(FATAL) << "Unreachable";
2300 }
2301 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002302 DCHECK(method->IsStatic());
2303 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002304 invoke->SetResolvedMethod(method);
2305 // Sharpen the new invoke. Note that we do not update the dex method index of
2306 // the invoke, as we would need to look it up in the current dex file, and it
2307 // is unlikely that it exists. The most usual situation for such typed
2308 // arraycopy methods is a direct pointer to the boot image.
Vladimir Markobb089b62018-06-28 17:30:16 +01002309 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002310 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002311 }
2312}
2313
Roland Levillaina5c4a402016-03-15 15:02:50 +00002314void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2315 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002316 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002317 DCHECK(invoke->IsInvokeStaticOrDirect());
2318 uint32_t dex_pc = invoke->GetDexPc();
2319 HInstruction* left = invoke->InputAt(0);
2320 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002321 if (!is_signum) {
2322 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002323 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002324 right = GetGraph()->GetLongConstant(0);
2325 } else {
2326 right = GetGraph()->GetIntConstant(0);
2327 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002328 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002329 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2330 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2331}
2332
Aart Bik75a38b22016-02-17 10:41:50 -08002333void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2334 DCHECK(invoke->IsInvokeStaticOrDirect());
2335 uint32_t dex_pc = invoke->GetDexPc();
2336 // IsNaN(x) is the same as x != x.
2337 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002338 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002339 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002340 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2341}
2342
Aart Bik2a6aad92016-02-25 11:32:32 -08002343void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2344 DCHECK(invoke->IsInvokeStaticOrDirect());
2345 uint32_t dex_pc = invoke->GetDexPc();
2346 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002347 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002348 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2349 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002350 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002351 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2352 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2353 kNeedsEnvironmentOrCache,
2354 kNoSideEffects,
2355 kNoThrow);
2356 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002357 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002358 nan = GetGraph()->GetIntConstant(0x7fc00000);
2359 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2360 kNeedsEnvironmentOrCache,
2361 kNoSideEffects,
2362 kNoThrow);
2363 }
2364 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002365 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002366 condition->SetBias(ComparisonBias::kLtBias);
2367 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2368 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002369 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002370 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2371 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2372}
2373
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002374void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2375 HInstruction* str = invoke->InputAt(0);
2376 HInstruction* index = invoke->InputAt(1);
2377 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002378 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002379 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2380 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002381 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002382 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002383 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002384 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002385 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002386 HArrayGet* array_get = new (allocator) HArrayGet(str,
2387 bounds_check,
2388 DataType::Type::kUint16,
2389 SideEffects::None(), // Strings are immutable.
2390 dex_pc,
2391 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002392 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2393 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2394 GetGraph()->SetHasBoundsChecks(true);
2395}
2396
Vladimir Markodce016e2016-04-28 13:10:02 +01002397void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2398 HInstruction* str = invoke->InputAt(0);
2399 uint32_t dex_pc = invoke->GetDexPc();
2400 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2401 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002402 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002403 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002404 HInstruction* replacement;
2405 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2406 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2407 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2408 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002409 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002410 replacement = equal;
2411 } else {
2412 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2413 replacement = length;
2414 }
2415 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2416}
2417
Vladimir Marko6fa44042018-03-19 18:42:49 +00002418void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2419 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2420 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2421 if (invoke->InputAt(0)->IsLoadString()) {
2422 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
2423 const DexFile& dex_file = load_string->GetDexFile();
2424 uint32_t utf16_length;
2425 const char* data =
2426 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2427 if (utf16_length == 0) {
2428 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2429 invoke->GetBlock()->RemoveInstruction(invoke);
2430 RecordSimplification();
2431 return;
2432 }
2433 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2434 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2435 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2436 uint32_t c = GetUtf16FromUtf8(&data);
2437 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2438 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2439 uint32_t dex_pc = invoke->GetDexPc();
2440 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2441 HEqual* equal =
2442 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2443 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2444 HSelect* result = new (allocator) HSelect(equal,
2445 GetGraph()->GetIntConstant(0),
2446 GetGraph()->GetIntConstant(-1),
2447 dex_pc);
2448 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2449 RecordSimplification();
2450 return;
2451 }
2452 }
2453}
2454
Aart Bikff7d89c2016-11-07 08:49:28 -08002455// This method should only be used on intrinsics whose sole way of throwing an
2456// exception is raising a NPE when the nth argument is null. If that argument
2457// is provably non-null, we can clear the flag.
2458void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2459 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002460 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002461 invoke->SetCanThrow(false);
2462 }
2463}
2464
Aart Bik71bf7b42016-11-16 10:17:46 -08002465// Methods that return "this" can replace the returned value with the receiver.
2466void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2467 if (invoke->HasUses()) {
2468 HInstruction* receiver = invoke->InputAt(0);
2469 invoke->ReplaceWith(receiver);
2470 RecordSimplification();
2471 }
2472}
2473
2474// Helper method for StringBuffer escape analysis.
2475static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2476 if (user->IsInvokeStaticOrDirect()) {
2477 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002478 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2479 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002480 user->InputAt(0) == reference;
2481 } else if (user->IsInvokeVirtual()) {
2482 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2483 case Intrinsics::kStringBufferLength:
2484 case Intrinsics::kStringBufferToString:
2485 DCHECK_EQ(user->InputAt(0), reference);
2486 return true;
2487 case Intrinsics::kStringBufferAppend:
2488 // Returns "this", so only okay if no further uses.
2489 DCHECK_EQ(user->InputAt(0), reference);
2490 DCHECK_NE(user->InputAt(1), reference);
2491 return !user->HasUses();
2492 default:
2493 break;
2494 }
2495 }
2496 return false;
2497}
2498
2499// Certain allocation intrinsics are not removed by dead code elimination
2500// because of potentially throwing an OOM exception or other side effects.
2501// This method removes such intrinsics when special circumstances allow.
2502void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2503 if (!invoke->HasUses()) {
2504 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2505 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2506 // call does not escape since only thread-local synchronization may be removed.
2507 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2508 HInstruction* receiver = invoke->InputAt(0);
2509 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2510 invoke->GetBlock()->RemoveInstruction(invoke);
2511 RecordSimplification();
2512 }
2513 }
2514}
2515
Vladimir Markoca6fff82017-10-03 14:49:14 +01002516void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2517 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002518 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002519 HMemoryBarrier* mem_barrier =
2520 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002521 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2522}
2523
Aart Bik1f8d51b2018-02-15 10:42:37 -08002524void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2525 DCHECK(invoke->IsInvokeStaticOrDirect());
2526 HMin* min = new (GetGraph()->GetAllocator())
2527 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2528 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2529}
2530
2531void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2532 DCHECK(invoke->IsInvokeStaticOrDirect());
2533 HMax* max = new (GetGraph()->GetAllocator())
2534 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2535 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2536}
2537
Aart Bik3dad3412018-02-28 12:01:46 -08002538void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2539 DCHECK(invoke->IsInvokeStaticOrDirect());
2540 HAbs* abs = new (GetGraph()->GetAllocator())
2541 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2542 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2543}
2544
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002545void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002546 switch (instruction->GetIntrinsic()) {
2547 case Intrinsics::kStringEquals:
2548 SimplifyStringEquals(instruction);
2549 break;
2550 case Intrinsics::kSystemArrayCopy:
2551 SimplifySystemArrayCopy(instruction);
2552 break;
2553 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002554 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002555 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002556 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002557 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002558 break;
2559 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002560 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002561 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002562 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002563 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002564 break;
2565 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002566 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002567 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002568 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002569 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002570 break;
2571 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002572 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002573 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002574 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002575 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002576 break;
2577 case Intrinsics::kFloatIsNaN:
2578 case Intrinsics::kDoubleIsNaN:
2579 SimplifyIsNaN(instruction);
2580 break;
2581 case Intrinsics::kFloatFloatToIntBits:
2582 case Intrinsics::kDoubleDoubleToLongBits:
2583 SimplifyFP2Int(instruction);
2584 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002585 case Intrinsics::kStringCharAt:
2586 SimplifyStringCharAt(instruction);
2587 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002588 case Intrinsics::kStringIsEmpty:
2589 case Intrinsics::kStringLength:
2590 SimplifyStringIsEmptyOrLength(instruction);
2591 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00002592 case Intrinsics::kStringIndexOf:
2593 case Intrinsics::kStringIndexOfAfter:
2594 SimplifyStringIndexOf(instruction);
2595 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002596 case Intrinsics::kStringStringIndexOf:
2597 case Intrinsics::kStringStringIndexOfAfter:
2598 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2599 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002600 case Intrinsics::kStringBufferAppend:
2601 case Intrinsics::kStringBuilderAppend:
2602 SimplifyReturnThis(instruction);
2603 break;
2604 case Intrinsics::kStringBufferToString:
2605 case Intrinsics::kStringBuilderToString:
2606 SimplifyAllocationIntrinsic(instruction);
2607 break;
Aart Bik11932592016-03-08 12:42:25 -08002608 case Intrinsics::kUnsafeLoadFence:
2609 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2610 break;
2611 case Intrinsics::kUnsafeStoreFence:
2612 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2613 break;
2614 case Intrinsics::kUnsafeFullFence:
2615 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2616 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002617 case Intrinsics::kVarHandleFullFence:
2618 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2619 break;
2620 case Intrinsics::kVarHandleAcquireFence:
2621 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2622 break;
2623 case Intrinsics::kVarHandleReleaseFence:
2624 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2625 break;
2626 case Intrinsics::kVarHandleLoadLoadFence:
2627 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2628 break;
2629 case Intrinsics::kVarHandleStoreStoreFence:
2630 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2631 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002632 case Intrinsics::kMathMinIntInt:
2633 SimplifyMin(instruction, DataType::Type::kInt32);
2634 break;
2635 case Intrinsics::kMathMinLongLong:
2636 SimplifyMin(instruction, DataType::Type::kInt64);
2637 break;
2638 case Intrinsics::kMathMinFloatFloat:
2639 SimplifyMin(instruction, DataType::Type::kFloat32);
2640 break;
2641 case Intrinsics::kMathMinDoubleDouble:
2642 SimplifyMin(instruction, DataType::Type::kFloat64);
2643 break;
2644 case Intrinsics::kMathMaxIntInt:
2645 SimplifyMax(instruction, DataType::Type::kInt32);
2646 break;
2647 case Intrinsics::kMathMaxLongLong:
2648 SimplifyMax(instruction, DataType::Type::kInt64);
2649 break;
2650 case Intrinsics::kMathMaxFloatFloat:
2651 SimplifyMax(instruction, DataType::Type::kFloat32);
2652 break;
2653 case Intrinsics::kMathMaxDoubleDouble:
2654 SimplifyMax(instruction, DataType::Type::kFloat64);
2655 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002656 case Intrinsics::kMathAbsInt:
2657 SimplifyAbs(instruction, DataType::Type::kInt32);
2658 break;
2659 case Intrinsics::kMathAbsLong:
2660 SimplifyAbs(instruction, DataType::Type::kInt64);
2661 break;
2662 case Intrinsics::kMathAbsFloat:
2663 SimplifyAbs(instruction, DataType::Type::kFloat32);
2664 break;
2665 case Intrinsics::kMathAbsDouble:
2666 SimplifyAbs(instruction, DataType::Type::kFloat64);
2667 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002668 default:
2669 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002670 }
2671}
2672
Aart Bikbb245d12015-10-19 11:05:03 -07002673void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2674 HInstruction* cond = deoptimize->InputAt(0);
2675 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002676 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002677 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002678 if (deoptimize->GuardsAnInput()) {
2679 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2680 }
Aart Bikbb245d12015-10-19 11:05:03 -07002681 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2682 } else {
2683 // Always deopt.
2684 }
2685 }
2686}
2687
Anton Kirilove14dc862016-05-13 17:56:15 +01002688// Replace code looking like
2689// OP y, x, const1
2690// OP z, y, const2
2691// with
2692// OP z, x, const3
2693// where OP is both an associative and a commutative operation.
2694bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2695 HBinaryOperation* instruction) {
2696 DCHECK(instruction->IsCommutative());
2697
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002698 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002699 return false;
2700 }
2701
2702 HInstruction* left = instruction->GetLeft();
2703 HInstruction* right = instruction->GetRight();
2704 // Variable names as described above.
2705 HConstant* const2;
2706 HBinaryOperation* y;
2707
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002708 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002709 const2 = right->AsConstant();
2710 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002711 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002712 const2 = left->AsConstant();
2713 y = right->AsBinaryOperation();
2714 } else {
2715 // The node does not match the pattern.
2716 return false;
2717 }
2718
2719 // If `y` has more than one use, we do not perform the optimization
2720 // because it might increase code size (e.g. if the new constant is
2721 // no longer encodable as an immediate operand in the target ISA).
2722 if (!y->HasOnlyOneNonEnvironmentUse()) {
2723 return false;
2724 }
2725
2726 // GetConstantRight() can return both left and right constants
2727 // for commutative operations.
2728 HConstant* const1 = y->GetConstantRight();
2729 if (const1 == nullptr) {
2730 return false;
2731 }
2732
2733 instruction->ReplaceInput(const1, 0);
2734 instruction->ReplaceInput(const2, 1);
2735 HConstant* const3 = instruction->TryStaticEvaluation();
2736 DCHECK(const3 != nullptr);
2737 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2738 instruction->ReplaceInput(const3, 1);
2739 RecordSimplification();
2740 return true;
2741}
2742
2743static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2744 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2745}
2746
2747// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002748static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002749 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002750 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002751 return HAdd::Compute<int32_t>(x, y);
2752 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002753 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002754 return HAdd::Compute<int64_t>(x, y);
2755 }
2756}
2757
2758// Helper function that handles the child classes of HConstant
2759// and returns an integer with the appropriate sign.
2760static int64_t GetValue(HConstant* constant, bool is_negated) {
2761 int64_t ret = Int64FromConstant(constant);
2762 return is_negated ? -ret : ret;
2763}
2764
2765// Replace code looking like
2766// OP1 y, x, const1
2767// OP2 z, y, const2
2768// with
2769// OP3 z, x, const3
2770// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2771bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2772 HBinaryOperation* instruction) {
2773 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2774
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002775 DataType::Type type = instruction->GetType();
2776 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002777 return false;
2778 }
2779
2780 HInstruction* left = instruction->GetLeft();
2781 HInstruction* right = instruction->GetRight();
2782 // Variable names as described above.
2783 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2784 if (const2 == nullptr) {
2785 return false;
2786 }
2787
2788 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2789 ? left->AsBinaryOperation()
2790 : AsAddOrSub(right);
2791 // If y has more than one use, we do not perform the optimization because
2792 // it might increase code size (e.g. if the new constant is no longer
2793 // encodable as an immediate operand in the target ISA).
2794 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2795 return false;
2796 }
2797
2798 left = y->GetLeft();
2799 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2800 if (const1 == nullptr) {
2801 return false;
2802 }
2803
2804 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2805 // If both inputs are constants, let the constant folding pass deal with it.
2806 if (x->IsConstant()) {
2807 return false;
2808 }
2809
2810 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2811 int64_t const2_val = GetValue(const2, is_const2_negated);
2812 bool is_y_negated = (y == right) && instruction->IsSub();
2813 right = y->GetRight();
2814 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2815 int64_t const1_val = GetValue(const1, is_const1_negated);
2816 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2817 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2818 HBasicBlock* block = instruction->GetBlock();
2819 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002820 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002821 HInstruction* z;
2822
2823 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002824 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002825 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002826 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002827 }
2828
2829 block->ReplaceAndRemoveInstructionWith(instruction, z);
2830 RecordSimplification();
2831 return true;
2832}
2833
Lena Djokicbc5460b2017-07-20 16:07:36 +02002834void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2835 if (TryCombineVecMultiplyAccumulate(instruction)) {
2836 RecordSimplification();
2837 }
2838}
2839
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002840} // namespace art