blob: 63c596541599243f07553c386e300bdefd6bd555 [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"
Vladimir Marko552a1342017-10-31 10:56:47 +000028#include "string_builder_append.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000029
Nicolas Geoffray3c049742014-09-24 18:10:46 +010030namespace art {
31
Artem Serovcced8ba2017-07-19 18:18:09 +010032// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
33// is replaced with its copy if it is clonable.
34static constexpr bool kTestInstructionClonerExhaustively = false;
35
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000037 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000038 InstructionSimplifierVisitor(HGraph* graph,
39 CodeGenerator* codegen,
40 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010041 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 codegen_(codegen),
Alexandre Rames188d4312015-04-09 18:30:21 +010043 stats_(stats) {}
44
Aart Bik24773202018-04-26 10:28:51 -070045 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000046
47 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010048 void RecordSimplification() {
49 simplification_occurred_ = true;
50 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000051 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010052 }
53
Scott Wakeling40a04bf2015-12-11 09:50:36 +000054 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55 bool TryReplaceWithRotate(HBinaryOperation* instruction);
56 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
57 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59
Alexandre Rames188d4312015-04-09 18:30:21 +010060 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000061 // `op` should be either HOr or HAnd.
62 // De Morgan's laws:
63 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
64 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010065 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
66 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020067 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010068
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitShift(HBinaryOperation* shift);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010070 void VisitEqual(HEqual* equal) override;
71 void VisitNotEqual(HNotEqual* equal) override;
72 void VisitBooleanNot(HBooleanNot* bool_not) override;
73 void VisitInstanceFieldSet(HInstanceFieldSet* equal) override;
74 void VisitStaticFieldSet(HStaticFieldSet* equal) override;
75 void VisitArraySet(HArraySet* equal) override;
76 void VisitTypeConversion(HTypeConversion* instruction) override;
77 void VisitNullCheck(HNullCheck* instruction) override;
78 void VisitArrayLength(HArrayLength* instruction) override;
79 void VisitCheckCast(HCheckCast* instruction) override;
80 void VisitAbs(HAbs* instruction) override;
81 void VisitAdd(HAdd* instruction) override;
82 void VisitAnd(HAnd* instruction) override;
83 void VisitCondition(HCondition* instruction) override;
84 void VisitGreaterThan(HGreaterThan* condition) override;
85 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) override;
86 void VisitLessThan(HLessThan* condition) override;
87 void VisitLessThanOrEqual(HLessThanOrEqual* condition) override;
88 void VisitBelow(HBelow* condition) override;
89 void VisitBelowOrEqual(HBelowOrEqual* condition) override;
90 void VisitAbove(HAbove* condition) override;
91 void VisitAboveOrEqual(HAboveOrEqual* condition) override;
92 void VisitDiv(HDiv* instruction) override;
93 void VisitMul(HMul* instruction) override;
94 void VisitNeg(HNeg* instruction) override;
95 void VisitNot(HNot* instruction) override;
96 void VisitOr(HOr* instruction) override;
97 void VisitShl(HShl* instruction) override;
98 void VisitShr(HShr* instruction) override;
99 void VisitSub(HSub* instruction) override;
100 void VisitUShr(HUShr* instruction) override;
101 void VisitXor(HXor* instruction) override;
102 void VisitSelect(HSelect* select) override;
103 void VisitIf(HIf* instruction) override;
104 void VisitInstanceOf(HInstanceOf* instruction) override;
105 void VisitInvoke(HInvoke* invoke) override;
106 void VisitDeoptimize(HDeoptimize* deoptimize) override;
107 void VisitVecMul(HVecMul* instruction) override;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100108
109 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000110
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100111 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100112 void SimplifySystemArrayCopy(HInvoke* invoke);
113 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100114 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800115 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800116 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100117 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100118 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000119 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800120 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800121 void SimplifyReturnThis(HInvoke* invoke);
122 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800123 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800124 void SimplifyMin(HInvoke* invoke, DataType::Type type);
125 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800126 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100127
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000128 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000129 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100130 bool simplification_occurred_ = false;
131 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700132 // We ensure we do not loop infinitely. The value should not be too high, since that
133 // would allow looping around the same basic block too many times. The value should
134 // not be too low either, however, since we want to allow revisiting a basic block
135 // with many statements and simplifications at least once.
136 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000137};
138
Aart Bik24773202018-04-26 10:28:51 -0700139bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100140 if (kTestInstructionClonerExhaustively) {
141 CloneAndReplaceInstructionVisitor visitor(graph_);
142 visitor.VisitReversePostOrder();
143 }
144
Vladimir Markobb089b62018-06-28 17:30:16 +0100145 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700146 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100147}
148
Aart Bik24773202018-04-26 10:28:51 -0700149bool InstructionSimplifierVisitor::Run() {
150 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100151 // Iterate in reverse post order to open up more simplifications to users
152 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100153 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100154 // The simplification of an instruction to another instruction may yield
155 // possibilities for other simplifications. So although we perform a reverse
156 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100157 do {
158 simplification_occurred_ = false;
159 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700160 if (simplification_occurred_) {
161 didSimplify = true;
162 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100163 } while (simplification_occurred_ &&
164 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100165 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100166 }
Aart Bik24773202018-04-26 10:28:51 -0700167 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100168}
169
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000170namespace {
171
172bool AreAllBitsSet(HConstant* constant) {
173 return Int64FromConstant(constant) == -1;
174}
175
176} // namespace
177
Alexandre Rames188d4312015-04-09 18:30:21 +0100178// Returns true if the code was simplified to use only one negation operation
179// after the binary operation instead of one on each of the inputs.
180bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
181 DCHECK(binop->IsAdd() || binop->IsSub());
182 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
183 HNeg* left_neg = binop->GetLeft()->AsNeg();
184 HNeg* right_neg = binop->GetRight()->AsNeg();
185 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
186 !right_neg->HasOnlyOneNonEnvironmentUse()) {
187 return false;
188 }
189 // Replace code looking like
190 // NEG tmp1, a
191 // NEG tmp2, b
192 // ADD dst, tmp1, tmp2
193 // with
194 // ADD tmp, a, b
195 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600196 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
197 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
198 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100199 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600200 return false;
201 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100202 binop->ReplaceInput(left_neg->GetInput(), 0);
203 binop->ReplaceInput(right_neg->GetInput(), 1);
204 left_neg->GetBlock()->RemoveInstruction(left_neg);
205 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100206 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100207 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
208 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
209 RecordSimplification();
210 return true;
211}
212
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000213bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
214 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100215 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000216 HInstruction* left = op->GetLeft();
217 HInstruction* right = op->GetRight();
218
219 // We can apply De Morgan's laws if both inputs are Not's and are only used
220 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000221 if (((left->IsNot() && right->IsNot()) ||
222 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000223 left->HasOnlyOneNonEnvironmentUse() &&
224 right->HasOnlyOneNonEnvironmentUse()) {
225 // Replace code looking like
226 // NOT nota, a
227 // NOT notb, b
228 // AND dst, nota, notb (respectively OR)
229 // with
230 // OR or, a, b (respectively AND)
231 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* src_left = left->InputAt(0);
233 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000234 uint32_t dex_pc = op->GetDexPc();
235
236 // Remove the negations on the inputs.
237 left->ReplaceWith(src_left);
238 right->ReplaceWith(src_right);
239 left->GetBlock()->RemoveInstruction(left);
240 right->GetBlock()->RemoveInstruction(right);
241
242 // Replace the `HAnd` or `HOr`.
243 HBinaryOperation* hbin;
244 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100245 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000246 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100247 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000248 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000249 HInstruction* hnot;
250 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100251 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000252 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100253 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000254 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000255
256 op->GetBlock()->InsertInstructionBefore(hbin, op);
257 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
258
259 RecordSimplification();
260 return true;
261 }
262
263 return false;
264}
265
Lena Djokicbc5460b2017-07-20 16:07:36 +0200266bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100267 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200268 InstructionSet isa = codegen_->GetInstructionSet();
269 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000270 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100271 if (!(type == DataType::Type::kUint8 ||
272 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100273 type == DataType::Type::kUint16 ||
274 type == DataType::Type::kInt16 ||
275 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200276 return false;
277 }
278 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000279 case InstructionSet::kMips:
280 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100281 if (!(type == DataType::Type::kUint8 ||
282 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100283 type == DataType::Type::kUint16 ||
284 type == DataType::Type::kInt16 ||
285 type == DataType::Type::kInt32 ||
286 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200287 return false;
288 }
289 break;
290 default:
291 return false;
292 }
293
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100294 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200295
296 if (mul->HasOnlyOneNonEnvironmentUse()) {
297 HInstruction* use = mul->GetUses().front().GetUser();
298 if (use->IsVecAdd() || use->IsVecSub()) {
299 // Replace code looking like
300 // VECMUL tmp, x, y
301 // VECADD/SUB dst, acc, tmp
302 // with
303 // VECMULACC dst, acc, x, y
304 // Note that we do not want to (unconditionally) perform the merge when the
305 // multiplication has multiple uses and it can be merged in all of them.
306 // Multiple uses could happen on the same control-flow path, and we would
307 // then increase the amount of work. In the future we could try to evaluate
308 // whether all uses are on different control-flow paths (using dominance and
309 // reverse-dominance information) and only perform the merge when they are.
310 HInstruction* accumulator = nullptr;
311 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
312 HInstruction* binop_left = binop->GetLeft();
313 HInstruction* binop_right = binop->GetRight();
314 // This is always true since the `HVecMul` has only one use (which is checked above).
315 DCHECK_NE(binop_left, binop_right);
316 if (binop_right == mul) {
317 accumulator = binop_left;
318 } else if (use->IsVecAdd()) {
319 DCHECK_EQ(binop_left, mul);
320 accumulator = binop_right;
321 }
322
323 HInstruction::InstructionKind kind =
324 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
325 if (accumulator != nullptr) {
326 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100327 new (allocator) HVecMultiplyAccumulate(allocator,
328 kind,
329 accumulator,
330 mul->GetLeft(),
331 mul->GetRight(),
332 binop->GetPackedType(),
333 binop->GetVectorLength(),
334 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200335
336 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
337 DCHECK(!mul->HasUses());
338 mul->GetBlock()->RemoveInstruction(mul);
339 return true;
340 }
341 }
342 }
343
344 return false;
345}
346
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000347void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
348 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100349 HInstruction* shift_amount = instruction->GetRight();
350 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000351
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100352 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100353 ? kMaxLongShiftDistance
354 : kMaxIntShiftDistance;
355
356 if (shift_amount->IsConstant()) {
357 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700358 int64_t masked_cst = cst & implicit_mask;
359 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400360 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100361 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400362 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100363 // value
364 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400365 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100366 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100367 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700368 } else if (masked_cst != cst) {
369 // Replace code looking like
370 // SHL dst, value, cst
371 // where cst exceeds maximum distance with the equivalent
372 // SHL dst, value, cst & implicit_mask
373 // (as defined by shift semantics). This ensures other
374 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100375 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Andreas Gampe3db70682018-12-26 15:12:03 -0800376 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index= */ 1);
Aart Bik50e20d52017-05-05 14:07:29 -0700377 RecordSimplification();
378 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100379 }
380 }
381
382 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100383 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
384 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100385 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 // AND adjusted_shift, shift, <superset of implicit mask>
387 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
388 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
389 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100390 // with
391 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100392 if (shift_amount->IsAnd() ||
393 shift_amount->IsOr() ||
394 shift_amount->IsXor() ||
395 shift_amount->IsAdd() ||
396 shift_amount->IsSub()) {
397 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
398 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
399 HConstant* mask = bin_op->GetConstantRight();
400 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
401 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100402 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100403 return;
404 }
405 } else if (shift_amount->IsTypeConversion()) {
406 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
407 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
408 // Non-integral and 64-bit source types require an explicit type conversion.
409 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
410 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
411 RecordSimplification();
412 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400413 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000414 }
415}
416
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000417static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
418 return (sub->GetRight() == other &&
419 sub->GetLeft()->IsConstant() &&
420 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
421}
422
423bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
424 HUShr* ushr,
425 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000426 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100427 HRor* ror =
428 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000429 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
430 if (!ushr->HasUses()) {
431 ushr->GetBlock()->RemoveInstruction(ushr);
432 }
433 if (!ushr->GetRight()->HasUses()) {
434 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
435 }
436 if (!shl->HasUses()) {
437 shl->GetBlock()->RemoveInstruction(shl);
438 }
439 if (!shl->GetRight()->HasUses()) {
440 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
441 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100442 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000443 return true;
444}
445
446// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
447bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000448 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
449 HInstruction* left = op->GetLeft();
450 HInstruction* right = op->GetRight();
451 // If we have an UShr and a Shl (in either order).
452 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
453 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
454 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100455 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000456 if (ushr->GetType() == shl->GetType() &&
457 ushr->GetLeft() == shl->GetLeft()) {
458 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
459 // Shift distances are both constant, try replacing with Ror if they
460 // add up to the register size.
461 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
462 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
463 // Shift distances are potentially of the form x and (reg_size - x).
464 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
465 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
466 // Shift distances are potentially of the form d and -d.
467 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
468 }
469 }
470 }
471 return false;
472}
473
474// Try replacing code looking like (x >>> #rdist OP x << #ldist):
475// UShr dst, x, #rdist
476// Shl tmp, x, #ldist
477// OP dst, dst, tmp
478// or like (x >>> #rdist OP x << #-ldist):
479// UShr dst, x, #rdist
480// Shl tmp, x, #-ldist
481// OP dst, dst, tmp
482// with
483// Ror dst, x, #rdist
484bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
485 HUShr* ushr,
486 HShl* shl) {
487 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100488 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000489 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
490 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
491 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
492 ReplaceRotateWithRor(op, ushr, shl);
493 return true;
494 }
495 return false;
496}
497
498// Replace code looking like (x >>> -d OP x << d):
499// Neg neg, d
500// UShr dst, x, neg
501// Shl tmp, x, d
502// OP dst, dst, tmp
503// with
504// Neg neg, d
505// Ror dst, x, neg
506// *** OR ***
507// Replace code looking like (x >>> d OP x << -d):
508// UShr dst, x, d
509// Neg neg, d
510// Shl tmp, x, neg
511// OP dst, dst, tmp
512// with
513// Ror dst, x, d
514bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
515 HUShr* ushr,
516 HShl* shl) {
517 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
518 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
519 bool neg_is_left = shl->GetRight()->IsNeg();
520 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
521 // And the shift distance being negated is the distance being shifted the other way.
522 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
523 ReplaceRotateWithRor(op, ushr, shl);
524 }
525 return false;
526}
527
528// Try replacing code looking like (x >>> d OP x << (#bits - d)):
529// UShr dst, x, d
530// Sub ld, #bits, d
531// Shl tmp, x, ld
532// OP dst, dst, tmp
533// with
534// Ror dst, x, d
535// *** OR ***
536// Replace code looking like (x >>> (#bits - d) OP x << d):
537// Sub rd, #bits, d
538// UShr dst, x, rd
539// Shl tmp, x, d
540// OP dst, dst, tmp
541// with
542// Neg neg, d
543// Ror dst, x, neg
544bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
545 HUShr* ushr,
546 HShl* shl) {
547 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
548 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100549 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000550 HInstruction* shl_shift = shl->GetRight();
551 HInstruction* ushr_shift = ushr->GetRight();
552 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
553 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
554 return ReplaceRotateWithRor(op, ushr, shl);
555 }
556 return false;
557}
558
Calin Juravle10e244f2015-01-26 18:54:32 +0000559void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
560 HInstruction* obj = null_check->InputAt(0);
561 if (!obj->CanBeNull()) {
562 null_check->ReplaceWith(obj);
563 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000564 if (stats_ != nullptr) {
565 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
566 }
567 }
568}
569
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100570bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
571 if (!input->CanBeNull()) {
572 return true;
573 }
574
Vladimir Marko46817b82016-03-29 12:21:58 +0100575 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
576 HInstruction* user = use.GetUser();
577 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100578 return true;
579 }
580 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100581
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100582 return false;
583}
584
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100585// Returns whether doing a type test between the class of `object` against `klass` has
586// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000587static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
588 HInstruction* object,
589 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000590 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
591 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
592 ScopedObjectAccess soa(Thread::Current());
593 if (!obj_rti.IsValid()) {
594 // We run the simplifier before the reference type propagation so type info might not be
595 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000597 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100598
Calin Juravle98893e12015-10-02 21:05:03 +0100599 if (!class_rti.IsValid()) {
600 // Happens when the loaded class is unresolved.
601 return false;
602 }
603 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000604 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100605 *outcome = true;
606 return true;
607 } else if (obj_rti.IsExact()) {
608 // The test failed at compile time so will also fail at runtime.
609 *outcome = false;
610 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100611 } else if (!class_rti.IsInterface()
612 && !obj_rti.IsInterface()
613 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100614 // Different type hierarchy. The test will fail.
615 *outcome = false;
616 return true;
617 }
618 return false;
619}
620
621void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
622 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000623 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
624 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100625 // If we need to perform an access check we cannot remove the instruction.
626 return;
627 }
628
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100629 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100630 check_cast->ClearMustDoNullCheck();
631 }
632
633 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000634 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700635 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100636 return;
637 }
638
Roland Levillain05e34f42018-05-24 13:19:05 +0000639 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
640 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000641 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000642 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100643 if (outcome) {
644 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700645 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000646 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
647 HLoadClass* load_class = check_cast->GetTargetClass();
648 if (!load_class->HasUses()) {
649 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
650 // However, here we know that it cannot because the checkcast was successfull, hence
651 // the class was already loaded.
652 load_class->GetBlock()->RemoveInstruction(load_class);
653 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700654 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100655 } else {
656 // Don't do anything for exceptional cases for now. Ideally we should remove
657 // all instructions and blocks this instruction dominates.
658 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000659 }
660}
661
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100662void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100663 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000664 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
665 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100666 // If we need to perform an access check we cannot remove the instruction.
667 return;
668 }
669
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100670 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100671 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100673 instruction->ClearMustDoNullCheck();
674 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100675
676 HGraph* graph = GetGraph();
677 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000678 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100679 instruction->ReplaceWith(graph->GetIntConstant(0));
680 instruction->GetBlock()->RemoveInstruction(instruction);
681 RecordSimplification();
682 return;
683 }
684
Roland Levillain05e34f42018-05-24 13:19:05 +0000685 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
686 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000687 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000688 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000689 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100690 if (outcome && can_be_null) {
691 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100692 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100693 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
694 instruction->ReplaceWith(test);
695 } else {
696 // We've statically determined the result of the instanceof.
697 instruction->ReplaceWith(graph->GetIntConstant(outcome));
698 }
699 RecordSimplification();
700 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000701 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
702 HLoadClass* load_class = instruction->GetTargetClass();
703 if (!load_class->HasUses()) {
704 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
705 // However, here we know that it cannot because the instanceof check was successfull, hence
706 // the class was already loaded.
707 load_class->GetBlock()->RemoveInstruction(load_class);
708 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700709 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100710 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100711}
712
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100713void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100714 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100715 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100716 instruction->ClearValueCanBeNull();
717 }
718}
719
720void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100721 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100722 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100723 instruction->ClearValueCanBeNull();
724 }
725}
726
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100727static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600728 HInstruction *lhs = cond->InputAt(0);
729 HInstruction *rhs = cond->InputAt(1);
730 switch (cond->GetKind()) {
731 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100732 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600733 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100734 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600735 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100736 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600737 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100738 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600739 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100740 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600741 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100742 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600743 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100744 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600745 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100746 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600747 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100748 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600749 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100750 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600751 default:
752 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800753 UNREACHABLE();
Anton Shaminbdd79352016-02-15 12:48:36 +0600754 }
Anton Shaminbdd79352016-02-15 12:48:36 +0600755}
756
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000757void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100758 HInstruction* input_const = equal->GetConstantRight();
759 if (input_const != nullptr) {
760 HInstruction* input_value = equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100761 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100763 // We are comparing the boolean to a constant which is of type int and can
764 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000765 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100766 // Replace (bool_value == true) with bool_value
767 equal->ReplaceWith(input_value);
768 block->RemoveInstruction(equal);
769 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000770 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700771 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500772 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
773 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100774 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100775 } else {
776 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
777 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
778 block->RemoveInstruction(equal);
779 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100780 }
Mark Mendellc4701932015-04-10 13:18:51 -0400781 } else {
782 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100783 }
Mark Mendellc4701932015-04-10 13:18:51 -0400784 } else {
785 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100786 }
787}
788
David Brazdil0d13fee2015-04-17 14:52:19 +0100789void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
790 HInstruction* input_const = not_equal->GetConstantRight();
791 if (input_const != nullptr) {
792 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100793 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100794 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100795 // We are comparing the boolean to a constant which is of type int and can
796 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000797 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700798 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500799 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
800 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000802 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100803 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100804 not_equal->ReplaceWith(input_value);
805 block->RemoveInstruction(not_equal);
806 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100807 } else {
808 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
809 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
810 block->RemoveInstruction(not_equal);
811 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100812 }
Mark Mendellc4701932015-04-10 13:18:51 -0400813 } else {
814 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100815 }
Mark Mendellc4701932015-04-10 13:18:51 -0400816 } else {
817 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100818 }
819}
820
821void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000822 HInstruction* input = bool_not->InputAt(0);
823 HInstruction* replace_with = nullptr;
824
825 if (input->IsIntConstant()) {
826 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000827 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000828 replace_with = GetGraph()->GetIntConstant(0);
829 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000830 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000831 replace_with = GetGraph()->GetIntConstant(1);
832 }
833 } else if (input->IsBooleanNot()) {
834 // Replace (!(!bool_value)) with bool_value.
835 replace_with = input->InputAt(0);
836 } else if (input->IsCondition() &&
837 // Don't change FP compares. The definition of compares involving
838 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100839 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000840 // Replace condition with its opposite.
841 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
842 }
843
844 if (replace_with != nullptr) {
845 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100846 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000847 RecordSimplification();
848 }
849}
850
Aart Bik4f7dd342017-09-12 13:12:57 -0700851// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100852static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
853 HInstruction* x,
854 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700855 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800856 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700857 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800858 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
859 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700860}
861
Aart Bik142b9132018-03-14 15:12:59 -0700862// Constructs a new MIN/MAX(x, y) node in the HIR.
863static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
864 HInstruction* x,
865 HInstruction* y,
866 HInstruction* cursor,
867 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700868 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700869 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
870 HBinaryOperation* minmax = nullptr;
871 if (is_min) {
872 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
873 } else {
874 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
875 }
876 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
877 return minmax;
878}
879
Aart Bik4f7dd342017-09-12 13:12:57 -0700880// Returns true if operands a and b consists of widening type conversions
881// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100882static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700883 if (a->IsTypeConversion() && a->GetType() == to_type) {
884 a = a->InputAt(0);
885 }
886 if (b->IsTypeConversion() && b->GetType() == to_type) {
887 b = b->InputAt(0);
888 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100889 DataType::Type type1 = a->GetType();
890 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100891 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
892 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
893 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
894 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
895 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100896 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700897}
898
Aart Bik1d746de2018-03-28 16:30:02 -0700899// Returns an acceptable substitution for "a" on the select
900// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
901static HInstruction* AllowInMinMax(IfCondition cmp,
902 HInstruction* a,
903 HInstruction* b,
904 HInstruction* c) {
905 int64_t value = 0;
906 if (IsInt64AndGet(b, /*out*/ &value) &&
907 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
908 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
909 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
910 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
911 int64_t other_value = Int64FromConstant(other);
912 bool is_max = (cmp == kCondLT || cmp == kCondLE);
913 // Allow the max for a < 100 ? max(a, -100) : ..
914 // or the min for a > -100 ? min(a, 100) : ..
915 if (is_max ? (value >= other_value) : (value <= other_value)) {
916 return c;
917 }
918 }
919 }
920 return nullptr;
921}
922
David Brazdil74eb1b22015-12-14 11:44:01 +0000923void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
924 HInstruction* replace_with = nullptr;
925 HInstruction* condition = select->GetCondition();
926 HInstruction* true_value = select->GetTrueValue();
927 HInstruction* false_value = select->GetFalseValue();
928
929 if (condition->IsBooleanNot()) {
930 // Change ((!cond) ? x : y) to (cond ? y : x).
931 condition = condition->InputAt(0);
932 std::swap(true_value, false_value);
933 select->ReplaceInput(false_value, 0);
934 select->ReplaceInput(true_value, 1);
935 select->ReplaceInput(condition, 2);
936 RecordSimplification();
937 }
938
939 if (true_value == false_value) {
940 // Replace (cond ? x : x) with (x).
941 replace_with = true_value;
942 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000943 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000944 // Replace (true ? x : y) with (x).
945 replace_with = true_value;
946 } else {
947 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000948 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000949 replace_with = false_value;
950 }
951 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000952 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000953 // Replace (cond ? true : false) with (cond).
954 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000955 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000956 // Replace (cond ? false : true) with (!cond).
957 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
958 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700959 } else if (condition->IsCondition()) {
960 IfCondition cmp = condition->AsCondition()->GetCondition();
961 HInstruction* a = condition->InputAt(0);
962 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100963 DataType::Type t_type = true_value->GetType();
964 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700965 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700966 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
967 // type will be int or long, like the condition). Replacements are general,
968 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700969 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700970 // Allow a < 100 ? max(a, -100) : ..
971 // or a > -100 ? min(a, 100) : ..
972 // to use min/max instead of a to detect nested min/max expressions.
973 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
974 if (new_a != nullptr) {
975 a = new_a;
976 }
Aart Bik142b9132018-03-14 15:12:59 -0700977 // Try to replace typical integral MIN/MAX/ABS constructs.
978 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
979 ((a == true_value && b == false_value) ||
980 (b == true_value && a == false_value))) {
981 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
982 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
983 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
984 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700985 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
986 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
987 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
988 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
989 HInstruction* not_negated = negLeft ? false_value : true_value;
990 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
991 // Found a < 0 ? -a : a
992 // or a > 0 ? a : -a
993 // which can be replaced by ABS(a).
994 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700995 }
996 } else if (true_value->IsSub() && false_value->IsSub()) {
997 HInstruction* true_sub1 = true_value->InputAt(0);
998 HInstruction* true_sub2 = true_value->InputAt(1);
999 HInstruction* false_sub1 = false_value->InputAt(0);
1000 HInstruction* false_sub2 = false_value->InputAt(1);
1001 if ((((cmp == kCondGT || cmp == kCondGE) &&
1002 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1003 ((cmp == kCondLT || cmp == kCondLE) &&
1004 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1005 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001006 // Found a > b ? a - b : b - a
1007 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001008 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001009 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001010 }
1011 }
1012 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001013 }
1014
1015 if (replace_with != nullptr) {
1016 select->ReplaceWith(replace_with);
1017 select->GetBlock()->RemoveInstruction(select);
1018 RecordSimplification();
1019 }
1020}
1021
1022void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1023 HInstruction* condition = instruction->InputAt(0);
1024 if (condition->IsBooleanNot()) {
1025 // Swap successors if input is negated.
1026 instruction->ReplaceInput(condition->InputAt(0), 0);
1027 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001028 RecordSimplification();
1029 }
1030}
1031
Mingyao Yang0304e182015-01-30 16:41:29 -08001032void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1033 HInstruction* input = instruction->InputAt(0);
1034 // If the array is a NewArray with constant size, replace the array length
1035 // with the constant instruction. This helps the bounds check elimination phase.
1036 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001037 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001038 if (input->IsIntConstant()) {
1039 instruction->ReplaceWith(input);
1040 }
1041 }
1042}
1043
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001044void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001045 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001046 if (value->GetType() != DataType::Type::kReference) {
1047 return;
1048 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001049
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001050 if (CanEnsureNotNullAt(value, instruction)) {
1051 instruction->ClearValueCanBeNull();
1052 }
1053
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001054 if (value->IsArrayGet()) {
1055 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1056 // If the code is just swapping elements in the array, no need for a type check.
1057 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001058 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001059 }
1060 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001061
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001062 if (value->IsNullConstant()) {
1063 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001064 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001065 }
1066
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001067 ScopedObjectAccess soa(Thread::Current());
1068 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1069 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1070 if (!array_rti.IsValid()) {
1071 return;
1072 }
1073
1074 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1075 instruction->ClearNeedsTypeCheck();
1076 return;
1077 }
1078
1079 if (array_rti.IsObjectArray()) {
1080 if (array_rti.IsExact()) {
1081 instruction->ClearNeedsTypeCheck();
1082 return;
1083 }
1084 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001085 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001086}
1087
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001088static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001089 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1090 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1091 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001092 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001093 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001094 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1095 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001096 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001097 return DataType::Size(result_type) > DataType::Size(input_type) &&
1098 result_type != DataType::Type::kUint16 &&
1099 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001100}
1101
Vladimir Marko61b92282017-10-11 13:23:17 +01001102static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1103 if (maybe_get->IsInstanceFieldGet()) {
1104 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1105 return true;
1106 } else if (maybe_get->IsStaticFieldGet()) {
1107 maybe_get->AsStaticFieldGet()->SetType(new_type);
1108 return true;
1109 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1110 maybe_get->AsArrayGet()->SetType(new_type);
1111 return true;
1112 } else {
1113 return false;
1114 }
1115}
1116
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001117// The type conversion is only used for storing into a field/element of the
1118// same/narrower size.
1119static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1120 if (type_conversion->HasEnvironmentUses()) {
1121 return false;
1122 }
1123 DataType::Type input_type = type_conversion->GetInputType();
1124 DataType::Type result_type = type_conversion->GetResultType();
1125 if (!DataType::IsIntegralType(input_type) ||
1126 !DataType::IsIntegralType(result_type) ||
1127 input_type == DataType::Type::kInt64 ||
1128 result_type == DataType::Type::kInt64) {
1129 // Type conversion is needed if non-integer types are involved, or 64-bit
1130 // types are involved, which may use different number of registers.
1131 return false;
1132 }
1133 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1134 // Type conversion is not necessary when storing to a field/element of the
1135 // same/smaller size.
1136 } else {
1137 // We do not handle this case here.
1138 return false;
1139 }
1140
1141 // Check if the converted value is only used for storing into heap.
1142 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1143 HInstruction* instruction = use.GetUser();
1144 if (instruction->IsInstanceFieldSet() &&
1145 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1146 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1147 continue;
1148 }
1149 if (instruction->IsStaticFieldSet() &&
1150 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1151 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1152 continue;
1153 }
1154 if (instruction->IsArraySet() &&
1155 instruction->AsArraySet()->GetComponentType() == result_type &&
1156 // not index use.
1157 instruction->AsArraySet()->GetIndex() != type_conversion) {
1158 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1159 continue;
1160 }
1161 // The use is not as a store value, or the field/element type is not the
1162 // same as the result_type, keep the type conversion.
1163 return false;
1164 }
1165 // Codegen automatically handles the type conversion during the store.
1166 return true;
1167}
1168
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001169void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001170 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001171 DataType::Type input_type = input->GetType();
1172 DataType::Type result_type = instruction->GetResultType();
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001173 if (instruction->IsImplicitConversion()) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001174 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001175 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001176 RecordSimplification();
1177 return;
1178 }
1179
1180 if (input->IsTypeConversion()) {
1181 HTypeConversion* input_conversion = input->AsTypeConversion();
1182 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001183 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001184
1185 // When the first conversion is lossless, a direct conversion from the original type
1186 // to the final type yields the same result, even for a lossy second conversion, for
1187 // example float->double->int or int->double->float.
1188 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1189
1190 // For integral conversions, see if the first conversion loses only bits that the second
1191 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1192 // conversion yields the same result, for example long->int->short or int->char->short.
1193 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001194 DataType::IsIntegralType(input_type) &&
1195 DataType::IsIntegralType(original_type) &&
1196 DataType::IsIntegralType(result_type) &&
1197 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001198
1199 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1200 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001201 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001202 instruction->ReplaceWith(original_input);
1203 instruction->GetBlock()->RemoveInstruction(instruction);
1204 if (!input_conversion->HasUses()) {
1205 // Don't wait for DCE.
1206 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1207 }
1208 RecordSimplification();
1209 return;
1210 }
1211 // Otherwise simplify only if the first conversion has no other use.
1212 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1213 input_conversion->ReplaceWith(original_input);
1214 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1215 RecordSimplification();
1216 return;
1217 }
1218 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001219 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1220 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001221 HAnd* input_and = input->AsAnd();
1222 HConstant* constant = input_and->GetConstantRight();
1223 if (constant != nullptr) {
1224 int64_t value = Int64FromConstant(constant);
1225 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1226 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001227 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001228 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001229 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001230 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001231 instruction->ReplaceWith(original_input);
1232 instruction->GetBlock()->RemoveInstruction(instruction);
1233 RecordSimplification();
1234 return;
1235 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1236 input_and->ReplaceWith(original_input);
1237 input_and->GetBlock()->RemoveInstruction(input_and);
1238 RecordSimplification();
1239 return;
1240 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001241 }
1242 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001243 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1244 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1245 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1246 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1247 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1248 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1249 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1250 instruction->ReplaceWith(input);
1251 instruction->GetBlock()->RemoveInstruction(instruction);
1252 RecordSimplification();
1253 return;
1254 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001255 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001256
1257 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1258 instruction->ReplaceWith(input);
1259 instruction->GetBlock()->RemoveInstruction(instruction);
1260 RecordSimplification();
1261 return;
1262 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001263}
1264
Aart Bikc6eec4b2018-03-29 17:22:00 -07001265void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1266 HInstruction* input = instruction->GetInput();
1267 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1268 // Zero extension from narrow to wide can never set sign bit in the wider
1269 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1270 instruction->ReplaceWith(input);
1271 instruction->GetBlock()->RemoveInstruction(instruction);
1272 RecordSimplification();
1273 }
1274}
1275
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001276void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1277 HConstant* input_cst = instruction->GetConstantRight();
1278 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001279 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001280 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001281 // Replace code looking like
1282 // ADD dst, src, 0
1283 // with
1284 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001285 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1286 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1287 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001288 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001289 instruction->ReplaceWith(input_other);
1290 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001291 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001292 return;
1293 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001294 }
1295
1296 HInstruction* left = instruction->GetLeft();
1297 HInstruction* right = instruction->GetRight();
1298 bool left_is_neg = left->IsNeg();
1299 bool right_is_neg = right->IsNeg();
1300
1301 if (left_is_neg && right_is_neg) {
1302 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1303 return;
1304 }
1305 }
1306
1307 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
Andreas Gampe654698d2018-09-20 13:34:35 -07001308 if (left_is_neg != right_is_neg && neg->HasOnlyOneNonEnvironmentUse()) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001309 // Replace code looking like
1310 // NEG tmp, b
1311 // ADD dst, a, tmp
1312 // with
1313 // SUB dst, a, b
1314 // We do not perform the optimization if the input negation has environment
1315 // uses or multiple non-environment uses as it could lead to worse code. In
1316 // particular, we do not want the live range of `b` to be extended if we are
1317 // not sure the initial 'NEG' instruction can be removed.
1318 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001319 HSub* sub =
1320 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001321 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1322 RecordSimplification();
1323 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001324 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001325 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001326
Anton Kirilove14dc862016-05-13 17:56:15 +01001327 if (TryReplaceWithRotate(instruction)) {
1328 return;
1329 }
1330
1331 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1332 // so no need to return.
1333 TryHandleAssociativeAndCommutativeOperation(instruction);
1334
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001335 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001336 TrySubtractionChainSimplification(instruction)) {
1337 return;
1338 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001339
1340 if (integral_type) {
1341 // Replace code patterns looking like
1342 // SUB dst1, x, y SUB dst1, x, y
1343 // ADD dst2, dst1, y ADD dst2, y, dst1
1344 // with
1345 // SUB dst1, x, y
1346 // ADD instruction is not needed in this case, we may use
1347 // one of inputs of SUB instead.
1348 if (left->IsSub() && left->InputAt(1) == right) {
1349 instruction->ReplaceWith(left->InputAt(0));
1350 RecordSimplification();
1351 instruction->GetBlock()->RemoveInstruction(instruction);
1352 return;
1353 } else if (right->IsSub() && right->InputAt(1) == left) {
1354 instruction->ReplaceWith(right->InputAt(0));
1355 RecordSimplification();
1356 instruction->GetBlock()->RemoveInstruction(instruction);
1357 return;
1358 }
1359 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001360}
1361
1362void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001363 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001364 HConstant* input_cst = instruction->GetConstantRight();
1365 HInstruction* input_other = instruction->GetLeastConstantLeft();
1366
Vladimir Marko452c1b62015-09-25 14:44:17 +01001367 if (input_cst != nullptr) {
1368 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001369 if (value == -1 ||
1370 // Similar cases under zero extension.
1371 (DataType::IsUnsignedType(input_other->GetType()) &&
1372 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001373 // Replace code looking like
1374 // AND dst, src, 0xFFF...FF
1375 // with
1376 // src
1377 instruction->ReplaceWith(input_other);
1378 instruction->GetBlock()->RemoveInstruction(instruction);
1379 RecordSimplification();
1380 return;
1381 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001382 if (input_other->IsTypeConversion() &&
1383 input_other->GetType() == DataType::Type::kInt64 &&
1384 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1385 IsInt<32>(value) &&
1386 input_other->HasOnlyOneNonEnvironmentUse()) {
1387 // The AND can be reordered before the TypeConversion. Replace
1388 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1389 // TypeConversion<Int64> tmp, src
1390 // AND dst, tmp, cst
1391 // with
1392 // IntConstant cst, <32-bit-constant>
1393 // AND tmp, src, cst
1394 // TypeConversion<Int64> dst, tmp
1395 // This helps 32-bit targets and does not hurt 64-bit targets.
1396 // This also simplifies detection of other patterns, such as Uint8 loads.
1397 HInstruction* new_and_input = input_other->InputAt(0);
1398 // Implicit conversion Int64->Int64 would have been removed previously.
1399 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1400 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1401 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001402 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001403 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1404 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001405 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001406 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1407 input_other->GetBlock()->RemoveInstruction(input_other);
1408 RecordSimplification();
1409 // Try to process the new And now, do not wait for the next round of simplifications.
1410 instruction = new_and;
1411 input_other = new_and_input;
1412 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001413 // Eliminate And from UShr+And if the And-mask contains all the bits that
1414 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1415 // precisely clears the shifted-in sign bits.
1416 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001417 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001418 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1419 size_t num_tail_bits_set = CTZ(value + 1);
1420 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1421 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1422 instruction->ReplaceWith(input_other);
1423 instruction->GetBlock()->RemoveInstruction(instruction);
1424 RecordSimplification();
1425 return;
1426 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1427 input_other->HasOnlyOneNonEnvironmentUse()) {
1428 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1429 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001430 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001431 input_other->InputAt(0),
1432 input_other->InputAt(1),
1433 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001434 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1435 input_other->GetBlock()->RemoveInstruction(input_other);
1436 RecordSimplification();
1437 return;
1438 }
1439 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001440 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1441 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1442 // or array Get with only a single use, short-circuit the subsequent simplification
1443 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1444 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1445 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1446 if (input_other->GetType() == find_type &&
1447 input_other->HasOnlyOneNonEnvironmentUse() &&
1448 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1449 instruction->ReplaceWith(input_other);
1450 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001451 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1452 instruction->ReplaceWith(input_other);
1453 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001454 } else {
1455 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1456 new_type, input_other, instruction->GetDexPc());
1457 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1458 }
1459 RecordSimplification();
1460 return;
1461 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001462 }
1463
1464 // We assume that GVN has run before, so we only perform a pointer comparison.
1465 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001466 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001467 if (instruction->GetLeft() == instruction->GetRight()) {
1468 // Replace code looking like
1469 // AND dst, src, src
1470 // with
1471 // src
1472 instruction->ReplaceWith(instruction->GetLeft());
1473 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001474 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001475 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001476 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001477
Anton Kirilove14dc862016-05-13 17:56:15 +01001478 if (TryDeMorganNegationFactoring(instruction)) {
1479 return;
1480 }
1481
1482 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1483 // so no need to return.
1484 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001485}
1486
Mark Mendellc4701932015-04-10 13:18:51 -04001487void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1488 VisitCondition(condition);
1489}
1490
1491void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1492 VisitCondition(condition);
1493}
1494
1495void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1496 VisitCondition(condition);
1497}
1498
1499void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1500 VisitCondition(condition);
1501}
1502
Anton Shaminbdd79352016-02-15 12:48:36 +06001503void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1504 VisitCondition(condition);
1505}
1506
1507void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1508 VisitCondition(condition);
1509}
1510
1511void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1512 VisitCondition(condition);
1513}
1514
1515void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1516 VisitCondition(condition);
1517}
Aart Bike9f37602015-10-09 11:15:55 -07001518
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001519// Recognize the following pattern:
1520// obj.getClass() ==/!= Foo.class
1521// And replace it with a constant value if the type of `obj` is statically known.
1522static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1523 HInstruction* input_one = condition->InputAt(0);
1524 HInstruction* input_two = condition->InputAt(1);
1525 HLoadClass* load_class = input_one->IsLoadClass()
1526 ? input_one->AsLoadClass()
1527 : input_two->AsLoadClass();
1528 if (load_class == nullptr) {
1529 return false;
1530 }
1531
1532 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1533 if (!class_rti.IsValid()) {
1534 // Unresolved class.
1535 return false;
1536 }
1537
1538 HInstanceFieldGet* field_get = (load_class == input_one)
1539 ? input_two->AsInstanceFieldGet()
1540 : input_one->AsInstanceFieldGet();
1541 if (field_get == nullptr) {
1542 return false;
1543 }
1544
1545 HInstruction* receiver = field_get->InputAt(0);
1546 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1547 if (!receiver_type.IsExact()) {
1548 return false;
1549 }
1550
1551 {
1552 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001553 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001554 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1555 if (field_get->GetFieldInfo().GetField() != field) {
1556 return false;
1557 }
1558
1559 // We can replace the compare.
1560 int value = 0;
1561 if (receiver_type.IsEqual(class_rti)) {
1562 value = condition->IsEqual() ? 1 : 0;
1563 } else {
1564 value = condition->IsNotEqual() ? 1 : 0;
1565 }
1566 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1567 return true;
1568 }
1569}
1570
Mark Mendellc4701932015-04-10 13:18:51 -04001571void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001572 if (condition->IsEqual() || condition->IsNotEqual()) {
1573 if (RecognizeAndSimplifyClassCheck(condition)) {
1574 return;
1575 }
1576 }
1577
Anton Shaminbdd79352016-02-15 12:48:36 +06001578 // Reverse condition if left is constant. Our code generators prefer constant
1579 // on the right hand side.
1580 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1581 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001582 HCondition* replacement =
1583 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001584 // If it is a fp we must set the opposite bias.
1585 if (replacement != nullptr) {
1586 if (condition->IsLtBias()) {
1587 replacement->SetBias(ComparisonBias::kGtBias);
1588 } else if (condition->IsGtBias()) {
1589 replacement->SetBias(ComparisonBias::kLtBias);
1590 }
1591 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1592 RecordSimplification();
1593
1594 condition = replacement;
1595 }
1596 }
Mark Mendellc4701932015-04-10 13:18:51 -04001597
Mark Mendellc4701932015-04-10 13:18:51 -04001598 HInstruction* left = condition->GetLeft();
1599 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001600
1601 // Try to fold an HCompare into this HCondition.
1602
Mark Mendellc4701932015-04-10 13:18:51 -04001603 // We can only replace an HCondition which compares a Compare to 0.
1604 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1605 // condition with a long, float or double comparison as input.
1606 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1607 // Conversion is not possible.
1608 return;
1609 }
1610
1611 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001612 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001613 // Someone else also wants the result of the compare.
1614 return;
1615 }
1616
Vladimir Marko46817b82016-03-29 12:21:58 +01001617 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001618 // There is a reference to the compare result in an environment. Do we really need it?
1619 if (GetGraph()->IsDebuggable()) {
1620 return;
1621 }
1622
1623 // We have to ensure that there are no deopt points in the sequence.
1624 if (left->HasAnyEnvironmentUseBefore(condition)) {
1625 return;
1626 }
1627 }
1628
1629 // Clean up any environment uses from the HCompare, if any.
1630 left->RemoveEnvironmentUsers();
1631
1632 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1633 condition->SetBias(left->AsCompare()->GetBias());
1634
1635 // Replace the operands of the HCondition.
1636 condition->ReplaceInput(left->InputAt(0), 0);
1637 condition->ReplaceInput(left->InputAt(1), 1);
1638
1639 // Remove the HCompare.
1640 left->GetBlock()->RemoveInstruction(left);
1641
1642 RecordSimplification();
1643}
1644
Andreas Gampe9186ced2016-12-12 14:28:21 -08001645// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1646static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1647 // True, if the most significant bits of divisor are 0.
1648 return ((divisor & 0x7fffff) == 0);
1649}
1650
1651// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1652static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1653 // True, if the most significant bits of divisor are 0.
1654 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1655}
1656
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001657void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1658 HConstant* input_cst = instruction->GetConstantRight();
1659 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001660 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001661
1662 if ((input_cst != nullptr) && input_cst->IsOne()) {
1663 // Replace code looking like
1664 // DIV dst, src, 1
1665 // with
1666 // src
1667 instruction->ReplaceWith(input_other);
1668 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001669 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001670 return;
1671 }
1672
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001673 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001674 // Replace code looking like
1675 // DIV dst, src, -1
1676 // with
1677 // NEG dst, src
1678 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001679 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001680 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001681 return;
1682 }
1683
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001684 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001685 // Try replacing code looking like
1686 // DIV dst, src, constant
1687 // with
1688 // MUL dst, src, 1 / constant
1689 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001690 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001691 double value = input_cst->AsDoubleConstant()->GetValue();
1692 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1693 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1694 }
1695 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001696 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001697 float value = input_cst->AsFloatConstant()->GetValue();
1698 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1699 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1700 }
1701 }
1702
1703 if (reciprocal != nullptr) {
1704 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001705 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001706 RecordSimplification();
1707 return;
1708 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001709 }
1710}
1711
1712void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1713 HConstant* input_cst = instruction->GetConstantRight();
1714 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001715 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001716 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001717 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001718
1719 if (input_cst == nullptr) {
1720 return;
1721 }
1722
1723 if (input_cst->IsOne()) {
1724 // Replace code looking like
1725 // MUL dst, src, 1
1726 // with
1727 // src
1728 instruction->ReplaceWith(input_other);
1729 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001730 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001731 return;
1732 }
1733
1734 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001735 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001736 // Replace code looking like
1737 // MUL dst, src, -1
1738 // with
1739 // NEG dst, src
1740 HNeg* neg = new (allocator) HNeg(type, input_other);
1741 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001742 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001743 return;
1744 }
1745
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001746 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001747 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1748 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1749 // Replace code looking like
1750 // FP_MUL dst, src, 2.0
1751 // with
1752 // FP_ADD dst, src, src
1753 // The 'int' and 'long' cases are handled below.
1754 block->ReplaceAndRemoveInstructionWith(instruction,
1755 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001756 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001757 return;
1758 }
1759
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001760 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001761 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001762 // Even though constant propagation also takes care of the zero case, other
1763 // optimizations can lead to having a zero multiplication.
1764 if (factor == 0) {
1765 // Replace code looking like
1766 // MUL dst, src, 0
1767 // with
1768 // 0
1769 instruction->ReplaceWith(input_cst);
1770 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001771 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001772 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001773 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001774 // Replace code looking like
1775 // MUL dst, src, pow_of_2
1776 // with
1777 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001778 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001779 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001780 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001781 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001782 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001783 } else if (IsPowerOfTwo(factor - 1)) {
1784 // Transform code looking like
1785 // MUL dst, src, (2^n + 1)
1786 // into
1787 // SHL tmp, src, n
1788 // ADD dst, src, tmp
1789 HShl* shl = new (allocator) HShl(type,
1790 input_other,
1791 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1792 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1793
1794 block->InsertInstructionBefore(shl, instruction);
1795 block->ReplaceAndRemoveInstructionWith(instruction, add);
1796 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001797 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001798 } else if (IsPowerOfTwo(factor + 1)) {
1799 // Transform code looking like
1800 // MUL dst, src, (2^n - 1)
1801 // into
1802 // SHL tmp, src, n
1803 // SUB dst, tmp, src
1804 HShl* shl = new (allocator) HShl(type,
1805 input_other,
1806 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1807 HSub* sub = new (allocator) HSub(type, shl, input_other);
1808
1809 block->InsertInstructionBefore(shl, instruction);
1810 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1811 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001812 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001813 }
1814 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001815
1816 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1817 // so no need to return.
1818 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001819}
1820
Alexandre Rames188d4312015-04-09 18:30:21 +01001821void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1822 HInstruction* input = instruction->GetInput();
1823 if (input->IsNeg()) {
1824 // Replace code looking like
1825 // NEG tmp, src
1826 // NEG dst, tmp
1827 // with
1828 // src
1829 HNeg* previous_neg = input->AsNeg();
1830 instruction->ReplaceWith(previous_neg->GetInput());
1831 instruction->GetBlock()->RemoveInstruction(instruction);
1832 // We perform the optimization even if the input negation has environment
1833 // uses since it allows removing the current instruction. But we only delete
1834 // the input negation only if it is does not have any uses left.
1835 if (!previous_neg->HasUses()) {
1836 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1837 }
1838 RecordSimplification();
1839 return;
1840 }
1841
Serguei Katkov339dfc22015-04-20 12:29:32 +06001842 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001843 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001844 // Replace code looking like
1845 // SUB tmp, a, b
1846 // NEG dst, tmp
1847 // with
1848 // SUB dst, b, a
1849 // We do not perform the optimization if the input subtraction has
1850 // environment uses or multiple non-environment uses as it could lead to
1851 // worse code. In particular, we do not want the live ranges of `a` and `b`
1852 // to be extended if we are not sure the initial 'SUB' instruction can be
1853 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001854 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001855 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001856 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1857 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001858 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1859 if (!sub->HasUses()) {
1860 sub->GetBlock()->RemoveInstruction(sub);
1861 }
1862 RecordSimplification();
1863 }
1864}
1865
1866void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1867 HInstruction* input = instruction->GetInput();
1868 if (input->IsNot()) {
1869 // Replace code looking like
1870 // NOT tmp, src
1871 // NOT dst, tmp
1872 // with
1873 // src
1874 // We perform the optimization even if the input negation has environment
1875 // uses since it allows removing the current instruction. But we only delete
1876 // the input negation only if it is does not have any uses left.
1877 HNot* previous_not = input->AsNot();
1878 instruction->ReplaceWith(previous_not->GetInput());
1879 instruction->GetBlock()->RemoveInstruction(instruction);
1880 if (!previous_not->HasUses()) {
1881 previous_not->GetBlock()->RemoveInstruction(previous_not);
1882 }
1883 RecordSimplification();
1884 }
1885}
1886
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001887void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1888 HConstant* input_cst = instruction->GetConstantRight();
1889 HInstruction* input_other = instruction->GetLeastConstantLeft();
1890
Roland Levillain1a653882016-03-18 18:05:57 +00001891 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001892 // Replace code looking like
1893 // OR dst, src, 0
1894 // with
1895 // src
1896 instruction->ReplaceWith(input_other);
1897 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001898 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001899 return;
1900 }
1901
1902 // We assume that GVN has run before, so we only perform a pointer comparison.
1903 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001904 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001905 if (instruction->GetLeft() == instruction->GetRight()) {
1906 // Replace code looking like
1907 // OR dst, src, src
1908 // with
1909 // src
1910 instruction->ReplaceWith(instruction->GetLeft());
1911 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001912 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001913 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001914 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001915
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001916 if (TryDeMorganNegationFactoring(instruction)) return;
1917
Anton Kirilove14dc862016-05-13 17:56:15 +01001918 if (TryReplaceWithRotate(instruction)) {
1919 return;
1920 }
1921
1922 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1923 // so no need to return.
1924 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001925}
1926
1927void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1928 VisitShift(instruction);
1929}
1930
1931void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1932 VisitShift(instruction);
1933}
1934
1935void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1936 HConstant* input_cst = instruction->GetConstantRight();
1937 HInstruction* input_other = instruction->GetLeastConstantLeft();
1938
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001939 DataType::Type type = instruction->GetType();
1940 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001941 return;
1942 }
1943
Roland Levillain1a653882016-03-18 18:05:57 +00001944 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001945 // Replace code looking like
1946 // SUB dst, src, 0
1947 // with
1948 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001949 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1950 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1951 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001952 instruction->ReplaceWith(input_other);
1953 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001954 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001955 return;
1956 }
1957
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001958 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001959 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001960
Alexandre Rames188d4312015-04-09 18:30:21 +01001961 HInstruction* left = instruction->GetLeft();
1962 HInstruction* right = instruction->GetRight();
1963 if (left->IsConstant()) {
1964 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001965 // Replace code looking like
1966 // SUB dst, 0, src
1967 // with
1968 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001969 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001970 // `x` is `0.0`, the former expression yields `0.0`, while the later
1971 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001972 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001973 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001974 RecordSimplification();
1975 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001976 }
1977 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001978
1979 if (left->IsNeg() && right->IsNeg()) {
1980 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1981 return;
1982 }
1983 }
1984
1985 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1986 // Replace code looking like
1987 // NEG tmp, b
1988 // SUB dst, a, tmp
1989 // with
1990 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001991 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001992 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1993 RecordSimplification();
1994 right->GetBlock()->RemoveInstruction(right);
1995 return;
1996 }
1997
1998 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1999 // Replace code looking like
2000 // NEG tmp, a
2001 // SUB dst, tmp, b
2002 // with
2003 // ADD tmp, a, b
2004 // NEG dst, tmp
2005 // The second version is not intrinsically better, but enables more
2006 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002007 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002008 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002009 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002010 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2011 instruction->ReplaceWith(neg);
2012 instruction->GetBlock()->RemoveInstruction(instruction);
2013 RecordSimplification();
2014 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002015 return;
2016 }
2017
2018 if (TrySubtractionChainSimplification(instruction)) {
2019 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002020 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002021
2022 if (left->IsAdd()) {
2023 // Replace code patterns looking like
2024 // ADD dst1, x, y ADD dst1, x, y
2025 // SUB dst2, dst1, y SUB dst2, dst1, x
2026 // with
2027 // ADD dst1, x, y
2028 // SUB instruction is not needed in this case, we may use
2029 // one of inputs of ADD instead.
2030 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002031 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002032 if (left->InputAt(1) == right) {
2033 instruction->ReplaceWith(left->InputAt(0));
2034 RecordSimplification();
2035 instruction->GetBlock()->RemoveInstruction(instruction);
2036 return;
2037 } else if (left->InputAt(0) == right) {
2038 instruction->ReplaceWith(left->InputAt(1));
2039 RecordSimplification();
2040 instruction->GetBlock()->RemoveInstruction(instruction);
2041 return;
2042 }
2043 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002044}
2045
2046void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2047 VisitShift(instruction);
2048}
2049
2050void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2051 HConstant* input_cst = instruction->GetConstantRight();
2052 HInstruction* input_other = instruction->GetLeastConstantLeft();
2053
Roland Levillain1a653882016-03-18 18:05:57 +00002054 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002055 // Replace code looking like
2056 // XOR dst, src, 0
2057 // with
2058 // src
2059 instruction->ReplaceWith(input_other);
2060 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002061 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002062 return;
2063 }
2064
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002065 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002066 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002067 // Replace code looking like
2068 // XOR dst, src, 1
2069 // with
2070 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002071 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002072 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2073 RecordSimplification();
2074 return;
2075 }
2076
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002077 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2078 // Replace code looking like
2079 // XOR dst, src, 0xFFF...FF
2080 // with
2081 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002082 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002083 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002084 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002085 return;
2086 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002087
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002088 HInstruction* left = instruction->GetLeft();
2089 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002090 if (((left->IsNot() && right->IsNot()) ||
2091 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002092 left->HasOnlyOneNonEnvironmentUse() &&
2093 right->HasOnlyOneNonEnvironmentUse()) {
2094 // Replace code looking like
2095 // NOT nota, a
2096 // NOT notb, b
2097 // XOR dst, nota, notb
2098 // with
2099 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002100 instruction->ReplaceInput(left->InputAt(0), 0);
2101 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002102 left->GetBlock()->RemoveInstruction(left);
2103 right->GetBlock()->RemoveInstruction(right);
2104 RecordSimplification();
2105 return;
2106 }
2107
Anton Kirilove14dc862016-05-13 17:56:15 +01002108 if (TryReplaceWithRotate(instruction)) {
2109 return;
2110 }
2111
2112 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2113 // so no need to return.
2114 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002115}
2116
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002117void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2118 HInstruction* argument = instruction->InputAt(1);
2119 HInstruction* receiver = instruction->InputAt(0);
2120 if (receiver == argument) {
2121 // Because String.equals is an instance call, the receiver is
2122 // a null check if we don't know it's null. The argument however, will
2123 // be the actual object. So we cannot end up in a situation where both
2124 // are equal but could be null.
2125 DCHECK(CanEnsureNotNullAt(argument, instruction));
2126 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2127 instruction->GetBlock()->RemoveInstruction(instruction);
2128 } else {
2129 StringEqualsOptimizations optimizations(instruction);
2130 if (CanEnsureNotNullAt(argument, instruction)) {
2131 optimizations.SetArgumentNotNull();
2132 }
2133 ScopedObjectAccess soa(Thread::Current());
2134 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2135 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2136 optimizations.SetArgumentIsString();
2137 }
2138 }
2139}
2140
Roland Levillain22c49222016-03-18 14:04:28 +00002141void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2142 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002143 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002144 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002145 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002146 HInstruction* value = invoke->InputAt(0);
2147 HInstruction* distance = invoke->InputAt(1);
2148 // Replace the invoke with an HRor.
2149 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002150 // Unconditionally set the type of the negated distance to `int`,
2151 // as shift and rotate operations expect a 32-bit (or narrower)
2152 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002153 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002154 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2155 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002156 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002157 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2158 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002159 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002160 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2161 clinit->GetBlock()->RemoveInstruction(clinit);
2162 HInstruction* ldclass = clinit->InputAt(0);
2163 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2164 ldclass->GetBlock()->RemoveInstruction(ldclass);
2165 }
2166 }
2167}
2168
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002169static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2170 if (potential_length->IsArrayLength()) {
2171 return potential_length->InputAt(0) == potential_array;
2172 }
2173
2174 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002175 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002176 }
2177
2178 return false;
2179}
2180
2181void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2182 HInstruction* source = instruction->InputAt(0);
2183 HInstruction* destination = instruction->InputAt(2);
2184 HInstruction* count = instruction->InputAt(4);
2185 SystemArrayCopyOptimizations optimizations(instruction);
2186 if (CanEnsureNotNullAt(source, instruction)) {
2187 optimizations.SetSourceIsNotNull();
2188 }
2189 if (CanEnsureNotNullAt(destination, instruction)) {
2190 optimizations.SetDestinationIsNotNull();
2191 }
2192 if (destination == source) {
2193 optimizations.SetDestinationIsSource();
2194 }
2195
2196 if (IsArrayLengthOf(count, source)) {
2197 optimizations.SetCountIsSourceLength();
2198 }
2199
2200 if (IsArrayLengthOf(count, destination)) {
2201 optimizations.SetCountIsDestinationLength();
2202 }
2203
2204 {
2205 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002206 DataType::Type source_component_type = DataType::Type::kVoid;
2207 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002208 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2209 if (destination_rti.IsValid()) {
2210 if (destination_rti.IsObjectArray()) {
2211 if (destination_rti.IsExact()) {
2212 optimizations.SetDoesNotNeedTypeCheck();
2213 }
2214 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002215 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002216 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002217 destination_component_type = DataTypeFromPrimitive(
2218 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002219 optimizations.SetDestinationIsPrimitiveArray();
2220 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2221 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002222 }
2223 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002224 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2225 if (source_rti.IsValid()) {
2226 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2227 optimizations.SetDoesNotNeedTypeCheck();
2228 }
2229 if (source_rti.IsPrimitiveArrayClass()) {
2230 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002231 source_component_type = DataTypeFromPrimitive(
2232 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002233 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2234 optimizations.SetSourceIsNonPrimitiveArray();
2235 }
2236 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002237 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002238 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002239 (source_component_type == destination_component_type)) {
2240 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2241 PointerSize image_size = class_linker->GetImagePointerSize();
2242 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
Vladimir Markod93e3742018-07-18 10:58:13 +01002243 ObjPtr<mirror::Class> system = invoke->GetResolvedMethod()->GetDeclaringClass();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002244 ArtMethod* method = nullptr;
2245 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002246 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002247 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002248 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002249 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002250 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002251 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002252 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002253 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002254 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002255 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002256 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002257 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002258 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002259 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002260 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002261 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002262 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002263 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002264 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002265 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002266 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002267 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002268 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002269 break;
2270 default:
2271 LOG(FATAL) << "Unreachable";
2272 }
2273 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002274 DCHECK(method->IsStatic());
2275 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002276 invoke->SetResolvedMethod(method);
2277 // Sharpen the new invoke. Note that we do not update the dex method index of
2278 // the invoke, as we would need to look it up in the current dex file, and it
2279 // is unlikely that it exists. The most usual situation for such typed
2280 // arraycopy methods is a direct pointer to the boot image.
Nicolas Geoffraybdb2ecc2018-09-18 14:33:55 +01002281 invoke->SetDispatchInfo(HSharpening::SharpenInvokeStaticOrDirect(method, codegen_));
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002282 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002283 }
2284}
2285
Roland Levillaina5c4a402016-03-15 15:02:50 +00002286void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2287 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002288 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002289 DCHECK(invoke->IsInvokeStaticOrDirect());
2290 uint32_t dex_pc = invoke->GetDexPc();
2291 HInstruction* left = invoke->InputAt(0);
2292 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002293 if (!is_signum) {
2294 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002295 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002296 right = GetGraph()->GetLongConstant(0);
2297 } else {
2298 right = GetGraph()->GetIntConstant(0);
2299 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002300 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002301 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2302 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2303}
2304
Aart Bik75a38b22016-02-17 10:41:50 -08002305void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2306 DCHECK(invoke->IsInvokeStaticOrDirect());
2307 uint32_t dex_pc = invoke->GetDexPc();
2308 // IsNaN(x) is the same as x != x.
2309 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002310 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002311 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002312 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2313}
2314
Aart Bik2a6aad92016-02-25 11:32:32 -08002315void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2316 DCHECK(invoke->IsInvokeStaticOrDirect());
2317 uint32_t dex_pc = invoke->GetDexPc();
2318 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002319 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002320 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2321 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002322 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002323 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2324 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2325 kNeedsEnvironmentOrCache,
2326 kNoSideEffects,
2327 kNoThrow);
2328 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002329 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002330 nan = GetGraph()->GetIntConstant(0x7fc00000);
2331 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2332 kNeedsEnvironmentOrCache,
2333 kNoSideEffects,
2334 kNoThrow);
2335 }
2336 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002337 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002338 condition->SetBias(ComparisonBias::kLtBias);
2339 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2340 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002341 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002342 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2343 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2344}
2345
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002346void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2347 HInstruction* str = invoke->InputAt(0);
2348 HInstruction* index = invoke->InputAt(1);
2349 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002350 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002351 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2352 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Andreas Gampe3db70682018-12-26 15:12:03 -08002353 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002354 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002355 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Andreas Gampe3db70682018-12-26 15:12:03 -08002356 index, length, dex_pc, /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002357 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002358 HArrayGet* array_get = new (allocator) HArrayGet(str,
2359 bounds_check,
2360 DataType::Type::kUint16,
2361 SideEffects::None(), // Strings are immutable.
2362 dex_pc,
Andreas Gampe3db70682018-12-26 15:12:03 -08002363 /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002364 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2365 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2366 GetGraph()->SetHasBoundsChecks(true);
2367}
2368
Vladimir Markodce016e2016-04-28 13:10:02 +01002369void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2370 HInstruction* str = invoke->InputAt(0);
2371 uint32_t dex_pc = invoke->GetDexPc();
2372 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2373 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002374 HArrayLength* length =
Andreas Gampe3db70682018-12-26 15:12:03 -08002375 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002376 HInstruction* replacement;
2377 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2378 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2379 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2380 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002381 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002382 replacement = equal;
2383 } else {
2384 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2385 replacement = length;
2386 }
2387 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2388}
2389
Vladimir Marko6fa44042018-03-19 18:42:49 +00002390void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2391 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2392 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2393 if (invoke->InputAt(0)->IsLoadString()) {
2394 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
2395 const DexFile& dex_file = load_string->GetDexFile();
2396 uint32_t utf16_length;
2397 const char* data =
2398 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2399 if (utf16_length == 0) {
2400 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2401 invoke->GetBlock()->RemoveInstruction(invoke);
2402 RecordSimplification();
2403 return;
2404 }
2405 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2406 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2407 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2408 uint32_t c = GetUtf16FromUtf8(&data);
2409 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2410 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2411 uint32_t dex_pc = invoke->GetDexPc();
2412 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2413 HEqual* equal =
2414 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2415 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2416 HSelect* result = new (allocator) HSelect(equal,
2417 GetGraph()->GetIntConstant(0),
2418 GetGraph()->GetIntConstant(-1),
2419 dex_pc);
2420 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2421 RecordSimplification();
2422 return;
2423 }
2424 }
2425}
2426
Aart Bikff7d89c2016-11-07 08:49:28 -08002427// This method should only be used on intrinsics whose sole way of throwing an
2428// exception is raising a NPE when the nth argument is null. If that argument
2429// is provably non-null, we can clear the flag.
2430void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2431 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002432 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002433 invoke->SetCanThrow(false);
2434 }
2435}
2436
Aart Bik71bf7b42016-11-16 10:17:46 -08002437// Methods that return "this" can replace the returned value with the receiver.
2438void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2439 if (invoke->HasUses()) {
2440 HInstruction* receiver = invoke->InputAt(0);
2441 invoke->ReplaceWith(receiver);
2442 RecordSimplification();
2443 }
2444}
2445
2446// Helper method for StringBuffer escape analysis.
2447static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2448 if (user->IsInvokeStaticOrDirect()) {
2449 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002450 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2451 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002452 user->InputAt(0) == reference;
2453 } else if (user->IsInvokeVirtual()) {
2454 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2455 case Intrinsics::kStringBufferLength:
2456 case Intrinsics::kStringBufferToString:
2457 DCHECK_EQ(user->InputAt(0), reference);
2458 return true;
2459 case Intrinsics::kStringBufferAppend:
2460 // Returns "this", so only okay if no further uses.
2461 DCHECK_EQ(user->InputAt(0), reference);
2462 DCHECK_NE(user->InputAt(1), reference);
2463 return !user->HasUses();
2464 default:
2465 break;
2466 }
2467 }
2468 return false;
2469}
2470
Vladimir Marko552a1342017-10-31 10:56:47 +00002471static bool TryReplaceStringBuilderAppend(HInvoke* invoke) {
2472 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringBuilderToString);
2473 if (invoke->CanThrowIntoCatchBlock()) {
2474 return false;
2475 }
2476
2477 HBasicBlock* block = invoke->GetBlock();
2478 HInstruction* sb = invoke->InputAt(0);
2479
2480 // We support only a new StringBuilder, otherwise we cannot ensure that
2481 // the StringBuilder data does not need to be populated for other users.
2482 if (!sb->IsNewInstance()) {
2483 return false;
2484 }
2485
2486 // For now, we support only single-block recognition.
2487 // (Ternary operators feeding the append could be implemented.)
2488 for (const HUseListNode<HInstruction*>& use : sb->GetUses()) {
2489 if (use.GetUser()->GetBlock() != block) {
2490 return false;
2491 }
2492 }
2493
2494 // Collect args and check for unexpected uses.
2495 // We expect one call to a constructor with no arguments, one constructor fence (unless
2496 // eliminated), some number of append calls and one call to StringBuilder.toString().
2497 bool seen_constructor = false;
2498 bool seen_constructor_fence = false;
2499 bool seen_to_string = false;
2500 uint32_t format = 0u;
2501 uint32_t num_args = 0u;
2502 HInstruction* args[StringBuilderAppend::kMaxArgs]; // Added in reverse order.
2503 for (const HUseListNode<HInstruction*>& use : sb->GetUses()) {
2504 // The append pattern uses the StringBuilder only as the first argument.
2505 if (use.GetIndex() != 0u) {
2506 return false;
2507 }
2508 // We see the uses in reverse order because they are inserted at the front
2509 // of the singly-linked list, so the StringBuilder.append() must come first.
2510 HInstruction* user = use.GetUser();
2511 if (!seen_to_string) {
2512 if (user->IsInvokeVirtual() &&
2513 user->AsInvokeVirtual()->GetIntrinsic() == Intrinsics::kStringBuilderToString) {
2514 seen_to_string = true;
2515 continue;
2516 } else {
2517 return false;
2518 }
2519 }
2520 // Then we should see the arguments.
2521 if (user->IsInvokeVirtual()) {
2522 HInvokeVirtual* as_invoke_virtual = user->AsInvokeVirtual();
2523 DCHECK(!seen_constructor);
2524 DCHECK(!seen_constructor_fence);
2525 StringBuilderAppend::Argument arg;
2526 switch (as_invoke_virtual->GetIntrinsic()) {
2527 case Intrinsics::kStringBuilderAppendObject:
2528 // TODO: Unimplemented, needs to call String.valueOf().
2529 return false;
2530 case Intrinsics::kStringBuilderAppendString:
2531 arg = StringBuilderAppend::Argument::kString;
2532 break;
2533 case Intrinsics::kStringBuilderAppendCharArray:
2534 // TODO: Unimplemented, StringBuilder.append(char[]) can throw NPE and we would
2535 // not have the correct stack trace for it.
2536 return false;
2537 case Intrinsics::kStringBuilderAppendBoolean:
2538 arg = StringBuilderAppend::Argument::kBoolean;
2539 break;
2540 case Intrinsics::kStringBuilderAppendChar:
2541 arg = StringBuilderAppend::Argument::kChar;
2542 break;
2543 case Intrinsics::kStringBuilderAppendInt:
2544 arg = StringBuilderAppend::Argument::kInt;
2545 break;
2546 case Intrinsics::kStringBuilderAppendLong:
2547 arg = StringBuilderAppend::Argument::kLong;
2548 break;
2549 case Intrinsics::kStringBuilderAppendCharSequence: {
2550 ReferenceTypeInfo rti = user->AsInvokeVirtual()->InputAt(1)->GetReferenceTypeInfo();
2551 if (!rti.IsValid()) {
2552 return false;
2553 }
2554 ScopedObjectAccess soa(Thread::Current());
2555 Handle<mirror::Class> input_type = rti.GetTypeHandle();
2556 DCHECK(input_type != nullptr);
2557 if (input_type.Get() == GetClassRoot<mirror::String>()) {
2558 arg = StringBuilderAppend::Argument::kString;
2559 } else {
2560 // TODO: Check and implement for StringBuilder. We could find the StringBuilder's
2561 // internal char[] inconsistent with the length, or the string compression
2562 // of the result could be compromised with a concurrent modification, and
2563 // we would need to throw appropriate exceptions.
2564 return false;
2565 }
2566 break;
2567 }
2568 case Intrinsics::kStringBuilderAppendFloat:
2569 case Intrinsics::kStringBuilderAppendDouble:
2570 // TODO: Unimplemented, needs to call FloatingDecimal.getBinaryToASCIIConverter().
2571 return false;
2572 default: {
2573 return false;
2574 }
2575 }
2576 // Uses of the append return value should have been replaced with the first input.
2577 DCHECK(!as_invoke_virtual->HasUses());
2578 DCHECK(!as_invoke_virtual->HasEnvironmentUses());
2579 if (num_args == StringBuilderAppend::kMaxArgs) {
2580 return false;
2581 }
2582 format = (format << StringBuilderAppend::kBitsPerArg) | static_cast<uint32_t>(arg);
2583 args[num_args] = as_invoke_virtual->InputAt(1u);
2584 ++num_args;
2585 } else if (user->IsInvokeStaticOrDirect() &&
2586 user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2587 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
2588 user->AsInvokeStaticOrDirect()->GetNumberOfArguments() == 1u) {
2589 // After arguments, we should see the constructor.
2590 // We accept only the constructor with no extra arguments.
2591 DCHECK(!seen_constructor);
2592 DCHECK(!seen_constructor_fence);
2593 seen_constructor = true;
2594 } else if (user->IsConstructorFence()) {
2595 // The last use we see is the constructor fence.
2596 DCHECK(seen_constructor);
2597 DCHECK(!seen_constructor_fence);
2598 seen_constructor_fence = true;
2599 } else {
2600 return false;
2601 }
2602 }
2603
2604 if (num_args == 0u) {
2605 return false;
2606 }
2607
2608 // Check environment uses.
2609 for (const HUseListNode<HEnvironment*>& use : sb->GetEnvUses()) {
2610 HInstruction* holder = use.GetUser()->GetHolder();
2611 if (holder->GetBlock() != block) {
2612 return false;
2613 }
2614 // Accept only calls on the StringBuilder (which shall all be removed).
2615 // TODO: Carve-out for const-string? Or rely on environment pruning (to be implemented)?
2616 if (holder->InputCount() == 0 || holder->InputAt(0) != sb) {
2617 return false;
2618 }
2619 }
2620
2621 // Create replacement instruction.
2622 HIntConstant* fmt = block->GetGraph()->GetIntConstant(static_cast<int32_t>(format));
2623 ArenaAllocator* allocator = block->GetGraph()->GetAllocator();
2624 HStringBuilderAppend* append =
2625 new (allocator) HStringBuilderAppend(fmt, num_args, allocator, invoke->GetDexPc());
2626 append->SetReferenceTypeInfo(invoke->GetReferenceTypeInfo());
2627 for (size_t i = 0; i != num_args; ++i) {
2628 append->SetArgumentAt(i, args[num_args - 1u - i]);
2629 }
2630 block->InsertInstructionBefore(append, invoke);
2631 invoke->ReplaceWith(append);
2632 // Copy environment, except for the StringBuilder uses.
2633 for (size_t i = 0, size = invoke->GetEnvironment()->Size(); i != size; ++i) {
2634 if (invoke->GetEnvironment()->GetInstructionAt(i) == sb) {
2635 invoke->GetEnvironment()->RemoveAsUserOfInput(i);
2636 invoke->GetEnvironment()->SetRawEnvAt(i, nullptr);
2637 }
2638 }
2639 append->CopyEnvironmentFrom(invoke->GetEnvironment());
2640 // Remove the old instruction.
2641 block->RemoveInstruction(invoke);
2642 // Remove the StringBuilder's uses and StringBuilder.
2643 while (sb->HasNonEnvironmentUses()) {
2644 block->RemoveInstruction(sb->GetUses().front().GetUser());
2645 }
2646 DCHECK(!sb->HasEnvironmentUses());
2647 block->RemoveInstruction(sb);
2648 return true;
2649}
2650
Aart Bik71bf7b42016-11-16 10:17:46 -08002651// Certain allocation intrinsics are not removed by dead code elimination
2652// because of potentially throwing an OOM exception or other side effects.
2653// This method removes such intrinsics when special circumstances allow.
2654void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2655 if (!invoke->HasUses()) {
2656 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2657 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2658 // call does not escape since only thread-local synchronization may be removed.
2659 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2660 HInstruction* receiver = invoke->InputAt(0);
2661 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2662 invoke->GetBlock()->RemoveInstruction(invoke);
2663 RecordSimplification();
2664 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002665 } else if (invoke->GetIntrinsic() == Intrinsics::kStringBuilderToString &&
2666 TryReplaceStringBuilderAppend(invoke)) {
2667 RecordSimplification();
Aart Bik71bf7b42016-11-16 10:17:46 -08002668 }
2669}
2670
Vladimir Markoca6fff82017-10-03 14:49:14 +01002671void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2672 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002673 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002674 HMemoryBarrier* mem_barrier =
2675 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002676 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2677}
2678
Aart Bik1f8d51b2018-02-15 10:42:37 -08002679void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2680 DCHECK(invoke->IsInvokeStaticOrDirect());
2681 HMin* min = new (GetGraph()->GetAllocator())
2682 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2683 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2684}
2685
2686void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2687 DCHECK(invoke->IsInvokeStaticOrDirect());
2688 HMax* max = new (GetGraph()->GetAllocator())
2689 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2690 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2691}
2692
Aart Bik3dad3412018-02-28 12:01:46 -08002693void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2694 DCHECK(invoke->IsInvokeStaticOrDirect());
2695 HAbs* abs = new (GetGraph()->GetAllocator())
2696 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2697 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2698}
2699
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002700void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002701 switch (instruction->GetIntrinsic()) {
2702 case Intrinsics::kStringEquals:
2703 SimplifyStringEquals(instruction);
2704 break;
2705 case Intrinsics::kSystemArrayCopy:
2706 SimplifySystemArrayCopy(instruction);
2707 break;
2708 case Intrinsics::kIntegerRotateRight:
Andreas Gampe3db70682018-12-26 15:12:03 -08002709 SimplifyRotate(instruction, /* is_left= */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002710 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002711 case Intrinsics::kLongRotateRight:
Andreas Gampe3db70682018-12-26 15:12:03 -08002712 SimplifyRotate(instruction, /* is_left= */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002713 break;
2714 case Intrinsics::kIntegerRotateLeft:
Andreas Gampe3db70682018-12-26 15:12:03 -08002715 SimplifyRotate(instruction, /* is_left= */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002716 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002717 case Intrinsics::kLongRotateLeft:
Andreas Gampe3db70682018-12-26 15:12:03 -08002718 SimplifyRotate(instruction, /* is_left= */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002719 break;
2720 case Intrinsics::kIntegerCompare:
Andreas Gampe3db70682018-12-26 15:12:03 -08002721 SimplifyCompare(instruction, /* is_signum= */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002722 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002723 case Intrinsics::kLongCompare:
Andreas Gampe3db70682018-12-26 15:12:03 -08002724 SimplifyCompare(instruction, /* is_signum= */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002725 break;
2726 case Intrinsics::kIntegerSignum:
Andreas Gampe3db70682018-12-26 15:12:03 -08002727 SimplifyCompare(instruction, /* is_signum= */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002728 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002729 case Intrinsics::kLongSignum:
Andreas Gampe3db70682018-12-26 15:12:03 -08002730 SimplifyCompare(instruction, /* is_signum= */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002731 break;
2732 case Intrinsics::kFloatIsNaN:
2733 case Intrinsics::kDoubleIsNaN:
2734 SimplifyIsNaN(instruction);
2735 break;
2736 case Intrinsics::kFloatFloatToIntBits:
2737 case Intrinsics::kDoubleDoubleToLongBits:
2738 SimplifyFP2Int(instruction);
2739 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002740 case Intrinsics::kStringCharAt:
2741 SimplifyStringCharAt(instruction);
2742 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002743 case Intrinsics::kStringIsEmpty:
2744 case Intrinsics::kStringLength:
2745 SimplifyStringIsEmptyOrLength(instruction);
2746 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00002747 case Intrinsics::kStringIndexOf:
2748 case Intrinsics::kStringIndexOfAfter:
2749 SimplifyStringIndexOf(instruction);
2750 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002751 case Intrinsics::kStringStringIndexOf:
2752 case Intrinsics::kStringStringIndexOfAfter:
2753 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2754 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002755 case Intrinsics::kStringBufferAppend:
Vladimir Markod4561172017-10-30 17:48:25 +00002756 case Intrinsics::kStringBuilderAppendObject:
2757 case Intrinsics::kStringBuilderAppendString:
2758 case Intrinsics::kStringBuilderAppendCharSequence:
2759 case Intrinsics::kStringBuilderAppendCharArray:
2760 case Intrinsics::kStringBuilderAppendBoolean:
2761 case Intrinsics::kStringBuilderAppendChar:
2762 case Intrinsics::kStringBuilderAppendInt:
2763 case Intrinsics::kStringBuilderAppendLong:
2764 case Intrinsics::kStringBuilderAppendFloat:
2765 case Intrinsics::kStringBuilderAppendDouble:
Aart Bik71bf7b42016-11-16 10:17:46 -08002766 SimplifyReturnThis(instruction);
2767 break;
2768 case Intrinsics::kStringBufferToString:
2769 case Intrinsics::kStringBuilderToString:
2770 SimplifyAllocationIntrinsic(instruction);
2771 break;
Aart Bik11932592016-03-08 12:42:25 -08002772 case Intrinsics::kUnsafeLoadFence:
2773 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2774 break;
2775 case Intrinsics::kUnsafeStoreFence:
2776 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2777 break;
2778 case Intrinsics::kUnsafeFullFence:
2779 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2780 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002781 case Intrinsics::kVarHandleFullFence:
2782 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2783 break;
2784 case Intrinsics::kVarHandleAcquireFence:
2785 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2786 break;
2787 case Intrinsics::kVarHandleReleaseFence:
2788 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2789 break;
2790 case Intrinsics::kVarHandleLoadLoadFence:
2791 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2792 break;
2793 case Intrinsics::kVarHandleStoreStoreFence:
2794 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2795 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002796 case Intrinsics::kMathMinIntInt:
2797 SimplifyMin(instruction, DataType::Type::kInt32);
2798 break;
2799 case Intrinsics::kMathMinLongLong:
2800 SimplifyMin(instruction, DataType::Type::kInt64);
2801 break;
2802 case Intrinsics::kMathMinFloatFloat:
2803 SimplifyMin(instruction, DataType::Type::kFloat32);
2804 break;
2805 case Intrinsics::kMathMinDoubleDouble:
2806 SimplifyMin(instruction, DataType::Type::kFloat64);
2807 break;
2808 case Intrinsics::kMathMaxIntInt:
2809 SimplifyMax(instruction, DataType::Type::kInt32);
2810 break;
2811 case Intrinsics::kMathMaxLongLong:
2812 SimplifyMax(instruction, DataType::Type::kInt64);
2813 break;
2814 case Intrinsics::kMathMaxFloatFloat:
2815 SimplifyMax(instruction, DataType::Type::kFloat32);
2816 break;
2817 case Intrinsics::kMathMaxDoubleDouble:
2818 SimplifyMax(instruction, DataType::Type::kFloat64);
2819 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002820 case Intrinsics::kMathAbsInt:
2821 SimplifyAbs(instruction, DataType::Type::kInt32);
2822 break;
2823 case Intrinsics::kMathAbsLong:
2824 SimplifyAbs(instruction, DataType::Type::kInt64);
2825 break;
2826 case Intrinsics::kMathAbsFloat:
2827 SimplifyAbs(instruction, DataType::Type::kFloat32);
2828 break;
2829 case Intrinsics::kMathAbsDouble:
2830 SimplifyAbs(instruction, DataType::Type::kFloat64);
2831 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002832 default:
2833 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002834 }
2835}
2836
Aart Bikbb245d12015-10-19 11:05:03 -07002837void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2838 HInstruction* cond = deoptimize->InputAt(0);
2839 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002840 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002841 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002842 if (deoptimize->GuardsAnInput()) {
2843 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2844 }
Aart Bikbb245d12015-10-19 11:05:03 -07002845 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2846 } else {
2847 // Always deopt.
2848 }
2849 }
2850}
2851
Anton Kirilove14dc862016-05-13 17:56:15 +01002852// Replace code looking like
2853// OP y, x, const1
2854// OP z, y, const2
2855// with
2856// OP z, x, const3
2857// where OP is both an associative and a commutative operation.
2858bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2859 HBinaryOperation* instruction) {
2860 DCHECK(instruction->IsCommutative());
2861
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002862 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002863 return false;
2864 }
2865
2866 HInstruction* left = instruction->GetLeft();
2867 HInstruction* right = instruction->GetRight();
2868 // Variable names as described above.
2869 HConstant* const2;
2870 HBinaryOperation* y;
2871
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002872 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002873 const2 = right->AsConstant();
2874 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002875 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002876 const2 = left->AsConstant();
2877 y = right->AsBinaryOperation();
2878 } else {
2879 // The node does not match the pattern.
2880 return false;
2881 }
2882
2883 // If `y` has more than one use, we do not perform the optimization
2884 // because it might increase code size (e.g. if the new constant is
2885 // no longer encodable as an immediate operand in the target ISA).
2886 if (!y->HasOnlyOneNonEnvironmentUse()) {
2887 return false;
2888 }
2889
2890 // GetConstantRight() can return both left and right constants
2891 // for commutative operations.
2892 HConstant* const1 = y->GetConstantRight();
2893 if (const1 == nullptr) {
2894 return false;
2895 }
2896
2897 instruction->ReplaceInput(const1, 0);
2898 instruction->ReplaceInput(const2, 1);
2899 HConstant* const3 = instruction->TryStaticEvaluation();
2900 DCHECK(const3 != nullptr);
2901 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2902 instruction->ReplaceInput(const3, 1);
2903 RecordSimplification();
2904 return true;
2905}
2906
2907static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2908 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2909}
2910
2911// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002912static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002913 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002914 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002915 return HAdd::Compute<int32_t>(x, y);
2916 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002917 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002918 return HAdd::Compute<int64_t>(x, y);
2919 }
2920}
2921
2922// Helper function that handles the child classes of HConstant
2923// and returns an integer with the appropriate sign.
2924static int64_t GetValue(HConstant* constant, bool is_negated) {
2925 int64_t ret = Int64FromConstant(constant);
2926 return is_negated ? -ret : ret;
2927}
2928
2929// Replace code looking like
2930// OP1 y, x, const1
2931// OP2 z, y, const2
2932// with
2933// OP3 z, x, const3
2934// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2935bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2936 HBinaryOperation* instruction) {
2937 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2938
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002939 DataType::Type type = instruction->GetType();
2940 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002941 return false;
2942 }
2943
2944 HInstruction* left = instruction->GetLeft();
2945 HInstruction* right = instruction->GetRight();
2946 // Variable names as described above.
2947 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2948 if (const2 == nullptr) {
2949 return false;
2950 }
2951
2952 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2953 ? left->AsBinaryOperation()
2954 : AsAddOrSub(right);
2955 // If y has more than one use, we do not perform the optimization because
2956 // it might increase code size (e.g. if the new constant is no longer
2957 // encodable as an immediate operand in the target ISA).
2958 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2959 return false;
2960 }
2961
2962 left = y->GetLeft();
2963 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2964 if (const1 == nullptr) {
2965 return false;
2966 }
2967
2968 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2969 // If both inputs are constants, let the constant folding pass deal with it.
2970 if (x->IsConstant()) {
2971 return false;
2972 }
2973
2974 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2975 int64_t const2_val = GetValue(const2, is_const2_negated);
2976 bool is_y_negated = (y == right) && instruction->IsSub();
2977 right = y->GetRight();
2978 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2979 int64_t const1_val = GetValue(const1, is_const1_negated);
2980 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2981 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2982 HBasicBlock* block = instruction->GetBlock();
2983 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002984 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002985 HInstruction* z;
2986
2987 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002988 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002989 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002990 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002991 }
2992
2993 block->ReplaceAndRemoveInstructionWith(instruction, z);
2994 RecordSimplification();
2995 return true;
2996}
2997
Lena Djokicbc5460b2017-07-20 16:07:36 +02002998void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2999 if (TryCombineVecMultiplyAccumulate(instruction)) {
3000 RecordSimplification();
3001 }
3002}
3003
Nicolas Geoffray3c049742014-09-24 18:10:46 +01003004} // namespace art