blob: c979a5a56c03ae3ddbc30314e0bbe6f42f3a8f4d [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Andreas Gampec6ea7d02017-02-01 16:46:28 -080019#include "art_method-inl.h"
20#include "class_linker-inl.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010021#include "class_root.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010022#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080023#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070026#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028
Nicolas Geoffray3c049742014-09-24 18:10:46 +010029namespace art {
30
Artem Serovcced8ba2017-07-19 18:18:09 +010031// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
32// is replaced with its copy if it is clonable.
33static constexpr bool kTestInstructionClonerExhaustively = false;
34
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010035class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000036 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 InstructionSimplifierVisitor(HGraph* graph,
38 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010039 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000040 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010041 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010043 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010044 stats_(stats) {}
45
Aart Bik24773202018-04-26 10:28:51 -070046 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000047
48 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010049 void RecordSimplification() {
50 simplification_occurred_ = true;
51 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000052 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010053 }
54
Scott Wakeling40a04bf2015-12-11 09:50:36 +000055 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
56 bool TryReplaceWithRotate(HBinaryOperation* instruction);
57 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
60
Alexandre Rames188d4312015-04-09 18:30:21 +010061 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000062 // `op` should be either HOr or HAnd.
63 // De Morgan's laws:
64 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
65 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010066 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
67 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020068 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010069
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000070 void VisitShift(HBinaryOperation* shift);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000071 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010072 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
73 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010074 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
75 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000076 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000077 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000078 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080079 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000080 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Aart Bikc6eec4b2018-03-29 17:22:00 -070081 void VisitAbs(HAbs* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000082 void VisitAdd(HAdd* instruction) OVERRIDE;
83 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040084 void VisitCondition(HCondition* instruction) OVERRIDE;
85 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
86 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
87 void VisitLessThan(HLessThan* condition) OVERRIDE;
88 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060089 void VisitBelow(HBelow* condition) OVERRIDE;
90 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
91 void VisitAbove(HAbove* condition) OVERRIDE;
92 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000093 void VisitDiv(HDiv* instruction) OVERRIDE;
94 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010095 void VisitNeg(HNeg* instruction) OVERRIDE;
96 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000097 void VisitOr(HOr* instruction) OVERRIDE;
98 void VisitShl(HShl* instruction) OVERRIDE;
99 void VisitShr(HShr* instruction) OVERRIDE;
100 void VisitSub(HSub* instruction) OVERRIDE;
101 void VisitUShr(HUShr* instruction) OVERRIDE;
102 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +0000103 void VisitSelect(HSelect* select) OVERRIDE;
104 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100105 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100106 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700107 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200108 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100109
110 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000111
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100113 void SimplifySystemArrayCopy(HInvoke* invoke);
114 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100115 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800116 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800117 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100118 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100119 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000120 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800121 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800122 void SimplifyReturnThis(HInvoke* invoke);
123 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800124 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800125 void SimplifyMin(HInvoke* invoke, DataType::Type type);
126 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800127 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100128
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000129 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100130 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000131 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100132 bool simplification_occurred_ = false;
133 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700134 // We ensure we do not loop infinitely. The value should not be too high, since that
135 // would allow looping around the same basic block too many times. The value should
136 // not be too low either, however, since we want to allow revisiting a basic block
137 // with many statements and simplifications at least once.
138 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000139};
140
Aart Bik24773202018-04-26 10:28:51 -0700141bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100142 if (kTestInstructionClonerExhaustively) {
143 CloneAndReplaceInstructionVisitor visitor(graph_);
144 visitor.VisitReversePostOrder();
145 }
146
Vladimir Marko65979462017-05-19 17:25:12 +0100147 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700148 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100149}
150
Aart Bik24773202018-04-26 10:28:51 -0700151bool InstructionSimplifierVisitor::Run() {
152 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100153 // Iterate in reverse post order to open up more simplifications to users
154 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100155 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100156 // The simplification of an instruction to another instruction may yield
157 // possibilities for other simplifications. So although we perform a reverse
158 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100159 do {
160 simplification_occurred_ = false;
161 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700162 if (simplification_occurred_) {
163 didSimplify = true;
164 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100165 } while (simplification_occurred_ &&
166 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100167 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100168 }
Aart Bik24773202018-04-26 10:28:51 -0700169 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100170}
171
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000172namespace {
173
174bool AreAllBitsSet(HConstant* constant) {
175 return Int64FromConstant(constant) == -1;
176}
177
178} // namespace
179
Alexandre Rames188d4312015-04-09 18:30:21 +0100180// Returns true if the code was simplified to use only one negation operation
181// after the binary operation instead of one on each of the inputs.
182bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
183 DCHECK(binop->IsAdd() || binop->IsSub());
184 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
185 HNeg* left_neg = binop->GetLeft()->AsNeg();
186 HNeg* right_neg = binop->GetRight()->AsNeg();
187 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
188 !right_neg->HasOnlyOneNonEnvironmentUse()) {
189 return false;
190 }
191 // Replace code looking like
192 // NEG tmp1, a
193 // NEG tmp2, b
194 // ADD dst, tmp1, tmp2
195 // with
196 // ADD tmp, a, b
197 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600198 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
199 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
200 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100201 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600202 return false;
203 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100204 binop->ReplaceInput(left_neg->GetInput(), 0);
205 binop->ReplaceInput(right_neg->GetInput(), 1);
206 left_neg->GetBlock()->RemoveInstruction(left_neg);
207 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100208 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100209 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
210 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
211 RecordSimplification();
212 return true;
213}
214
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000215bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
216 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100217 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000218 HInstruction* left = op->GetLeft();
219 HInstruction* right = op->GetRight();
220
221 // We can apply De Morgan's laws if both inputs are Not's and are only used
222 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000223 if (((left->IsNot() && right->IsNot()) ||
224 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225 left->HasOnlyOneNonEnvironmentUse() &&
226 right->HasOnlyOneNonEnvironmentUse()) {
227 // Replace code looking like
228 // NOT nota, a
229 // NOT notb, b
230 // AND dst, nota, notb (respectively OR)
231 // with
232 // OR or, a, b (respectively AND)
233 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000234 HInstruction* src_left = left->InputAt(0);
235 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000236 uint32_t dex_pc = op->GetDexPc();
237
238 // Remove the negations on the inputs.
239 left->ReplaceWith(src_left);
240 right->ReplaceWith(src_right);
241 left->GetBlock()->RemoveInstruction(left);
242 right->GetBlock()->RemoveInstruction(right);
243
244 // Replace the `HAnd` or `HOr`.
245 HBinaryOperation* hbin;
246 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100247 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000248 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100249 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000250 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000251 HInstruction* hnot;
252 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100253 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000254 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100255 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000256 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000257
258 op->GetBlock()->InsertInstructionBefore(hbin, op);
259 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
260
261 RecordSimplification();
262 return true;
263 }
264
265 return false;
266}
267
Lena Djokicbc5460b2017-07-20 16:07:36 +0200268bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100269 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200270 InstructionSet isa = codegen_->GetInstructionSet();
271 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000272 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100273 if (!(type == DataType::Type::kUint8 ||
274 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100275 type == DataType::Type::kUint16 ||
276 type == DataType::Type::kInt16 ||
277 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278 return false;
279 }
280 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000281 case InstructionSet::kMips:
282 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100283 if (!(type == DataType::Type::kUint8 ||
284 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100285 type == DataType::Type::kUint16 ||
286 type == DataType::Type::kInt16 ||
287 type == DataType::Type::kInt32 ||
288 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200289 return false;
290 }
291 break;
292 default:
293 return false;
294 }
295
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100296 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200297
298 if (mul->HasOnlyOneNonEnvironmentUse()) {
299 HInstruction* use = mul->GetUses().front().GetUser();
300 if (use->IsVecAdd() || use->IsVecSub()) {
301 // Replace code looking like
302 // VECMUL tmp, x, y
303 // VECADD/SUB dst, acc, tmp
304 // with
305 // VECMULACC dst, acc, x, y
306 // Note that we do not want to (unconditionally) perform the merge when the
307 // multiplication has multiple uses and it can be merged in all of them.
308 // Multiple uses could happen on the same control-flow path, and we would
309 // then increase the amount of work. In the future we could try to evaluate
310 // whether all uses are on different control-flow paths (using dominance and
311 // reverse-dominance information) and only perform the merge when they are.
312 HInstruction* accumulator = nullptr;
313 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
314 HInstruction* binop_left = binop->GetLeft();
315 HInstruction* binop_right = binop->GetRight();
316 // This is always true since the `HVecMul` has only one use (which is checked above).
317 DCHECK_NE(binop_left, binop_right);
318 if (binop_right == mul) {
319 accumulator = binop_left;
320 } else if (use->IsVecAdd()) {
321 DCHECK_EQ(binop_left, mul);
322 accumulator = binop_right;
323 }
324
325 HInstruction::InstructionKind kind =
326 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
327 if (accumulator != nullptr) {
328 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100329 new (allocator) HVecMultiplyAccumulate(allocator,
330 kind,
331 accumulator,
332 mul->GetLeft(),
333 mul->GetRight(),
334 binop->GetPackedType(),
335 binop->GetVectorLength(),
336 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200337
338 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
339 DCHECK(!mul->HasUses());
340 mul->GetBlock()->RemoveInstruction(mul);
341 return true;
342 }
343 }
344 }
345
346 return false;
347}
348
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000349void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
350 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100351 HInstruction* shift_amount = instruction->GetRight();
352 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000353
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100354 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100355 ? kMaxLongShiftDistance
356 : kMaxIntShiftDistance;
357
358 if (shift_amount->IsConstant()) {
359 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700360 int64_t masked_cst = cst & implicit_mask;
361 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400362 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100363 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400364 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100365 // value
366 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400367 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100368 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100369 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700370 } else if (masked_cst != cst) {
371 // Replace code looking like
372 // SHL dst, value, cst
373 // where cst exceeds maximum distance with the equivalent
374 // SHL dst, value, cst & implicit_mask
375 // (as defined by shift semantics). This ensures other
376 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100377 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700378 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
379 RecordSimplification();
380 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100381 }
382 }
383
384 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100385 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
386 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100387 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100388 // AND adjusted_shift, shift, <superset of implicit mask>
389 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
390 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
391 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100392 // with
393 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100394 if (shift_amount->IsAnd() ||
395 shift_amount->IsOr() ||
396 shift_amount->IsXor() ||
397 shift_amount->IsAdd() ||
398 shift_amount->IsSub()) {
399 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
400 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
401 HConstant* mask = bin_op->GetConstantRight();
402 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
403 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100404 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100405 return;
406 }
407 } else if (shift_amount->IsTypeConversion()) {
408 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
409 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
410 // Non-integral and 64-bit source types require an explicit type conversion.
411 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
412 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
413 RecordSimplification();
414 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400415 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000416 }
417}
418
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000419static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
420 return (sub->GetRight() == other &&
421 sub->GetLeft()->IsConstant() &&
422 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
423}
424
425bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
426 HUShr* ushr,
427 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000428 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100429 HRor* ror =
430 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000431 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
432 if (!ushr->HasUses()) {
433 ushr->GetBlock()->RemoveInstruction(ushr);
434 }
435 if (!ushr->GetRight()->HasUses()) {
436 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
437 }
438 if (!shl->HasUses()) {
439 shl->GetBlock()->RemoveInstruction(shl);
440 }
441 if (!shl->GetRight()->HasUses()) {
442 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
443 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100444 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000445 return true;
446}
447
448// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
449bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000450 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
451 HInstruction* left = op->GetLeft();
452 HInstruction* right = op->GetRight();
453 // If we have an UShr and a Shl (in either order).
454 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
455 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
456 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100457 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000458 if (ushr->GetType() == shl->GetType() &&
459 ushr->GetLeft() == shl->GetLeft()) {
460 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
461 // Shift distances are both constant, try replacing with Ror if they
462 // add up to the register size.
463 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
464 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
465 // Shift distances are potentially of the form x and (reg_size - x).
466 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
467 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
468 // Shift distances are potentially of the form d and -d.
469 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
470 }
471 }
472 }
473 return false;
474}
475
476// Try replacing code looking like (x >>> #rdist OP x << #ldist):
477// UShr dst, x, #rdist
478// Shl tmp, x, #ldist
479// OP dst, dst, tmp
480// or like (x >>> #rdist OP x << #-ldist):
481// UShr dst, x, #rdist
482// Shl tmp, x, #-ldist
483// OP dst, dst, tmp
484// with
485// Ror dst, x, #rdist
486bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
487 HUShr* ushr,
488 HShl* shl) {
489 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100490 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000491 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
492 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
493 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
494 ReplaceRotateWithRor(op, ushr, shl);
495 return true;
496 }
497 return false;
498}
499
500// Replace code looking like (x >>> -d OP x << d):
501// Neg neg, d
502// UShr dst, x, neg
503// Shl tmp, x, d
504// OP dst, dst, tmp
505// with
506// Neg neg, d
507// Ror dst, x, neg
508// *** OR ***
509// Replace code looking like (x >>> d OP x << -d):
510// UShr dst, x, d
511// Neg neg, d
512// Shl tmp, x, neg
513// OP dst, dst, tmp
514// with
515// Ror dst, x, d
516bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
517 HUShr* ushr,
518 HShl* shl) {
519 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
520 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
521 bool neg_is_left = shl->GetRight()->IsNeg();
522 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
523 // And the shift distance being negated is the distance being shifted the other way.
524 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
525 ReplaceRotateWithRor(op, ushr, shl);
526 }
527 return false;
528}
529
530// Try replacing code looking like (x >>> d OP x << (#bits - d)):
531// UShr dst, x, d
532// Sub ld, #bits, d
533// Shl tmp, x, ld
534// OP dst, dst, tmp
535// with
536// Ror dst, x, d
537// *** OR ***
538// Replace code looking like (x >>> (#bits - d) OP x << d):
539// Sub rd, #bits, d
540// UShr dst, x, rd
541// Shl tmp, x, d
542// OP dst, dst, tmp
543// with
544// Neg neg, d
545// Ror dst, x, neg
546bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
547 HUShr* ushr,
548 HShl* shl) {
549 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
550 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100551 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000552 HInstruction* shl_shift = shl->GetRight();
553 HInstruction* ushr_shift = ushr->GetRight();
554 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
555 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
556 return ReplaceRotateWithRor(op, ushr, shl);
557 }
558 return false;
559}
560
Calin Juravle10e244f2015-01-26 18:54:32 +0000561void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
562 HInstruction* obj = null_check->InputAt(0);
563 if (!obj->CanBeNull()) {
564 null_check->ReplaceWith(obj);
565 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000566 if (stats_ != nullptr) {
567 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
568 }
569 }
570}
571
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100572bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
573 if (!input->CanBeNull()) {
574 return true;
575 }
576
Vladimir Marko46817b82016-03-29 12:21:58 +0100577 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
578 HInstruction* user = use.GetUser();
579 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100580 return true;
581 }
582 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100583
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100584 return false;
585}
586
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100587// Returns whether doing a type test between the class of `object` against `klass` has
588// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000589static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
590 HInstruction* object,
591 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000592 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
593 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
594 ScopedObjectAccess soa(Thread::Current());
595 if (!obj_rti.IsValid()) {
596 // We run the simplifier before the reference type propagation so type info might not be
597 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100598 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000599 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100600
Calin Juravle98893e12015-10-02 21:05:03 +0100601 if (!class_rti.IsValid()) {
602 // Happens when the loaded class is unresolved.
603 return false;
604 }
605 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000606 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100607 *outcome = true;
608 return true;
609 } else if (obj_rti.IsExact()) {
610 // The test failed at compile time so will also fail at runtime.
611 *outcome = false;
612 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100613 } else if (!class_rti.IsInterface()
614 && !obj_rti.IsInterface()
615 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100616 // Different type hierarchy. The test will fail.
617 *outcome = false;
618 return true;
619 }
620 return false;
621}
622
623void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
624 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000625 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
626 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100627 // If we need to perform an access check we cannot remove the instruction.
628 return;
629 }
630
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100631 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100632 check_cast->ClearMustDoNullCheck();
633 }
634
635 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000636 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700637 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100638 return;
639 }
640
Roland Levillain05e34f42018-05-24 13:19:05 +0000641 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
642 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000643 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000644 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100645 if (outcome) {
646 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700647 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000648 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
649 HLoadClass* load_class = check_cast->GetTargetClass();
650 if (!load_class->HasUses()) {
651 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
652 // However, here we know that it cannot because the checkcast was successfull, hence
653 // the class was already loaded.
654 load_class->GetBlock()->RemoveInstruction(load_class);
655 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700656 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100657 } else {
658 // Don't do anything for exceptional cases for now. Ideally we should remove
659 // all instructions and blocks this instruction dominates.
660 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000661 }
662}
663
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100664void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100665 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000666 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
667 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100668 // If we need to perform an access check we cannot remove the instruction.
669 return;
670 }
671
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100673 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100674 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100675 instruction->ClearMustDoNullCheck();
676 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100677
678 HGraph* graph = GetGraph();
679 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000680 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100681 instruction->ReplaceWith(graph->GetIntConstant(0));
682 instruction->GetBlock()->RemoveInstruction(instruction);
683 RecordSimplification();
684 return;
685 }
686
Roland Levillain05e34f42018-05-24 13:19:05 +0000687 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
688 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000689 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000690 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000691 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100692 if (outcome && can_be_null) {
693 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100694 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100695 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
696 instruction->ReplaceWith(test);
697 } else {
698 // We've statically determined the result of the instanceof.
699 instruction->ReplaceWith(graph->GetIntConstant(outcome));
700 }
701 RecordSimplification();
702 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000703 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
704 HLoadClass* load_class = instruction->GetTargetClass();
705 if (!load_class->HasUses()) {
706 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
707 // However, here we know that it cannot because the instanceof check was successfull, hence
708 // the class was already loaded.
709 load_class->GetBlock()->RemoveInstruction(load_class);
710 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700711 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100712 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100713}
714
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100715void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100716 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100717 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100718 instruction->ClearValueCanBeNull();
719 }
720}
721
722void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100723 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100724 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100725 instruction->ClearValueCanBeNull();
726 }
727}
728
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100729static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600730 HInstruction *lhs = cond->InputAt(0);
731 HInstruction *rhs = cond->InputAt(1);
732 switch (cond->GetKind()) {
733 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100734 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600735 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100736 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600737 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100738 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600739 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100740 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600741 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100742 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600743 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100744 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600745 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100746 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600747 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100748 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600749 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100750 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600751 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100752 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600753 default:
754 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
755 }
756 return nullptr;
757}
758
Aart Bik2767f4b2016-10-28 15:03:53 -0700759static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100760 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700761 return true; // input has direct boolean type
762 } else if (cmp->GetUses().HasExactlyOneElement()) {
763 // Comparison also has boolean type if both its input and the instruction
764 // itself feed into the same phi node.
765 HInstruction* user = cmp->GetUses().front().GetUser();
766 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
767 }
768 return false;
769}
770
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000771void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100772 HInstruction* input_const = equal->GetConstantRight();
773 if (input_const != nullptr) {
774 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700775 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100776 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100777 // We are comparing the boolean to a constant which is of type int and can
778 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000779 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100780 // Replace (bool_value == true) with bool_value
781 equal->ReplaceWith(input_value);
782 block->RemoveInstruction(equal);
783 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000784 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700785 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500786 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
787 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100788 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100789 } else {
790 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
791 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
792 block->RemoveInstruction(equal);
793 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100794 }
Mark Mendellc4701932015-04-10 13:18:51 -0400795 } else {
796 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100797 }
Mark Mendellc4701932015-04-10 13:18:51 -0400798 } else {
799 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100800 }
801}
802
David Brazdil0d13fee2015-04-17 14:52:19 +0100803void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
804 HInstruction* input_const = not_equal->GetConstantRight();
805 if (input_const != nullptr) {
806 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700807 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100808 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100809 // We are comparing the boolean to a constant which is of type int and can
810 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000811 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700812 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500813 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
814 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100815 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000816 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100817 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100818 not_equal->ReplaceWith(input_value);
819 block->RemoveInstruction(not_equal);
820 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100821 } else {
822 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
823 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
824 block->RemoveInstruction(not_equal);
825 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100826 }
Mark Mendellc4701932015-04-10 13:18:51 -0400827 } else {
828 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100829 }
Mark Mendellc4701932015-04-10 13:18:51 -0400830 } else {
831 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100832 }
833}
834
835void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000836 HInstruction* input = bool_not->InputAt(0);
837 HInstruction* replace_with = nullptr;
838
839 if (input->IsIntConstant()) {
840 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000841 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000842 replace_with = GetGraph()->GetIntConstant(0);
843 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000844 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000845 replace_with = GetGraph()->GetIntConstant(1);
846 }
847 } else if (input->IsBooleanNot()) {
848 // Replace (!(!bool_value)) with bool_value.
849 replace_with = input->InputAt(0);
850 } else if (input->IsCondition() &&
851 // Don't change FP compares. The definition of compares involving
852 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100853 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000854 // Replace condition with its opposite.
855 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
856 }
857
858 if (replace_with != nullptr) {
859 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100860 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000861 RecordSimplification();
862 }
863}
864
Aart Bik4f7dd342017-09-12 13:12:57 -0700865// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100866static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
867 HInstruction* x,
868 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700869 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800870 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700871 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800872 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
873 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700874}
875
Aart Bik142b9132018-03-14 15:12:59 -0700876// Constructs a new MIN/MAX(x, y) node in the HIR.
877static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
878 HInstruction* x,
879 HInstruction* y,
880 HInstruction* cursor,
881 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700882 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700883 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
884 HBinaryOperation* minmax = nullptr;
885 if (is_min) {
886 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
887 } else {
888 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
889 }
890 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
891 return minmax;
892}
893
Aart Bik4f7dd342017-09-12 13:12:57 -0700894// Returns true if operands a and b consists of widening type conversions
895// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100896static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700897 if (a->IsTypeConversion() && a->GetType() == to_type) {
898 a = a->InputAt(0);
899 }
900 if (b->IsTypeConversion() && b->GetType() == to_type) {
901 b = b->InputAt(0);
902 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100903 DataType::Type type1 = a->GetType();
904 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100905 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
906 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
907 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
908 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
909 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100910 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700911}
912
Aart Bik1d746de2018-03-28 16:30:02 -0700913// Returns an acceptable substitution for "a" on the select
914// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
915static HInstruction* AllowInMinMax(IfCondition cmp,
916 HInstruction* a,
917 HInstruction* b,
918 HInstruction* c) {
919 int64_t value = 0;
920 if (IsInt64AndGet(b, /*out*/ &value) &&
921 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
922 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
923 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
924 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
925 int64_t other_value = Int64FromConstant(other);
926 bool is_max = (cmp == kCondLT || cmp == kCondLE);
927 // Allow the max for a < 100 ? max(a, -100) : ..
928 // or the min for a > -100 ? min(a, 100) : ..
929 if (is_max ? (value >= other_value) : (value <= other_value)) {
930 return c;
931 }
932 }
933 }
934 return nullptr;
935}
936
David Brazdil74eb1b22015-12-14 11:44:01 +0000937void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
938 HInstruction* replace_with = nullptr;
939 HInstruction* condition = select->GetCondition();
940 HInstruction* true_value = select->GetTrueValue();
941 HInstruction* false_value = select->GetFalseValue();
942
943 if (condition->IsBooleanNot()) {
944 // Change ((!cond) ? x : y) to (cond ? y : x).
945 condition = condition->InputAt(0);
946 std::swap(true_value, false_value);
947 select->ReplaceInput(false_value, 0);
948 select->ReplaceInput(true_value, 1);
949 select->ReplaceInput(condition, 2);
950 RecordSimplification();
951 }
952
953 if (true_value == false_value) {
954 // Replace (cond ? x : x) with (x).
955 replace_with = true_value;
956 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000957 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000958 // Replace (true ? x : y) with (x).
959 replace_with = true_value;
960 } else {
961 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000962 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000963 replace_with = false_value;
964 }
965 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000966 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000967 // Replace (cond ? true : false) with (cond).
968 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000969 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000970 // Replace (cond ? false : true) with (!cond).
971 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
972 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700973 } else if (condition->IsCondition()) {
974 IfCondition cmp = condition->AsCondition()->GetCondition();
975 HInstruction* a = condition->InputAt(0);
976 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100977 DataType::Type t_type = true_value->GetType();
978 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700979 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700980 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
981 // type will be int or long, like the condition). Replacements are general,
982 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700983 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700984 // Allow a < 100 ? max(a, -100) : ..
985 // or a > -100 ? min(a, 100) : ..
986 // to use min/max instead of a to detect nested min/max expressions.
987 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
988 if (new_a != nullptr) {
989 a = new_a;
990 }
Aart Bik142b9132018-03-14 15:12:59 -0700991 // Try to replace typical integral MIN/MAX/ABS constructs.
992 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
993 ((a == true_value && b == false_value) ||
994 (b == true_value && a == false_value))) {
995 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
996 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
997 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
998 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700999 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
1000 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
1001 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
1002 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1003 HInstruction* not_negated = negLeft ? false_value : true_value;
1004 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1005 // Found a < 0 ? -a : a
1006 // or a > 0 ? a : -a
1007 // which can be replaced by ABS(a).
1008 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001009 }
1010 } else if (true_value->IsSub() && false_value->IsSub()) {
1011 HInstruction* true_sub1 = true_value->InputAt(0);
1012 HInstruction* true_sub2 = true_value->InputAt(1);
1013 HInstruction* false_sub1 = false_value->InputAt(0);
1014 HInstruction* false_sub2 = false_value->InputAt(1);
1015 if ((((cmp == kCondGT || cmp == kCondGE) &&
1016 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1017 ((cmp == kCondLT || cmp == kCondLE) &&
1018 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1019 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001020 // Found a > b ? a - b : b - a
1021 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001022 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001023 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001024 }
1025 }
1026 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001027 }
1028
1029 if (replace_with != nullptr) {
1030 select->ReplaceWith(replace_with);
1031 select->GetBlock()->RemoveInstruction(select);
1032 RecordSimplification();
1033 }
1034}
1035
1036void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1037 HInstruction* condition = instruction->InputAt(0);
1038 if (condition->IsBooleanNot()) {
1039 // Swap successors if input is negated.
1040 instruction->ReplaceInput(condition->InputAt(0), 0);
1041 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001042 RecordSimplification();
1043 }
1044}
1045
Mingyao Yang0304e182015-01-30 16:41:29 -08001046void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1047 HInstruction* input = instruction->InputAt(0);
1048 // If the array is a NewArray with constant size, replace the array length
1049 // with the constant instruction. This helps the bounds check elimination phase.
1050 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001051 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001052 if (input->IsIntConstant()) {
1053 instruction->ReplaceWith(input);
1054 }
1055 }
1056}
1057
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001058void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001059 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001060 if (value->GetType() != DataType::Type::kReference) {
1061 return;
1062 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001063
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001064 if (CanEnsureNotNullAt(value, instruction)) {
1065 instruction->ClearValueCanBeNull();
1066 }
1067
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001068 if (value->IsArrayGet()) {
1069 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1070 // If the code is just swapping elements in the array, no need for a type check.
1071 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001072 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001073 }
1074 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001075
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001076 if (value->IsNullConstant()) {
1077 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001078 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001079 }
1080
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001081 ScopedObjectAccess soa(Thread::Current());
1082 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1083 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1084 if (!array_rti.IsValid()) {
1085 return;
1086 }
1087
1088 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1089 instruction->ClearNeedsTypeCheck();
1090 return;
1091 }
1092
1093 if (array_rti.IsObjectArray()) {
1094 if (array_rti.IsExact()) {
1095 instruction->ClearNeedsTypeCheck();
1096 return;
1097 }
1098 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001099 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001100}
1101
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001102static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001103 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1104 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1105 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001106 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001107 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001108 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1109 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001110 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001111 return DataType::Size(result_type) > DataType::Size(input_type) &&
1112 result_type != DataType::Type::kUint16 &&
1113 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001114}
1115
Vladimir Marko61b92282017-10-11 13:23:17 +01001116static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1117 if (maybe_get->IsInstanceFieldGet()) {
1118 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1119 return true;
1120 } else if (maybe_get->IsStaticFieldGet()) {
1121 maybe_get->AsStaticFieldGet()->SetType(new_type);
1122 return true;
1123 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1124 maybe_get->AsArrayGet()->SetType(new_type);
1125 return true;
1126 } else {
1127 return false;
1128 }
1129}
1130
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001131// The type conversion is only used for storing into a field/element of the
1132// same/narrower size.
1133static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1134 if (type_conversion->HasEnvironmentUses()) {
1135 return false;
1136 }
1137 DataType::Type input_type = type_conversion->GetInputType();
1138 DataType::Type result_type = type_conversion->GetResultType();
1139 if (!DataType::IsIntegralType(input_type) ||
1140 !DataType::IsIntegralType(result_type) ||
1141 input_type == DataType::Type::kInt64 ||
1142 result_type == DataType::Type::kInt64) {
1143 // Type conversion is needed if non-integer types are involved, or 64-bit
1144 // types are involved, which may use different number of registers.
1145 return false;
1146 }
1147 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1148 // Type conversion is not necessary when storing to a field/element of the
1149 // same/smaller size.
1150 } else {
1151 // We do not handle this case here.
1152 return false;
1153 }
1154
1155 // Check if the converted value is only used for storing into heap.
1156 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1157 HInstruction* instruction = use.GetUser();
1158 if (instruction->IsInstanceFieldSet() &&
1159 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1160 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1161 continue;
1162 }
1163 if (instruction->IsStaticFieldSet() &&
1164 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1165 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1166 continue;
1167 }
1168 if (instruction->IsArraySet() &&
1169 instruction->AsArraySet()->GetComponentType() == result_type &&
1170 // not index use.
1171 instruction->AsArraySet()->GetIndex() != type_conversion) {
1172 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1173 continue;
1174 }
1175 // The use is not as a store value, or the field/element type is not the
1176 // same as the result_type, keep the type conversion.
1177 return false;
1178 }
1179 // Codegen automatically handles the type conversion during the store.
1180 return true;
1181}
1182
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001183void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001184 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001185 DataType::Type input_type = input->GetType();
1186 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001187 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001188 // Remove the implicit conversion; this includes conversion to the same type.
1189 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001190 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001191 RecordSimplification();
1192 return;
1193 }
1194
1195 if (input->IsTypeConversion()) {
1196 HTypeConversion* input_conversion = input->AsTypeConversion();
1197 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001198 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001199
1200 // When the first conversion is lossless, a direct conversion from the original type
1201 // to the final type yields the same result, even for a lossy second conversion, for
1202 // example float->double->int or int->double->float.
1203 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1204
1205 // For integral conversions, see if the first conversion loses only bits that the second
1206 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1207 // conversion yields the same result, for example long->int->short or int->char->short.
1208 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001209 DataType::IsIntegralType(input_type) &&
1210 DataType::IsIntegralType(original_type) &&
1211 DataType::IsIntegralType(result_type) &&
1212 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001213
1214 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1215 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001216 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001217 instruction->ReplaceWith(original_input);
1218 instruction->GetBlock()->RemoveInstruction(instruction);
1219 if (!input_conversion->HasUses()) {
1220 // Don't wait for DCE.
1221 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1222 }
1223 RecordSimplification();
1224 return;
1225 }
1226 // Otherwise simplify only if the first conversion has no other use.
1227 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1228 input_conversion->ReplaceWith(original_input);
1229 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1230 RecordSimplification();
1231 return;
1232 }
1233 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001234 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1235 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001236 HAnd* input_and = input->AsAnd();
1237 HConstant* constant = input_and->GetConstantRight();
1238 if (constant != nullptr) {
1239 int64_t value = Int64FromConstant(constant);
1240 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1241 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001242 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001243 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001244 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001245 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001246 instruction->ReplaceWith(original_input);
1247 instruction->GetBlock()->RemoveInstruction(instruction);
1248 RecordSimplification();
1249 return;
1250 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1251 input_and->ReplaceWith(original_input);
1252 input_and->GetBlock()->RemoveInstruction(input_and);
1253 RecordSimplification();
1254 return;
1255 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001256 }
1257 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001258 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1259 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1260 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1261 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1262 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1263 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1264 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1265 instruction->ReplaceWith(input);
1266 instruction->GetBlock()->RemoveInstruction(instruction);
1267 RecordSimplification();
1268 return;
1269 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001270 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001271
1272 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1273 instruction->ReplaceWith(input);
1274 instruction->GetBlock()->RemoveInstruction(instruction);
1275 RecordSimplification();
1276 return;
1277 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001278}
1279
Aart Bikc6eec4b2018-03-29 17:22:00 -07001280void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1281 HInstruction* input = instruction->GetInput();
1282 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1283 // Zero extension from narrow to wide can never set sign bit in the wider
1284 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1285 instruction->ReplaceWith(input);
1286 instruction->GetBlock()->RemoveInstruction(instruction);
1287 RecordSimplification();
1288 }
1289}
1290
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001291void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1292 HConstant* input_cst = instruction->GetConstantRight();
1293 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001294 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001295 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001296 // Replace code looking like
1297 // ADD dst, src, 0
1298 // with
1299 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001300 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1301 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1302 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001303 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001304 instruction->ReplaceWith(input_other);
1305 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001306 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001307 return;
1308 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001309 }
1310
1311 HInstruction* left = instruction->GetLeft();
1312 HInstruction* right = instruction->GetRight();
1313 bool left_is_neg = left->IsNeg();
1314 bool right_is_neg = right->IsNeg();
1315
1316 if (left_is_neg && right_is_neg) {
1317 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1318 return;
1319 }
1320 }
1321
1322 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1323 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1324 // Replace code looking like
1325 // NEG tmp, b
1326 // ADD dst, a, tmp
1327 // with
1328 // SUB dst, a, b
1329 // We do not perform the optimization if the input negation has environment
1330 // uses or multiple non-environment uses as it could lead to worse code. In
1331 // particular, we do not want the live range of `b` to be extended if we are
1332 // not sure the initial 'NEG' instruction can be removed.
1333 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001334 HSub* sub =
1335 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001336 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1337 RecordSimplification();
1338 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001339 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001340 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001341
Anton Kirilove14dc862016-05-13 17:56:15 +01001342 if (TryReplaceWithRotate(instruction)) {
1343 return;
1344 }
1345
1346 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1347 // so no need to return.
1348 TryHandleAssociativeAndCommutativeOperation(instruction);
1349
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001350 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001351 TrySubtractionChainSimplification(instruction)) {
1352 return;
1353 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001354
1355 if (integral_type) {
1356 // Replace code patterns looking like
1357 // SUB dst1, x, y SUB dst1, x, y
1358 // ADD dst2, dst1, y ADD dst2, y, dst1
1359 // with
1360 // SUB dst1, x, y
1361 // ADD instruction is not needed in this case, we may use
1362 // one of inputs of SUB instead.
1363 if (left->IsSub() && left->InputAt(1) == right) {
1364 instruction->ReplaceWith(left->InputAt(0));
1365 RecordSimplification();
1366 instruction->GetBlock()->RemoveInstruction(instruction);
1367 return;
1368 } else if (right->IsSub() && right->InputAt(1) == left) {
1369 instruction->ReplaceWith(right->InputAt(0));
1370 RecordSimplification();
1371 instruction->GetBlock()->RemoveInstruction(instruction);
1372 return;
1373 }
1374 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001375}
1376
1377void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001378 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001379 HConstant* input_cst = instruction->GetConstantRight();
1380 HInstruction* input_other = instruction->GetLeastConstantLeft();
1381
Vladimir Marko452c1b62015-09-25 14:44:17 +01001382 if (input_cst != nullptr) {
1383 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001384 if (value == -1 ||
1385 // Similar cases under zero extension.
1386 (DataType::IsUnsignedType(input_other->GetType()) &&
1387 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001388 // Replace code looking like
1389 // AND dst, src, 0xFFF...FF
1390 // with
1391 // src
1392 instruction->ReplaceWith(input_other);
1393 instruction->GetBlock()->RemoveInstruction(instruction);
1394 RecordSimplification();
1395 return;
1396 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001397 if (input_other->IsTypeConversion() &&
1398 input_other->GetType() == DataType::Type::kInt64 &&
1399 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1400 IsInt<32>(value) &&
1401 input_other->HasOnlyOneNonEnvironmentUse()) {
1402 // The AND can be reordered before the TypeConversion. Replace
1403 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1404 // TypeConversion<Int64> tmp, src
1405 // AND dst, tmp, cst
1406 // with
1407 // IntConstant cst, <32-bit-constant>
1408 // AND tmp, src, cst
1409 // TypeConversion<Int64> dst, tmp
1410 // This helps 32-bit targets and does not hurt 64-bit targets.
1411 // This also simplifies detection of other patterns, such as Uint8 loads.
1412 HInstruction* new_and_input = input_other->InputAt(0);
1413 // Implicit conversion Int64->Int64 would have been removed previously.
1414 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1415 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1416 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001417 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001418 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1419 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001420 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001421 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1422 input_other->GetBlock()->RemoveInstruction(input_other);
1423 RecordSimplification();
1424 // Try to process the new And now, do not wait for the next round of simplifications.
1425 instruction = new_and;
1426 input_other = new_and_input;
1427 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001428 // Eliminate And from UShr+And if the And-mask contains all the bits that
1429 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1430 // precisely clears the shifted-in sign bits.
1431 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001432 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001433 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1434 size_t num_tail_bits_set = CTZ(value + 1);
1435 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1436 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1437 instruction->ReplaceWith(input_other);
1438 instruction->GetBlock()->RemoveInstruction(instruction);
1439 RecordSimplification();
1440 return;
1441 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1442 input_other->HasOnlyOneNonEnvironmentUse()) {
1443 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1444 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001445 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001446 input_other->InputAt(0),
1447 input_other->InputAt(1),
1448 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001449 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1450 input_other->GetBlock()->RemoveInstruction(input_other);
1451 RecordSimplification();
1452 return;
1453 }
1454 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001455 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1456 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1457 // or array Get with only a single use, short-circuit the subsequent simplification
1458 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1459 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1460 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1461 if (input_other->GetType() == find_type &&
1462 input_other->HasOnlyOneNonEnvironmentUse() &&
1463 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1464 instruction->ReplaceWith(input_other);
1465 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001466 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1467 instruction->ReplaceWith(input_other);
1468 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001469 } else {
1470 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1471 new_type, input_other, instruction->GetDexPc());
1472 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1473 }
1474 RecordSimplification();
1475 return;
1476 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001477 }
1478
1479 // We assume that GVN has run before, so we only perform a pointer comparison.
1480 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001481 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001482 if (instruction->GetLeft() == instruction->GetRight()) {
1483 // Replace code looking like
1484 // AND dst, src, src
1485 // with
1486 // src
1487 instruction->ReplaceWith(instruction->GetLeft());
1488 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001489 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001490 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001491 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001492
Anton Kirilove14dc862016-05-13 17:56:15 +01001493 if (TryDeMorganNegationFactoring(instruction)) {
1494 return;
1495 }
1496
1497 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1498 // so no need to return.
1499 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001500}
1501
Mark Mendellc4701932015-04-10 13:18:51 -04001502void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1503 VisitCondition(condition);
1504}
1505
1506void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1507 VisitCondition(condition);
1508}
1509
1510void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1511 VisitCondition(condition);
1512}
1513
1514void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1515 VisitCondition(condition);
1516}
1517
Anton Shaminbdd79352016-02-15 12:48:36 +06001518void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1519 VisitCondition(condition);
1520}
1521
1522void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1523 VisitCondition(condition);
1524}
1525
1526void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1527 VisitCondition(condition);
1528}
1529
1530void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1531 VisitCondition(condition);
1532}
Aart Bike9f37602015-10-09 11:15:55 -07001533
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001534// Recognize the following pattern:
1535// obj.getClass() ==/!= Foo.class
1536// And replace it with a constant value if the type of `obj` is statically known.
1537static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1538 HInstruction* input_one = condition->InputAt(0);
1539 HInstruction* input_two = condition->InputAt(1);
1540 HLoadClass* load_class = input_one->IsLoadClass()
1541 ? input_one->AsLoadClass()
1542 : input_two->AsLoadClass();
1543 if (load_class == nullptr) {
1544 return false;
1545 }
1546
1547 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1548 if (!class_rti.IsValid()) {
1549 // Unresolved class.
1550 return false;
1551 }
1552
1553 HInstanceFieldGet* field_get = (load_class == input_one)
1554 ? input_two->AsInstanceFieldGet()
1555 : input_one->AsInstanceFieldGet();
1556 if (field_get == nullptr) {
1557 return false;
1558 }
1559
1560 HInstruction* receiver = field_get->InputAt(0);
1561 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1562 if (!receiver_type.IsExact()) {
1563 return false;
1564 }
1565
1566 {
1567 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001568 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001569 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1570 if (field_get->GetFieldInfo().GetField() != field) {
1571 return false;
1572 }
1573
1574 // We can replace the compare.
1575 int value = 0;
1576 if (receiver_type.IsEqual(class_rti)) {
1577 value = condition->IsEqual() ? 1 : 0;
1578 } else {
1579 value = condition->IsNotEqual() ? 1 : 0;
1580 }
1581 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1582 return true;
1583 }
1584}
1585
Mark Mendellc4701932015-04-10 13:18:51 -04001586void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001587 if (condition->IsEqual() || condition->IsNotEqual()) {
1588 if (RecognizeAndSimplifyClassCheck(condition)) {
1589 return;
1590 }
1591 }
1592
Anton Shaminbdd79352016-02-15 12:48:36 +06001593 // Reverse condition if left is constant. Our code generators prefer constant
1594 // on the right hand side.
1595 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1596 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001597 HCondition* replacement =
1598 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001599 // If it is a fp we must set the opposite bias.
1600 if (replacement != nullptr) {
1601 if (condition->IsLtBias()) {
1602 replacement->SetBias(ComparisonBias::kGtBias);
1603 } else if (condition->IsGtBias()) {
1604 replacement->SetBias(ComparisonBias::kLtBias);
1605 }
1606 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1607 RecordSimplification();
1608
1609 condition = replacement;
1610 }
1611 }
Mark Mendellc4701932015-04-10 13:18:51 -04001612
Mark Mendellc4701932015-04-10 13:18:51 -04001613 HInstruction* left = condition->GetLeft();
1614 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001615
1616 // Try to fold an HCompare into this HCondition.
1617
Mark Mendellc4701932015-04-10 13:18:51 -04001618 // We can only replace an HCondition which compares a Compare to 0.
1619 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1620 // condition with a long, float or double comparison as input.
1621 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1622 // Conversion is not possible.
1623 return;
1624 }
1625
1626 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001627 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001628 // Someone else also wants the result of the compare.
1629 return;
1630 }
1631
Vladimir Marko46817b82016-03-29 12:21:58 +01001632 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001633 // There is a reference to the compare result in an environment. Do we really need it?
1634 if (GetGraph()->IsDebuggable()) {
1635 return;
1636 }
1637
1638 // We have to ensure that there are no deopt points in the sequence.
1639 if (left->HasAnyEnvironmentUseBefore(condition)) {
1640 return;
1641 }
1642 }
1643
1644 // Clean up any environment uses from the HCompare, if any.
1645 left->RemoveEnvironmentUsers();
1646
1647 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1648 condition->SetBias(left->AsCompare()->GetBias());
1649
1650 // Replace the operands of the HCondition.
1651 condition->ReplaceInput(left->InputAt(0), 0);
1652 condition->ReplaceInput(left->InputAt(1), 1);
1653
1654 // Remove the HCompare.
1655 left->GetBlock()->RemoveInstruction(left);
1656
1657 RecordSimplification();
1658}
1659
Andreas Gampe9186ced2016-12-12 14:28:21 -08001660// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1661static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1662 // True, if the most significant bits of divisor are 0.
1663 return ((divisor & 0x7fffff) == 0);
1664}
1665
1666// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1667static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1668 // True, if the most significant bits of divisor are 0.
1669 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1670}
1671
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001672void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1673 HConstant* input_cst = instruction->GetConstantRight();
1674 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001676
1677 if ((input_cst != nullptr) && input_cst->IsOne()) {
1678 // Replace code looking like
1679 // DIV dst, src, 1
1680 // with
1681 // src
1682 instruction->ReplaceWith(input_other);
1683 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001684 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001685 return;
1686 }
1687
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001688 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001689 // Replace code looking like
1690 // DIV dst, src, -1
1691 // with
1692 // NEG dst, src
1693 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001694 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001695 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001696 return;
1697 }
1698
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001699 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001700 // Try replacing code looking like
1701 // DIV dst, src, constant
1702 // with
1703 // MUL dst, src, 1 / constant
1704 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001705 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001706 double value = input_cst->AsDoubleConstant()->GetValue();
1707 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1708 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1709 }
1710 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001711 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001712 float value = input_cst->AsFloatConstant()->GetValue();
1713 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1714 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1715 }
1716 }
1717
1718 if (reciprocal != nullptr) {
1719 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001720 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001721 RecordSimplification();
1722 return;
1723 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001724 }
1725}
1726
1727void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1728 HConstant* input_cst = instruction->GetConstantRight();
1729 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001730 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001731 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001732 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001733
1734 if (input_cst == nullptr) {
1735 return;
1736 }
1737
1738 if (input_cst->IsOne()) {
1739 // Replace code looking like
1740 // MUL dst, src, 1
1741 // with
1742 // src
1743 instruction->ReplaceWith(input_other);
1744 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001745 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001746 return;
1747 }
1748
1749 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001750 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001751 // Replace code looking like
1752 // MUL dst, src, -1
1753 // with
1754 // NEG dst, src
1755 HNeg* neg = new (allocator) HNeg(type, input_other);
1756 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001757 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001758 return;
1759 }
1760
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001761 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001762 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1763 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1764 // Replace code looking like
1765 // FP_MUL dst, src, 2.0
1766 // with
1767 // FP_ADD dst, src, src
1768 // The 'int' and 'long' cases are handled below.
1769 block->ReplaceAndRemoveInstructionWith(instruction,
1770 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001771 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001772 return;
1773 }
1774
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001775 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001776 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001777 // Even though constant propagation also takes care of the zero case, other
1778 // optimizations can lead to having a zero multiplication.
1779 if (factor == 0) {
1780 // Replace code looking like
1781 // MUL dst, src, 0
1782 // with
1783 // 0
1784 instruction->ReplaceWith(input_cst);
1785 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001786 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001787 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001788 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001789 // Replace code looking like
1790 // MUL dst, src, pow_of_2
1791 // with
1792 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001793 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001794 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001795 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001796 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 // ADD dst, src, tmp
1804 HShl* shl = new (allocator) HShl(type,
1805 input_other,
1806 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1807 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1808
1809 block->InsertInstructionBefore(shl, instruction);
1810 block->ReplaceAndRemoveInstructionWith(instruction, add);
1811 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001812 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001813 } else if (IsPowerOfTwo(factor + 1)) {
1814 // Transform code looking like
1815 // MUL dst, src, (2^n - 1)
1816 // into
1817 // SHL tmp, src, n
1818 // SUB dst, tmp, src
1819 HShl* shl = new (allocator) HShl(type,
1820 input_other,
1821 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1822 HSub* sub = new (allocator) HSub(type, shl, input_other);
1823
1824 block->InsertInstructionBefore(shl, instruction);
1825 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1826 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001827 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001828 }
1829 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001830
1831 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1832 // so no need to return.
1833 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001834}
1835
Alexandre Rames188d4312015-04-09 18:30:21 +01001836void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1837 HInstruction* input = instruction->GetInput();
1838 if (input->IsNeg()) {
1839 // Replace code looking like
1840 // NEG tmp, src
1841 // NEG dst, tmp
1842 // with
1843 // src
1844 HNeg* previous_neg = input->AsNeg();
1845 instruction->ReplaceWith(previous_neg->GetInput());
1846 instruction->GetBlock()->RemoveInstruction(instruction);
1847 // We perform the optimization even if the input negation has environment
1848 // uses since it allows removing the current instruction. But we only delete
1849 // the input negation only if it is does not have any uses left.
1850 if (!previous_neg->HasUses()) {
1851 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1852 }
1853 RecordSimplification();
1854 return;
1855 }
1856
Serguei Katkov339dfc22015-04-20 12:29:32 +06001857 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001858 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001859 // Replace code looking like
1860 // SUB tmp, a, b
1861 // NEG dst, tmp
1862 // with
1863 // SUB dst, b, a
1864 // We do not perform the optimization if the input subtraction has
1865 // environment uses or multiple non-environment uses as it could lead to
1866 // worse code. In particular, we do not want the live ranges of `a` and `b`
1867 // to be extended if we are not sure the initial 'SUB' instruction can be
1868 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001869 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001870 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001871 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1872 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001873 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1874 if (!sub->HasUses()) {
1875 sub->GetBlock()->RemoveInstruction(sub);
1876 }
1877 RecordSimplification();
1878 }
1879}
1880
1881void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1882 HInstruction* input = instruction->GetInput();
1883 if (input->IsNot()) {
1884 // Replace code looking like
1885 // NOT tmp, src
1886 // NOT dst, tmp
1887 // with
1888 // src
1889 // We perform the optimization even if the input negation has environment
1890 // uses since it allows removing the current instruction. But we only delete
1891 // the input negation only if it is does not have any uses left.
1892 HNot* previous_not = input->AsNot();
1893 instruction->ReplaceWith(previous_not->GetInput());
1894 instruction->GetBlock()->RemoveInstruction(instruction);
1895 if (!previous_not->HasUses()) {
1896 previous_not->GetBlock()->RemoveInstruction(previous_not);
1897 }
1898 RecordSimplification();
1899 }
1900}
1901
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001902void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1903 HConstant* input_cst = instruction->GetConstantRight();
1904 HInstruction* input_other = instruction->GetLeastConstantLeft();
1905
Roland Levillain1a653882016-03-18 18:05:57 +00001906 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001907 // Replace code looking like
1908 // OR dst, src, 0
1909 // with
1910 // src
1911 instruction->ReplaceWith(input_other);
1912 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001913 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001914 return;
1915 }
1916
1917 // We assume that GVN has run before, so we only perform a pointer comparison.
1918 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001919 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001920 if (instruction->GetLeft() == instruction->GetRight()) {
1921 // Replace code looking like
1922 // OR dst, src, src
1923 // with
1924 // src
1925 instruction->ReplaceWith(instruction->GetLeft());
1926 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001927 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001928 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001929 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001930
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001931 if (TryDeMorganNegationFactoring(instruction)) return;
1932
Anton Kirilove14dc862016-05-13 17:56:15 +01001933 if (TryReplaceWithRotate(instruction)) {
1934 return;
1935 }
1936
1937 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1938 // so no need to return.
1939 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001940}
1941
1942void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1943 VisitShift(instruction);
1944}
1945
1946void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1947 VisitShift(instruction);
1948}
1949
1950void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1951 HConstant* input_cst = instruction->GetConstantRight();
1952 HInstruction* input_other = instruction->GetLeastConstantLeft();
1953
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001954 DataType::Type type = instruction->GetType();
1955 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001956 return;
1957 }
1958
Roland Levillain1a653882016-03-18 18:05:57 +00001959 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001960 // Replace code looking like
1961 // SUB dst, src, 0
1962 // with
1963 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001964 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1965 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1966 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001967 instruction->ReplaceWith(input_other);
1968 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001969 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001970 return;
1971 }
1972
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001973 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001974 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001975
Alexandre Rames188d4312015-04-09 18:30:21 +01001976 HInstruction* left = instruction->GetLeft();
1977 HInstruction* right = instruction->GetRight();
1978 if (left->IsConstant()) {
1979 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001980 // Replace code looking like
1981 // SUB dst, 0, src
1982 // with
1983 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001984 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001985 // `x` is `0.0`, the former expression yields `0.0`, while the later
1986 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001987 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001988 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001989 RecordSimplification();
1990 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001991 }
1992 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001993
1994 if (left->IsNeg() && right->IsNeg()) {
1995 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1996 return;
1997 }
1998 }
1999
2000 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
2001 // Replace code looking like
2002 // NEG tmp, b
2003 // SUB dst, a, tmp
2004 // with
2005 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002006 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002007 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2008 RecordSimplification();
2009 right->GetBlock()->RemoveInstruction(right);
2010 return;
2011 }
2012
2013 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2014 // Replace code looking like
2015 // NEG tmp, a
2016 // SUB dst, tmp, b
2017 // with
2018 // ADD tmp, a, b
2019 // NEG dst, tmp
2020 // The second version is not intrinsically better, but enables more
2021 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002022 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002023 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002024 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002025 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2026 instruction->ReplaceWith(neg);
2027 instruction->GetBlock()->RemoveInstruction(instruction);
2028 RecordSimplification();
2029 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002030 return;
2031 }
2032
2033 if (TrySubtractionChainSimplification(instruction)) {
2034 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002035 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002036
2037 if (left->IsAdd()) {
2038 // Replace code patterns looking like
2039 // ADD dst1, x, y ADD dst1, x, y
2040 // SUB dst2, dst1, y SUB dst2, dst1, x
2041 // with
2042 // ADD dst1, x, y
2043 // SUB instruction is not needed in this case, we may use
2044 // one of inputs of ADD instead.
2045 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002046 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002047 if (left->InputAt(1) == right) {
2048 instruction->ReplaceWith(left->InputAt(0));
2049 RecordSimplification();
2050 instruction->GetBlock()->RemoveInstruction(instruction);
2051 return;
2052 } else if (left->InputAt(0) == right) {
2053 instruction->ReplaceWith(left->InputAt(1));
2054 RecordSimplification();
2055 instruction->GetBlock()->RemoveInstruction(instruction);
2056 return;
2057 }
2058 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002059}
2060
2061void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2062 VisitShift(instruction);
2063}
2064
2065void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2066 HConstant* input_cst = instruction->GetConstantRight();
2067 HInstruction* input_other = instruction->GetLeastConstantLeft();
2068
Roland Levillain1a653882016-03-18 18:05:57 +00002069 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002070 // Replace code looking like
2071 // XOR dst, src, 0
2072 // with
2073 // src
2074 instruction->ReplaceWith(input_other);
2075 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002076 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002077 return;
2078 }
2079
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002080 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002081 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002082 // Replace code looking like
2083 // XOR dst, src, 1
2084 // with
2085 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002086 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002087 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2088 RecordSimplification();
2089 return;
2090 }
2091
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002092 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2093 // Replace code looking like
2094 // XOR dst, src, 0xFFF...FF
2095 // with
2096 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002097 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002098 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002099 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002100 return;
2101 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002102
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002103 HInstruction* left = instruction->GetLeft();
2104 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002105 if (((left->IsNot() && right->IsNot()) ||
2106 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002107 left->HasOnlyOneNonEnvironmentUse() &&
2108 right->HasOnlyOneNonEnvironmentUse()) {
2109 // Replace code looking like
2110 // NOT nota, a
2111 // NOT notb, b
2112 // XOR dst, nota, notb
2113 // with
2114 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002115 instruction->ReplaceInput(left->InputAt(0), 0);
2116 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002117 left->GetBlock()->RemoveInstruction(left);
2118 right->GetBlock()->RemoveInstruction(right);
2119 RecordSimplification();
2120 return;
2121 }
2122
Anton Kirilove14dc862016-05-13 17:56:15 +01002123 if (TryReplaceWithRotate(instruction)) {
2124 return;
2125 }
2126
2127 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2128 // so no need to return.
2129 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002130}
2131
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002132void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2133 HInstruction* argument = instruction->InputAt(1);
2134 HInstruction* receiver = instruction->InputAt(0);
2135 if (receiver == argument) {
2136 // Because String.equals is an instance call, the receiver is
2137 // a null check if we don't know it's null. The argument however, will
2138 // be the actual object. So we cannot end up in a situation where both
2139 // are equal but could be null.
2140 DCHECK(CanEnsureNotNullAt(argument, instruction));
2141 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2142 instruction->GetBlock()->RemoveInstruction(instruction);
2143 } else {
2144 StringEqualsOptimizations optimizations(instruction);
2145 if (CanEnsureNotNullAt(argument, instruction)) {
2146 optimizations.SetArgumentNotNull();
2147 }
2148 ScopedObjectAccess soa(Thread::Current());
2149 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2150 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2151 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002152 } else if (kUseReadBarrier) {
2153 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002154 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2155 // Object.equals() can be devirtualized to String.equals().
2156 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002157 Runtime* runtime = Runtime::Current();
2158 // For AOT, we always assume that the boot image shall contain the String.class and
2159 // we do not need a read barrier for boot image classes as they are non-moveable.
2160 // For JIT, check if we actually have a boot image; if we do, the String.class
2161 // should also be non-moveable.
2162 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2163 DCHECK(runtime->IsAotCompiler() ||
2164 !runtime->GetHeap()->IsMovableObject(
2165 instruction->GetResolvedMethod()->GetDeclaringClass()));
2166 optimizations.SetNoReadBarrierForStringClass();
2167 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002168 }
2169 }
2170}
2171
Roland Levillain22c49222016-03-18 14:04:28 +00002172void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2173 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002174 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002175 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002176 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002177 HInstruction* value = invoke->InputAt(0);
2178 HInstruction* distance = invoke->InputAt(1);
2179 // Replace the invoke with an HRor.
2180 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002181 // Unconditionally set the type of the negated distance to `int`,
2182 // as shift and rotate operations expect a 32-bit (or narrower)
2183 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002184 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002185 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2186 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002187 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002188 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2189 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002190 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002191 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2192 clinit->GetBlock()->RemoveInstruction(clinit);
2193 HInstruction* ldclass = clinit->InputAt(0);
2194 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2195 ldclass->GetBlock()->RemoveInstruction(ldclass);
2196 }
2197 }
2198}
2199
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002200static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2201 if (potential_length->IsArrayLength()) {
2202 return potential_length->InputAt(0) == potential_array;
2203 }
2204
2205 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002206 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002207 }
2208
2209 return false;
2210}
2211
2212void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2213 HInstruction* source = instruction->InputAt(0);
2214 HInstruction* destination = instruction->InputAt(2);
2215 HInstruction* count = instruction->InputAt(4);
2216 SystemArrayCopyOptimizations optimizations(instruction);
2217 if (CanEnsureNotNullAt(source, instruction)) {
2218 optimizations.SetSourceIsNotNull();
2219 }
2220 if (CanEnsureNotNullAt(destination, instruction)) {
2221 optimizations.SetDestinationIsNotNull();
2222 }
2223 if (destination == source) {
2224 optimizations.SetDestinationIsSource();
2225 }
2226
2227 if (IsArrayLengthOf(count, source)) {
2228 optimizations.SetCountIsSourceLength();
2229 }
2230
2231 if (IsArrayLengthOf(count, destination)) {
2232 optimizations.SetCountIsDestinationLength();
2233 }
2234
2235 {
2236 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002237 DataType::Type source_component_type = DataType::Type::kVoid;
2238 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002239 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2240 if (destination_rti.IsValid()) {
2241 if (destination_rti.IsObjectArray()) {
2242 if (destination_rti.IsExact()) {
2243 optimizations.SetDoesNotNeedTypeCheck();
2244 }
2245 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002246 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002247 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002248 destination_component_type = DataTypeFromPrimitive(
2249 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002250 optimizations.SetDestinationIsPrimitiveArray();
2251 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2252 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002253 }
2254 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002255 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2256 if (source_rti.IsValid()) {
2257 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2258 optimizations.SetDoesNotNeedTypeCheck();
2259 }
2260 if (source_rti.IsPrimitiveArrayClass()) {
2261 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002262 source_component_type = DataTypeFromPrimitive(
2263 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002264 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2265 optimizations.SetSourceIsNonPrimitiveArray();
2266 }
2267 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002268 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002269 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002270 (source_component_type == destination_component_type)) {
2271 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2272 PointerSize image_size = class_linker->GetImagePointerSize();
2273 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2274 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2275 ArtMethod* method = nullptr;
2276 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002277 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002278 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002279 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002280 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002281 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002282 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002283 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002284 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002285 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002286 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002287 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002288 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002289 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002290 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002291 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002292 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002293 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002294 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002295 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002296 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002297 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002298 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002299 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002300 break;
2301 default:
2302 LOG(FATAL) << "Unreachable";
2303 }
2304 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002305 DCHECK(method->IsStatic());
2306 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002307 invoke->SetResolvedMethod(method);
2308 // Sharpen the new invoke. Note that we do not update the dex method index of
2309 // the invoke, as we would need to look it up in the current dex file, and it
2310 // is unlikely that it exists. The most usual situation for such typed
2311 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002312 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002313 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002314 }
2315}
2316
Roland Levillaina5c4a402016-03-15 15:02:50 +00002317void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2318 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002319 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002320 DCHECK(invoke->IsInvokeStaticOrDirect());
2321 uint32_t dex_pc = invoke->GetDexPc();
2322 HInstruction* left = invoke->InputAt(0);
2323 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002324 if (!is_signum) {
2325 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002326 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002327 right = GetGraph()->GetLongConstant(0);
2328 } else {
2329 right = GetGraph()->GetIntConstant(0);
2330 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002331 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002332 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2333 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2334}
2335
Aart Bik75a38b22016-02-17 10:41:50 -08002336void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2337 DCHECK(invoke->IsInvokeStaticOrDirect());
2338 uint32_t dex_pc = invoke->GetDexPc();
2339 // IsNaN(x) is the same as x != x.
2340 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002341 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002342 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002343 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2344}
2345
Aart Bik2a6aad92016-02-25 11:32:32 -08002346void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2347 DCHECK(invoke->IsInvokeStaticOrDirect());
2348 uint32_t dex_pc = invoke->GetDexPc();
2349 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002350 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002351 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2352 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002353 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002354 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2355 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2356 kNeedsEnvironmentOrCache,
2357 kNoSideEffects,
2358 kNoThrow);
2359 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002360 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002361 nan = GetGraph()->GetIntConstant(0x7fc00000);
2362 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2363 kNeedsEnvironmentOrCache,
2364 kNoSideEffects,
2365 kNoThrow);
2366 }
2367 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002368 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002369 condition->SetBias(ComparisonBias::kLtBias);
2370 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2371 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002372 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002373 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2374 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2375}
2376
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002377void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2378 HInstruction* str = invoke->InputAt(0);
2379 HInstruction* index = invoke->InputAt(1);
2380 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002381 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002382 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2383 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002384 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002385 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002386 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002387 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002388 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002389 HArrayGet* array_get = new (allocator) HArrayGet(str,
2390 bounds_check,
2391 DataType::Type::kUint16,
2392 SideEffects::None(), // Strings are immutable.
2393 dex_pc,
2394 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002395 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2396 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2397 GetGraph()->SetHasBoundsChecks(true);
2398}
2399
Vladimir Markodce016e2016-04-28 13:10:02 +01002400void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2401 HInstruction* str = invoke->InputAt(0);
2402 uint32_t dex_pc = invoke->GetDexPc();
2403 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2404 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002405 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002406 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002407 HInstruction* replacement;
2408 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2409 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2410 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2411 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002412 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002413 replacement = equal;
2414 } else {
2415 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2416 replacement = length;
2417 }
2418 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2419}
2420
Vladimir Marko6fa44042018-03-19 18:42:49 +00002421void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2422 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2423 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2424 if (invoke->InputAt(0)->IsLoadString()) {
2425 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
2426 const DexFile& dex_file = load_string->GetDexFile();
2427 uint32_t utf16_length;
2428 const char* data =
2429 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2430 if (utf16_length == 0) {
2431 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2432 invoke->GetBlock()->RemoveInstruction(invoke);
2433 RecordSimplification();
2434 return;
2435 }
2436 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2437 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2438 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2439 uint32_t c = GetUtf16FromUtf8(&data);
2440 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2441 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2442 uint32_t dex_pc = invoke->GetDexPc();
2443 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2444 HEqual* equal =
2445 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2446 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2447 HSelect* result = new (allocator) HSelect(equal,
2448 GetGraph()->GetIntConstant(0),
2449 GetGraph()->GetIntConstant(-1),
2450 dex_pc);
2451 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2452 RecordSimplification();
2453 return;
2454 }
2455 }
2456}
2457
Aart Bikff7d89c2016-11-07 08:49:28 -08002458// This method should only be used on intrinsics whose sole way of throwing an
2459// exception is raising a NPE when the nth argument is null. If that argument
2460// is provably non-null, we can clear the flag.
2461void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2462 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002463 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002464 invoke->SetCanThrow(false);
2465 }
2466}
2467
Aart Bik71bf7b42016-11-16 10:17:46 -08002468// Methods that return "this" can replace the returned value with the receiver.
2469void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2470 if (invoke->HasUses()) {
2471 HInstruction* receiver = invoke->InputAt(0);
2472 invoke->ReplaceWith(receiver);
2473 RecordSimplification();
2474 }
2475}
2476
2477// Helper method for StringBuffer escape analysis.
2478static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2479 if (user->IsInvokeStaticOrDirect()) {
2480 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002481 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2482 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002483 user->InputAt(0) == reference;
2484 } else if (user->IsInvokeVirtual()) {
2485 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2486 case Intrinsics::kStringBufferLength:
2487 case Intrinsics::kStringBufferToString:
2488 DCHECK_EQ(user->InputAt(0), reference);
2489 return true;
2490 case Intrinsics::kStringBufferAppend:
2491 // Returns "this", so only okay if no further uses.
2492 DCHECK_EQ(user->InputAt(0), reference);
2493 DCHECK_NE(user->InputAt(1), reference);
2494 return !user->HasUses();
2495 default:
2496 break;
2497 }
2498 }
2499 return false;
2500}
2501
2502// Certain allocation intrinsics are not removed by dead code elimination
2503// because of potentially throwing an OOM exception or other side effects.
2504// This method removes such intrinsics when special circumstances allow.
2505void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2506 if (!invoke->HasUses()) {
2507 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2508 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2509 // call does not escape since only thread-local synchronization may be removed.
2510 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2511 HInstruction* receiver = invoke->InputAt(0);
2512 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2513 invoke->GetBlock()->RemoveInstruction(invoke);
2514 RecordSimplification();
2515 }
2516 }
2517}
2518
Vladimir Markoca6fff82017-10-03 14:49:14 +01002519void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2520 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002521 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002522 HMemoryBarrier* mem_barrier =
2523 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002524 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2525}
2526
Aart Bik1f8d51b2018-02-15 10:42:37 -08002527void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2528 DCHECK(invoke->IsInvokeStaticOrDirect());
2529 HMin* min = new (GetGraph()->GetAllocator())
2530 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2531 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2532}
2533
2534void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2535 DCHECK(invoke->IsInvokeStaticOrDirect());
2536 HMax* max = new (GetGraph()->GetAllocator())
2537 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2538 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2539}
2540
Aart Bik3dad3412018-02-28 12:01:46 -08002541void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2542 DCHECK(invoke->IsInvokeStaticOrDirect());
2543 HAbs* abs = new (GetGraph()->GetAllocator())
2544 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2545 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2546}
2547
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002548void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002549 switch (instruction->GetIntrinsic()) {
2550 case Intrinsics::kStringEquals:
2551 SimplifyStringEquals(instruction);
2552 break;
2553 case Intrinsics::kSystemArrayCopy:
2554 SimplifySystemArrayCopy(instruction);
2555 break;
2556 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002557 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002558 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002559 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002560 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002561 break;
2562 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002563 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002564 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002565 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002566 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002567 break;
2568 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002569 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002570 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002571 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002572 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002573 break;
2574 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002575 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002576 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002577 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002578 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002579 break;
2580 case Intrinsics::kFloatIsNaN:
2581 case Intrinsics::kDoubleIsNaN:
2582 SimplifyIsNaN(instruction);
2583 break;
2584 case Intrinsics::kFloatFloatToIntBits:
2585 case Intrinsics::kDoubleDoubleToLongBits:
2586 SimplifyFP2Int(instruction);
2587 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002588 case Intrinsics::kStringCharAt:
2589 SimplifyStringCharAt(instruction);
2590 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002591 case Intrinsics::kStringIsEmpty:
2592 case Intrinsics::kStringLength:
2593 SimplifyStringIsEmptyOrLength(instruction);
2594 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00002595 case Intrinsics::kStringIndexOf:
2596 case Intrinsics::kStringIndexOfAfter:
2597 SimplifyStringIndexOf(instruction);
2598 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002599 case Intrinsics::kStringStringIndexOf:
2600 case Intrinsics::kStringStringIndexOfAfter:
2601 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2602 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002603 case Intrinsics::kStringBufferAppend:
2604 case Intrinsics::kStringBuilderAppend:
2605 SimplifyReturnThis(instruction);
2606 break;
2607 case Intrinsics::kStringBufferToString:
2608 case Intrinsics::kStringBuilderToString:
2609 SimplifyAllocationIntrinsic(instruction);
2610 break;
Aart Bik11932592016-03-08 12:42:25 -08002611 case Intrinsics::kUnsafeLoadFence:
2612 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2613 break;
2614 case Intrinsics::kUnsafeStoreFence:
2615 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2616 break;
2617 case Intrinsics::kUnsafeFullFence:
2618 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2619 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002620 case Intrinsics::kVarHandleFullFence:
2621 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2622 break;
2623 case Intrinsics::kVarHandleAcquireFence:
2624 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2625 break;
2626 case Intrinsics::kVarHandleReleaseFence:
2627 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2628 break;
2629 case Intrinsics::kVarHandleLoadLoadFence:
2630 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2631 break;
2632 case Intrinsics::kVarHandleStoreStoreFence:
2633 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2634 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002635 case Intrinsics::kMathMinIntInt:
2636 SimplifyMin(instruction, DataType::Type::kInt32);
2637 break;
2638 case Intrinsics::kMathMinLongLong:
2639 SimplifyMin(instruction, DataType::Type::kInt64);
2640 break;
2641 case Intrinsics::kMathMinFloatFloat:
2642 SimplifyMin(instruction, DataType::Type::kFloat32);
2643 break;
2644 case Intrinsics::kMathMinDoubleDouble:
2645 SimplifyMin(instruction, DataType::Type::kFloat64);
2646 break;
2647 case Intrinsics::kMathMaxIntInt:
2648 SimplifyMax(instruction, DataType::Type::kInt32);
2649 break;
2650 case Intrinsics::kMathMaxLongLong:
2651 SimplifyMax(instruction, DataType::Type::kInt64);
2652 break;
2653 case Intrinsics::kMathMaxFloatFloat:
2654 SimplifyMax(instruction, DataType::Type::kFloat32);
2655 break;
2656 case Intrinsics::kMathMaxDoubleDouble:
2657 SimplifyMax(instruction, DataType::Type::kFloat64);
2658 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002659 case Intrinsics::kMathAbsInt:
2660 SimplifyAbs(instruction, DataType::Type::kInt32);
2661 break;
2662 case Intrinsics::kMathAbsLong:
2663 SimplifyAbs(instruction, DataType::Type::kInt64);
2664 break;
2665 case Intrinsics::kMathAbsFloat:
2666 SimplifyAbs(instruction, DataType::Type::kFloat32);
2667 break;
2668 case Intrinsics::kMathAbsDouble:
2669 SimplifyAbs(instruction, DataType::Type::kFloat64);
2670 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002671 default:
2672 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002673 }
2674}
2675
Aart Bikbb245d12015-10-19 11:05:03 -07002676void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2677 HInstruction* cond = deoptimize->InputAt(0);
2678 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002679 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002680 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002681 if (deoptimize->GuardsAnInput()) {
2682 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2683 }
Aart Bikbb245d12015-10-19 11:05:03 -07002684 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2685 } else {
2686 // Always deopt.
2687 }
2688 }
2689}
2690
Anton Kirilove14dc862016-05-13 17:56:15 +01002691// Replace code looking like
2692// OP y, x, const1
2693// OP z, y, const2
2694// with
2695// OP z, x, const3
2696// where OP is both an associative and a commutative operation.
2697bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2698 HBinaryOperation* instruction) {
2699 DCHECK(instruction->IsCommutative());
2700
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002701 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002702 return false;
2703 }
2704
2705 HInstruction* left = instruction->GetLeft();
2706 HInstruction* right = instruction->GetRight();
2707 // Variable names as described above.
2708 HConstant* const2;
2709 HBinaryOperation* y;
2710
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002711 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002712 const2 = right->AsConstant();
2713 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002714 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002715 const2 = left->AsConstant();
2716 y = right->AsBinaryOperation();
2717 } else {
2718 // The node does not match the pattern.
2719 return false;
2720 }
2721
2722 // If `y` has more than one use, we do not perform the optimization
2723 // because it might increase code size (e.g. if the new constant is
2724 // no longer encodable as an immediate operand in the target ISA).
2725 if (!y->HasOnlyOneNonEnvironmentUse()) {
2726 return false;
2727 }
2728
2729 // GetConstantRight() can return both left and right constants
2730 // for commutative operations.
2731 HConstant* const1 = y->GetConstantRight();
2732 if (const1 == nullptr) {
2733 return false;
2734 }
2735
2736 instruction->ReplaceInput(const1, 0);
2737 instruction->ReplaceInput(const2, 1);
2738 HConstant* const3 = instruction->TryStaticEvaluation();
2739 DCHECK(const3 != nullptr);
2740 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2741 instruction->ReplaceInput(const3, 1);
2742 RecordSimplification();
2743 return true;
2744}
2745
2746static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2747 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2748}
2749
2750// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002751static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002752 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002753 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002754 return HAdd::Compute<int32_t>(x, y);
2755 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002756 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002757 return HAdd::Compute<int64_t>(x, y);
2758 }
2759}
2760
2761// Helper function that handles the child classes of HConstant
2762// and returns an integer with the appropriate sign.
2763static int64_t GetValue(HConstant* constant, bool is_negated) {
2764 int64_t ret = Int64FromConstant(constant);
2765 return is_negated ? -ret : ret;
2766}
2767
2768// Replace code looking like
2769// OP1 y, x, const1
2770// OP2 z, y, const2
2771// with
2772// OP3 z, x, const3
2773// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2774bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2775 HBinaryOperation* instruction) {
2776 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2777
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002778 DataType::Type type = instruction->GetType();
2779 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002780 return false;
2781 }
2782
2783 HInstruction* left = instruction->GetLeft();
2784 HInstruction* right = instruction->GetRight();
2785 // Variable names as described above.
2786 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2787 if (const2 == nullptr) {
2788 return false;
2789 }
2790
2791 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2792 ? left->AsBinaryOperation()
2793 : AsAddOrSub(right);
2794 // If y has more than one use, we do not perform the optimization because
2795 // it might increase code size (e.g. if the new constant is no longer
2796 // encodable as an immediate operand in the target ISA).
2797 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2798 return false;
2799 }
2800
2801 left = y->GetLeft();
2802 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2803 if (const1 == nullptr) {
2804 return false;
2805 }
2806
2807 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2808 // If both inputs are constants, let the constant folding pass deal with it.
2809 if (x->IsConstant()) {
2810 return false;
2811 }
2812
2813 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2814 int64_t const2_val = GetValue(const2, is_const2_negated);
2815 bool is_y_negated = (y == right) && instruction->IsSub();
2816 right = y->GetRight();
2817 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2818 int64_t const1_val = GetValue(const1, is_const1_negated);
2819 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2820 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2821 HBasicBlock* block = instruction->GetBlock();
2822 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002823 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002824 HInstruction* z;
2825
2826 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002827 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002828 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002829 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002830 }
2831
2832 block->ReplaceAndRemoveInstructionWith(instruction, z);
2833 RecordSimplification();
2834 return true;
2835}
2836
Lena Djokicbc5460b2017-07-20 16:07:36 +02002837void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2838 if (TryCombineVecMultiplyAccumulate(instruction)) {
2839 RecordSimplification();
2840 }
2841}
2842
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002843} // namespace art