blob: 0fe16725f3df7dbf72e1929b83ce32ea639e34f8 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Andreas Gampec6ea7d02017-02-01 16:46:28 -080019#include "art_method-inl.h"
20#include "class_linker-inl.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010021#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080022#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010023#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070025#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070026#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027
Nicolas Geoffray3c049742014-09-24 18:10:46 +010028namespace art {
29
Artem Serovcced8ba2017-07-19 18:18:09 +010030// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
31// is replaced with its copy if it is clonable.
32static constexpr bool kTestInstructionClonerExhaustively = false;
33
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010034class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000035 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000036 InstructionSimplifierVisitor(HGraph* graph,
37 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010038 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000039 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010040 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000041 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010042 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010043 stats_(stats) {}
44
Aart Bik24773202018-04-26 10:28:51 -070045 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000046
47 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010048 void RecordSimplification() {
49 simplification_occurred_ = true;
50 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000051 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010052 }
53
Scott Wakeling40a04bf2015-12-11 09:50:36 +000054 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55 bool TryReplaceWithRotate(HBinaryOperation* instruction);
56 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
57 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59
Alexandre Rames188d4312015-04-09 18:30:21 +010060 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000061 // `op` should be either HOr or HAnd.
62 // De Morgan's laws:
63 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
64 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010065 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
66 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020067 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010068
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitShift(HBinaryOperation* shift);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000070 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010071 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
72 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010073 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
74 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000075 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000076 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000077 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080078 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000079 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Aart Bikc6eec4b2018-03-29 17:22:00 -070080 void VisitAbs(HAbs* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000081 void VisitAdd(HAdd* instruction) OVERRIDE;
82 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040083 void VisitCondition(HCondition* instruction) OVERRIDE;
84 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
85 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
86 void VisitLessThan(HLessThan* condition) OVERRIDE;
87 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060088 void VisitBelow(HBelow* condition) OVERRIDE;
89 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
90 void VisitAbove(HAbove* condition) OVERRIDE;
91 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitDiv(HDiv* instruction) OVERRIDE;
93 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010094 void VisitNeg(HNeg* instruction) OVERRIDE;
95 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000096 void VisitOr(HOr* instruction) OVERRIDE;
97 void VisitShl(HShl* instruction) OVERRIDE;
98 void VisitShr(HShr* instruction) OVERRIDE;
99 void VisitSub(HSub* instruction) OVERRIDE;
100 void VisitUShr(HUShr* instruction) OVERRIDE;
101 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +0000102 void VisitSelect(HSelect* select) OVERRIDE;
103 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100104 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100105 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700106 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200107 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100108
109 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000110
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100111 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100112 void SimplifySystemArrayCopy(HInvoke* invoke);
113 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100114 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800115 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800116 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100117 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100118 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800119 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800120 void SimplifyReturnThis(HInvoke* invoke);
121 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800122 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800123 void SimplifyMin(HInvoke* invoke, DataType::Type type);
124 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800125 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100126
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000127 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100128 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000129 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100130 bool simplification_occurred_ = false;
131 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700132 // We ensure we do not loop infinitely. The value should not be too high, since that
133 // would allow looping around the same basic block too many times. The value should
134 // not be too low either, however, since we want to allow revisiting a basic block
135 // with many statements and simplifications at least once.
136 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000137};
138
Aart Bik24773202018-04-26 10:28:51 -0700139bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100140 if (kTestInstructionClonerExhaustively) {
141 CloneAndReplaceInstructionVisitor visitor(graph_);
142 visitor.VisitReversePostOrder();
143 }
144
Vladimir Marko65979462017-05-19 17:25:12 +0100145 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700146 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100147}
148
Aart Bik24773202018-04-26 10:28:51 -0700149bool InstructionSimplifierVisitor::Run() {
150 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100151 // Iterate in reverse post order to open up more simplifications to users
152 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100153 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100154 // The simplification of an instruction to another instruction may yield
155 // possibilities for other simplifications. So although we perform a reverse
156 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100157 do {
158 simplification_occurred_ = false;
159 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700160 if (simplification_occurred_) {
161 didSimplify = true;
162 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100163 } while (simplification_occurred_ &&
164 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100165 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100166 }
Aart Bik24773202018-04-26 10:28:51 -0700167 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100168}
169
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000170namespace {
171
172bool AreAllBitsSet(HConstant* constant) {
173 return Int64FromConstant(constant) == -1;
174}
175
176} // namespace
177
Alexandre Rames188d4312015-04-09 18:30:21 +0100178// Returns true if the code was simplified to use only one negation operation
179// after the binary operation instead of one on each of the inputs.
180bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
181 DCHECK(binop->IsAdd() || binop->IsSub());
182 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
183 HNeg* left_neg = binop->GetLeft()->AsNeg();
184 HNeg* right_neg = binop->GetRight()->AsNeg();
185 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
186 !right_neg->HasOnlyOneNonEnvironmentUse()) {
187 return false;
188 }
189 // Replace code looking like
190 // NEG tmp1, a
191 // NEG tmp2, b
192 // ADD dst, tmp1, tmp2
193 // with
194 // ADD tmp, a, b
195 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600196 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
197 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
198 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100199 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600200 return false;
201 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100202 binop->ReplaceInput(left_neg->GetInput(), 0);
203 binop->ReplaceInput(right_neg->GetInput(), 1);
204 left_neg->GetBlock()->RemoveInstruction(left_neg);
205 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100206 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100207 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
208 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
209 RecordSimplification();
210 return true;
211}
212
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000213bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
214 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100215 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000216 HInstruction* left = op->GetLeft();
217 HInstruction* right = op->GetRight();
218
219 // We can apply De Morgan's laws if both inputs are Not's and are only used
220 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000221 if (((left->IsNot() && right->IsNot()) ||
222 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000223 left->HasOnlyOneNonEnvironmentUse() &&
224 right->HasOnlyOneNonEnvironmentUse()) {
225 // Replace code looking like
226 // NOT nota, a
227 // NOT notb, b
228 // AND dst, nota, notb (respectively OR)
229 // with
230 // OR or, a, b (respectively AND)
231 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* src_left = left->InputAt(0);
233 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000234 uint32_t dex_pc = op->GetDexPc();
235
236 // Remove the negations on the inputs.
237 left->ReplaceWith(src_left);
238 right->ReplaceWith(src_right);
239 left->GetBlock()->RemoveInstruction(left);
240 right->GetBlock()->RemoveInstruction(right);
241
242 // Replace the `HAnd` or `HOr`.
243 HBinaryOperation* hbin;
244 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100245 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000246 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100247 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000248 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000249 HInstruction* hnot;
250 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100251 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000252 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100253 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000254 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000255
256 op->GetBlock()->InsertInstructionBefore(hbin, op);
257 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
258
259 RecordSimplification();
260 return true;
261 }
262
263 return false;
264}
265
Lena Djokicbc5460b2017-07-20 16:07:36 +0200266bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100267 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200268 InstructionSet isa = codegen_->GetInstructionSet();
269 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000270 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100271 if (!(type == DataType::Type::kUint8 ||
272 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100273 type == DataType::Type::kUint16 ||
274 type == DataType::Type::kInt16 ||
275 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200276 return false;
277 }
278 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000279 case InstructionSet::kMips:
280 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100281 if (!(type == DataType::Type::kUint8 ||
282 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100283 type == DataType::Type::kUint16 ||
284 type == DataType::Type::kInt16 ||
285 type == DataType::Type::kInt32 ||
286 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200287 return false;
288 }
289 break;
290 default:
291 return false;
292 }
293
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100294 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200295
296 if (mul->HasOnlyOneNonEnvironmentUse()) {
297 HInstruction* use = mul->GetUses().front().GetUser();
298 if (use->IsVecAdd() || use->IsVecSub()) {
299 // Replace code looking like
300 // VECMUL tmp, x, y
301 // VECADD/SUB dst, acc, tmp
302 // with
303 // VECMULACC dst, acc, x, y
304 // Note that we do not want to (unconditionally) perform the merge when the
305 // multiplication has multiple uses and it can be merged in all of them.
306 // Multiple uses could happen on the same control-flow path, and we would
307 // then increase the amount of work. In the future we could try to evaluate
308 // whether all uses are on different control-flow paths (using dominance and
309 // reverse-dominance information) and only perform the merge when they are.
310 HInstruction* accumulator = nullptr;
311 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
312 HInstruction* binop_left = binop->GetLeft();
313 HInstruction* binop_right = binop->GetRight();
314 // This is always true since the `HVecMul` has only one use (which is checked above).
315 DCHECK_NE(binop_left, binop_right);
316 if (binop_right == mul) {
317 accumulator = binop_left;
318 } else if (use->IsVecAdd()) {
319 DCHECK_EQ(binop_left, mul);
320 accumulator = binop_right;
321 }
322
323 HInstruction::InstructionKind kind =
324 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
325 if (accumulator != nullptr) {
326 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100327 new (allocator) HVecMultiplyAccumulate(allocator,
328 kind,
329 accumulator,
330 mul->GetLeft(),
331 mul->GetRight(),
332 binop->GetPackedType(),
333 binop->GetVectorLength(),
334 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200335
336 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
337 DCHECK(!mul->HasUses());
338 mul->GetBlock()->RemoveInstruction(mul);
339 return true;
340 }
341 }
342 }
343
344 return false;
345}
346
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000347void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
348 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100349 HInstruction* shift_amount = instruction->GetRight();
350 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000351
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100352 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100353 ? kMaxLongShiftDistance
354 : kMaxIntShiftDistance;
355
356 if (shift_amount->IsConstant()) {
357 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700358 int64_t masked_cst = cst & implicit_mask;
359 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400360 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100361 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400362 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100363 // value
364 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400365 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100366 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100367 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700368 } else if (masked_cst != cst) {
369 // Replace code looking like
370 // SHL dst, value, cst
371 // where cst exceeds maximum distance with the equivalent
372 // SHL dst, value, cst & implicit_mask
373 // (as defined by shift semantics). This ensures other
374 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100375 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700376 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
377 RecordSimplification();
378 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100379 }
380 }
381
382 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100383 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
384 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100385 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 // AND adjusted_shift, shift, <superset of implicit mask>
387 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
388 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
389 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100390 // with
391 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100392 if (shift_amount->IsAnd() ||
393 shift_amount->IsOr() ||
394 shift_amount->IsXor() ||
395 shift_amount->IsAdd() ||
396 shift_amount->IsSub()) {
397 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
398 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
399 HConstant* mask = bin_op->GetConstantRight();
400 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
401 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100402 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100403 return;
404 }
405 } else if (shift_amount->IsTypeConversion()) {
406 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
407 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
408 // Non-integral and 64-bit source types require an explicit type conversion.
409 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
410 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
411 RecordSimplification();
412 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400413 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000414 }
415}
416
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000417static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
418 return (sub->GetRight() == other &&
419 sub->GetLeft()->IsConstant() &&
420 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
421}
422
423bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
424 HUShr* ushr,
425 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000426 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100427 HRor* ror =
428 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000429 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
430 if (!ushr->HasUses()) {
431 ushr->GetBlock()->RemoveInstruction(ushr);
432 }
433 if (!ushr->GetRight()->HasUses()) {
434 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
435 }
436 if (!shl->HasUses()) {
437 shl->GetBlock()->RemoveInstruction(shl);
438 }
439 if (!shl->GetRight()->HasUses()) {
440 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
441 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100442 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000443 return true;
444}
445
446// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
447bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000448 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
449 HInstruction* left = op->GetLeft();
450 HInstruction* right = op->GetRight();
451 // If we have an UShr and a Shl (in either order).
452 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
453 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
454 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100455 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000456 if (ushr->GetType() == shl->GetType() &&
457 ushr->GetLeft() == shl->GetLeft()) {
458 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
459 // Shift distances are both constant, try replacing with Ror if they
460 // add up to the register size.
461 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
462 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
463 // Shift distances are potentially of the form x and (reg_size - x).
464 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
465 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
466 // Shift distances are potentially of the form d and -d.
467 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
468 }
469 }
470 }
471 return false;
472}
473
474// Try replacing code looking like (x >>> #rdist OP x << #ldist):
475// UShr dst, x, #rdist
476// Shl tmp, x, #ldist
477// OP dst, dst, tmp
478// or like (x >>> #rdist OP x << #-ldist):
479// UShr dst, x, #rdist
480// Shl tmp, x, #-ldist
481// OP dst, dst, tmp
482// with
483// Ror dst, x, #rdist
484bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
485 HUShr* ushr,
486 HShl* shl) {
487 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100488 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000489 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
490 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
491 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
492 ReplaceRotateWithRor(op, ushr, shl);
493 return true;
494 }
495 return false;
496}
497
498// Replace code looking like (x >>> -d OP x << d):
499// Neg neg, d
500// UShr dst, x, neg
501// Shl tmp, x, d
502// OP dst, dst, tmp
503// with
504// Neg neg, d
505// Ror dst, x, neg
506// *** OR ***
507// Replace code looking like (x >>> d OP x << -d):
508// UShr dst, x, d
509// Neg neg, d
510// Shl tmp, x, neg
511// OP dst, dst, tmp
512// with
513// Ror dst, x, d
514bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
515 HUShr* ushr,
516 HShl* shl) {
517 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
518 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
519 bool neg_is_left = shl->GetRight()->IsNeg();
520 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
521 // And the shift distance being negated is the distance being shifted the other way.
522 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
523 ReplaceRotateWithRor(op, ushr, shl);
524 }
525 return false;
526}
527
528// Try replacing code looking like (x >>> d OP x << (#bits - d)):
529// UShr dst, x, d
530// Sub ld, #bits, d
531// Shl tmp, x, ld
532// OP dst, dst, tmp
533// with
534// Ror dst, x, d
535// *** OR ***
536// Replace code looking like (x >>> (#bits - d) OP x << d):
537// Sub rd, #bits, d
538// UShr dst, x, rd
539// Shl tmp, x, d
540// OP dst, dst, tmp
541// with
542// Neg neg, d
543// Ror dst, x, neg
544bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
545 HUShr* ushr,
546 HShl* shl) {
547 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
548 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100549 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000550 HInstruction* shl_shift = shl->GetRight();
551 HInstruction* ushr_shift = ushr->GetRight();
552 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
553 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
554 return ReplaceRotateWithRor(op, ushr, shl);
555 }
556 return false;
557}
558
Calin Juravle10e244f2015-01-26 18:54:32 +0000559void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
560 HInstruction* obj = null_check->InputAt(0);
561 if (!obj->CanBeNull()) {
562 null_check->ReplaceWith(obj);
563 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000564 if (stats_ != nullptr) {
565 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
566 }
567 }
568}
569
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100570bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
571 if (!input->CanBeNull()) {
572 return true;
573 }
574
Vladimir Marko46817b82016-03-29 12:21:58 +0100575 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
576 HInstruction* user = use.GetUser();
577 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100578 return true;
579 }
580 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100581
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100582 return false;
583}
584
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100585// Returns whether doing a type test between the class of `object` against `klass` has
586// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000587static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
588 HInstruction* object,
589 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000590 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
591 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
592 ScopedObjectAccess soa(Thread::Current());
593 if (!obj_rti.IsValid()) {
594 // We run the simplifier before the reference type propagation so type info might not be
595 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000597 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100598
Calin Juravle98893e12015-10-02 21:05:03 +0100599 if (!class_rti.IsValid()) {
600 // Happens when the loaded class is unresolved.
601 return false;
602 }
603 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000604 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100605 *outcome = true;
606 return true;
607 } else if (obj_rti.IsExact()) {
608 // The test failed at compile time so will also fail at runtime.
609 *outcome = false;
610 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100611 } else if (!class_rti.IsInterface()
612 && !obj_rti.IsInterface()
613 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100614 // Different type hierarchy. The test will fail.
615 *outcome = false;
616 return true;
617 }
618 return false;
619}
620
621void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
622 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000623 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
624 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100625 // If we need to perform an access check we cannot remove the instruction.
626 return;
627 }
628
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100629 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100630 check_cast->ClearMustDoNullCheck();
631 }
632
633 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000634 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700635 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100636 return;
637 }
638
Vladimir Markoa65ed302016-03-14 21:21:29 +0000639 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
640 // the return value check with the `outcome` check, b/27651442 .
641 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000642 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100643 if (outcome) {
644 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700645 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000646 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
647 HLoadClass* load_class = check_cast->GetTargetClass();
648 if (!load_class->HasUses()) {
649 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
650 // However, here we know that it cannot because the checkcast was successfull, hence
651 // the class was already loaded.
652 load_class->GetBlock()->RemoveInstruction(load_class);
653 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700654 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100655 } else {
656 // Don't do anything for exceptional cases for now. Ideally we should remove
657 // all instructions and blocks this instruction dominates.
658 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000659 }
660}
661
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100662void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100663 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000664 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
665 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100666 // If we need to perform an access check we cannot remove the instruction.
667 return;
668 }
669
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100670 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100671 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100673 instruction->ClearMustDoNullCheck();
674 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100675
676 HGraph* graph = GetGraph();
677 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000678 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100679 instruction->ReplaceWith(graph->GetIntConstant(0));
680 instruction->GetBlock()->RemoveInstruction(instruction);
681 RecordSimplification();
682 return;
683 }
684
Vladimir Marko24bd8952016-03-15 10:40:33 +0000685 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
686 // the return value check with the `outcome` check, b/27651442 .
687 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000688 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000689 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100690 if (outcome && can_be_null) {
691 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100692 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100693 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
694 instruction->ReplaceWith(test);
695 } else {
696 // We've statically determined the result of the instanceof.
697 instruction->ReplaceWith(graph->GetIntConstant(outcome));
698 }
699 RecordSimplification();
700 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000701 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
702 HLoadClass* load_class = instruction->GetTargetClass();
703 if (!load_class->HasUses()) {
704 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
705 // However, here we know that it cannot because the instanceof check was successfull, hence
706 // the class was already loaded.
707 load_class->GetBlock()->RemoveInstruction(load_class);
708 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700709 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100710 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100711}
712
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100713void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100714 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100715 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100716 instruction->ClearValueCanBeNull();
717 }
718}
719
720void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100721 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100722 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100723 instruction->ClearValueCanBeNull();
724 }
725}
726
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100727static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600728 HInstruction *lhs = cond->InputAt(0);
729 HInstruction *rhs = cond->InputAt(1);
730 switch (cond->GetKind()) {
731 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100732 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600733 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100734 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600735 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100736 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600737 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100738 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600739 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100740 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600741 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100742 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600743 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100744 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600745 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100746 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600747 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100748 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600749 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100750 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600751 default:
752 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
753 }
754 return nullptr;
755}
756
Aart Bik2767f4b2016-10-28 15:03:53 -0700757static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100758 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700759 return true; // input has direct boolean type
760 } else if (cmp->GetUses().HasExactlyOneElement()) {
761 // Comparison also has boolean type if both its input and the instruction
762 // itself feed into the same phi node.
763 HInstruction* user = cmp->GetUses().front().GetUser();
764 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
765 }
766 return false;
767}
768
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000769void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100770 HInstruction* input_const = equal->GetConstantRight();
771 if (input_const != nullptr) {
772 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700773 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100774 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100775 // We are comparing the boolean to a constant which is of type int and can
776 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000777 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100778 // Replace (bool_value == true) with bool_value
779 equal->ReplaceWith(input_value);
780 block->RemoveInstruction(equal);
781 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000782 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700783 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500784 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
785 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100786 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100787 } else {
788 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
789 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
790 block->RemoveInstruction(equal);
791 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100792 }
Mark Mendellc4701932015-04-10 13:18:51 -0400793 } else {
794 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100795 }
Mark Mendellc4701932015-04-10 13:18:51 -0400796 } else {
797 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100798 }
799}
800
David Brazdil0d13fee2015-04-17 14:52:19 +0100801void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
802 HInstruction* input_const = not_equal->GetConstantRight();
803 if (input_const != nullptr) {
804 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700805 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100806 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100807 // We are comparing the boolean to a constant which is of type int and can
808 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000809 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700810 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500811 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
812 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100813 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000814 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100815 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100816 not_equal->ReplaceWith(input_value);
817 block->RemoveInstruction(not_equal);
818 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100819 } else {
820 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
821 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
822 block->RemoveInstruction(not_equal);
823 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100824 }
Mark Mendellc4701932015-04-10 13:18:51 -0400825 } else {
826 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100827 }
Mark Mendellc4701932015-04-10 13:18:51 -0400828 } else {
829 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100830 }
831}
832
833void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000834 HInstruction* input = bool_not->InputAt(0);
835 HInstruction* replace_with = nullptr;
836
837 if (input->IsIntConstant()) {
838 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000839 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000840 replace_with = GetGraph()->GetIntConstant(0);
841 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000842 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000843 replace_with = GetGraph()->GetIntConstant(1);
844 }
845 } else if (input->IsBooleanNot()) {
846 // Replace (!(!bool_value)) with bool_value.
847 replace_with = input->InputAt(0);
848 } else if (input->IsCondition() &&
849 // Don't change FP compares. The definition of compares involving
850 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100851 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000852 // Replace condition with its opposite.
853 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
854 }
855
856 if (replace_with != nullptr) {
857 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100858 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000859 RecordSimplification();
860 }
861}
862
Aart Bik4f7dd342017-09-12 13:12:57 -0700863// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100864static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
865 HInstruction* x,
866 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700867 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800868 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700869 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800870 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
871 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700872}
873
Aart Bik142b9132018-03-14 15:12:59 -0700874// Constructs a new MIN/MAX(x, y) node in the HIR.
875static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
876 HInstruction* x,
877 HInstruction* y,
878 HInstruction* cursor,
879 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700880 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700881 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
882 HBinaryOperation* minmax = nullptr;
883 if (is_min) {
884 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
885 } else {
886 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
887 }
888 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
889 return minmax;
890}
891
Aart Bik4f7dd342017-09-12 13:12:57 -0700892// Returns true if operands a and b consists of widening type conversions
893// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100894static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700895 if (a->IsTypeConversion() && a->GetType() == to_type) {
896 a = a->InputAt(0);
897 }
898 if (b->IsTypeConversion() && b->GetType() == to_type) {
899 b = b->InputAt(0);
900 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100901 DataType::Type type1 = a->GetType();
902 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100903 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
904 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
905 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
906 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
907 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100908 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700909}
910
Aart Bik1d746de2018-03-28 16:30:02 -0700911// Returns an acceptable substitution for "a" on the select
912// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
913static HInstruction* AllowInMinMax(IfCondition cmp,
914 HInstruction* a,
915 HInstruction* b,
916 HInstruction* c) {
917 int64_t value = 0;
918 if (IsInt64AndGet(b, /*out*/ &value) &&
919 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
920 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
921 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
922 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
923 int64_t other_value = Int64FromConstant(other);
924 bool is_max = (cmp == kCondLT || cmp == kCondLE);
925 // Allow the max for a < 100 ? max(a, -100) : ..
926 // or the min for a > -100 ? min(a, 100) : ..
927 if (is_max ? (value >= other_value) : (value <= other_value)) {
928 return c;
929 }
930 }
931 }
932 return nullptr;
933}
934
David Brazdil74eb1b22015-12-14 11:44:01 +0000935void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
936 HInstruction* replace_with = nullptr;
937 HInstruction* condition = select->GetCondition();
938 HInstruction* true_value = select->GetTrueValue();
939 HInstruction* false_value = select->GetFalseValue();
940
941 if (condition->IsBooleanNot()) {
942 // Change ((!cond) ? x : y) to (cond ? y : x).
943 condition = condition->InputAt(0);
944 std::swap(true_value, false_value);
945 select->ReplaceInput(false_value, 0);
946 select->ReplaceInput(true_value, 1);
947 select->ReplaceInput(condition, 2);
948 RecordSimplification();
949 }
950
951 if (true_value == false_value) {
952 // Replace (cond ? x : x) with (x).
953 replace_with = true_value;
954 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000955 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000956 // Replace (true ? x : y) with (x).
957 replace_with = true_value;
958 } else {
959 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000960 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000961 replace_with = false_value;
962 }
963 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000964 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000965 // Replace (cond ? true : false) with (cond).
966 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000967 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000968 // Replace (cond ? false : true) with (!cond).
969 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
970 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700971 } else if (condition->IsCondition()) {
972 IfCondition cmp = condition->AsCondition()->GetCondition();
973 HInstruction* a = condition->InputAt(0);
974 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100975 DataType::Type t_type = true_value->GetType();
976 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700977 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700978 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
979 // type will be int or long, like the condition). Replacements are general,
980 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700981 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700982 // Allow a < 100 ? max(a, -100) : ..
983 // or a > -100 ? min(a, 100) : ..
984 // to use min/max instead of a to detect nested min/max expressions.
985 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
986 if (new_a != nullptr) {
987 a = new_a;
988 }
Aart Bik142b9132018-03-14 15:12:59 -0700989 // Try to replace typical integral MIN/MAX/ABS constructs.
990 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
991 ((a == true_value && b == false_value) ||
992 (b == true_value && a == false_value))) {
993 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
994 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
995 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
996 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700997 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
998 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
999 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
1000 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1001 HInstruction* not_negated = negLeft ? false_value : true_value;
1002 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1003 // Found a < 0 ? -a : a
1004 // or a > 0 ? a : -a
1005 // which can be replaced by ABS(a).
1006 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001007 }
1008 } else if (true_value->IsSub() && false_value->IsSub()) {
1009 HInstruction* true_sub1 = true_value->InputAt(0);
1010 HInstruction* true_sub2 = true_value->InputAt(1);
1011 HInstruction* false_sub1 = false_value->InputAt(0);
1012 HInstruction* false_sub2 = false_value->InputAt(1);
1013 if ((((cmp == kCondGT || cmp == kCondGE) &&
1014 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1015 ((cmp == kCondLT || cmp == kCondLE) &&
1016 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1017 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001018 // Found a > b ? a - b : b - a
1019 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001020 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001021 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001022 }
1023 }
1024 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001025 }
1026
1027 if (replace_with != nullptr) {
1028 select->ReplaceWith(replace_with);
1029 select->GetBlock()->RemoveInstruction(select);
1030 RecordSimplification();
1031 }
1032}
1033
1034void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1035 HInstruction* condition = instruction->InputAt(0);
1036 if (condition->IsBooleanNot()) {
1037 // Swap successors if input is negated.
1038 instruction->ReplaceInput(condition->InputAt(0), 0);
1039 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001040 RecordSimplification();
1041 }
1042}
1043
Mingyao Yang0304e182015-01-30 16:41:29 -08001044void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1045 HInstruction* input = instruction->InputAt(0);
1046 // If the array is a NewArray with constant size, replace the array length
1047 // with the constant instruction. This helps the bounds check elimination phase.
1048 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001049 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001050 if (input->IsIntConstant()) {
1051 instruction->ReplaceWith(input);
1052 }
1053 }
1054}
1055
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001056void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001057 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001058 if (value->GetType() != DataType::Type::kReference) {
1059 return;
1060 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001061
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001062 if (CanEnsureNotNullAt(value, instruction)) {
1063 instruction->ClearValueCanBeNull();
1064 }
1065
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001066 if (value->IsArrayGet()) {
1067 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1068 // If the code is just swapping elements in the array, no need for a type check.
1069 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001070 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001071 }
1072 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001073
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001074 if (value->IsNullConstant()) {
1075 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001076 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001077 }
1078
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001079 ScopedObjectAccess soa(Thread::Current());
1080 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1081 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1082 if (!array_rti.IsValid()) {
1083 return;
1084 }
1085
1086 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1087 instruction->ClearNeedsTypeCheck();
1088 return;
1089 }
1090
1091 if (array_rti.IsObjectArray()) {
1092 if (array_rti.IsExact()) {
1093 instruction->ClearNeedsTypeCheck();
1094 return;
1095 }
1096 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001097 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001098}
1099
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001100static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001101 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1102 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1103 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001104 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001105 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001106 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1107 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001108 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001109 return DataType::Size(result_type) > DataType::Size(input_type) &&
1110 result_type != DataType::Type::kUint16 &&
1111 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001112}
1113
Vladimir Marko61b92282017-10-11 13:23:17 +01001114static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1115 if (maybe_get->IsInstanceFieldGet()) {
1116 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1117 return true;
1118 } else if (maybe_get->IsStaticFieldGet()) {
1119 maybe_get->AsStaticFieldGet()->SetType(new_type);
1120 return true;
1121 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1122 maybe_get->AsArrayGet()->SetType(new_type);
1123 return true;
1124 } else {
1125 return false;
1126 }
1127}
1128
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001129// The type conversion is only used for storing into a field/element of the
1130// same/narrower size.
1131static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1132 if (type_conversion->HasEnvironmentUses()) {
1133 return false;
1134 }
1135 DataType::Type input_type = type_conversion->GetInputType();
1136 DataType::Type result_type = type_conversion->GetResultType();
1137 if (!DataType::IsIntegralType(input_type) ||
1138 !DataType::IsIntegralType(result_type) ||
1139 input_type == DataType::Type::kInt64 ||
1140 result_type == DataType::Type::kInt64) {
1141 // Type conversion is needed if non-integer types are involved, or 64-bit
1142 // types are involved, which may use different number of registers.
1143 return false;
1144 }
1145 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1146 // Type conversion is not necessary when storing to a field/element of the
1147 // same/smaller size.
1148 } else {
1149 // We do not handle this case here.
1150 return false;
1151 }
1152
1153 // Check if the converted value is only used for storing into heap.
1154 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1155 HInstruction* instruction = use.GetUser();
1156 if (instruction->IsInstanceFieldSet() &&
1157 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1158 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1159 continue;
1160 }
1161 if (instruction->IsStaticFieldSet() &&
1162 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1163 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1164 continue;
1165 }
1166 if (instruction->IsArraySet() &&
1167 instruction->AsArraySet()->GetComponentType() == result_type &&
1168 // not index use.
1169 instruction->AsArraySet()->GetIndex() != type_conversion) {
1170 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1171 continue;
1172 }
1173 // The use is not as a store value, or the field/element type is not the
1174 // same as the result_type, keep the type conversion.
1175 return false;
1176 }
1177 // Codegen automatically handles the type conversion during the store.
1178 return true;
1179}
1180
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001181void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001182 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001183 DataType::Type input_type = input->GetType();
1184 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001185 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001186 // Remove the implicit conversion; this includes conversion to the same type.
1187 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001188 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001189 RecordSimplification();
1190 return;
1191 }
1192
1193 if (input->IsTypeConversion()) {
1194 HTypeConversion* input_conversion = input->AsTypeConversion();
1195 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001196 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001197
1198 // When the first conversion is lossless, a direct conversion from the original type
1199 // to the final type yields the same result, even for a lossy second conversion, for
1200 // example float->double->int or int->double->float.
1201 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1202
1203 // For integral conversions, see if the first conversion loses only bits that the second
1204 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1205 // conversion yields the same result, for example long->int->short or int->char->short.
1206 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001207 DataType::IsIntegralType(input_type) &&
1208 DataType::IsIntegralType(original_type) &&
1209 DataType::IsIntegralType(result_type) &&
1210 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001211
1212 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1213 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001214 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001215 instruction->ReplaceWith(original_input);
1216 instruction->GetBlock()->RemoveInstruction(instruction);
1217 if (!input_conversion->HasUses()) {
1218 // Don't wait for DCE.
1219 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1220 }
1221 RecordSimplification();
1222 return;
1223 }
1224 // Otherwise simplify only if the first conversion has no other use.
1225 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1226 input_conversion->ReplaceWith(original_input);
1227 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1228 RecordSimplification();
1229 return;
1230 }
1231 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001232 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1233 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001234 HAnd* input_and = input->AsAnd();
1235 HConstant* constant = input_and->GetConstantRight();
1236 if (constant != nullptr) {
1237 int64_t value = Int64FromConstant(constant);
1238 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1239 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001240 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001241 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001242 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001243 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001244 instruction->ReplaceWith(original_input);
1245 instruction->GetBlock()->RemoveInstruction(instruction);
1246 RecordSimplification();
1247 return;
1248 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1249 input_and->ReplaceWith(original_input);
1250 input_and->GetBlock()->RemoveInstruction(input_and);
1251 RecordSimplification();
1252 return;
1253 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001254 }
1255 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001256 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1257 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1258 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1259 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1260 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1261 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1262 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1263 instruction->ReplaceWith(input);
1264 instruction->GetBlock()->RemoveInstruction(instruction);
1265 RecordSimplification();
1266 return;
1267 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001268 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001269
1270 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1271 instruction->ReplaceWith(input);
1272 instruction->GetBlock()->RemoveInstruction(instruction);
1273 RecordSimplification();
1274 return;
1275 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001276}
1277
Aart Bikc6eec4b2018-03-29 17:22:00 -07001278void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1279 HInstruction* input = instruction->GetInput();
1280 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1281 // Zero extension from narrow to wide can never set sign bit in the wider
1282 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1283 instruction->ReplaceWith(input);
1284 instruction->GetBlock()->RemoveInstruction(instruction);
1285 RecordSimplification();
1286 }
1287}
1288
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001289void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1290 HConstant* input_cst = instruction->GetConstantRight();
1291 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001292 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001293 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001294 // Replace code looking like
1295 // ADD dst, src, 0
1296 // with
1297 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001298 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1299 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1300 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001301 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001302 instruction->ReplaceWith(input_other);
1303 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001304 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001305 return;
1306 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001307 }
1308
1309 HInstruction* left = instruction->GetLeft();
1310 HInstruction* right = instruction->GetRight();
1311 bool left_is_neg = left->IsNeg();
1312 bool right_is_neg = right->IsNeg();
1313
1314 if (left_is_neg && right_is_neg) {
1315 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1316 return;
1317 }
1318 }
1319
1320 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1321 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1322 // Replace code looking like
1323 // NEG tmp, b
1324 // ADD dst, a, tmp
1325 // with
1326 // SUB dst, a, b
1327 // We do not perform the optimization if the input negation has environment
1328 // uses or multiple non-environment uses as it could lead to worse code. In
1329 // particular, we do not want the live range of `b` to be extended if we are
1330 // not sure the initial 'NEG' instruction can be removed.
1331 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001332 HSub* sub =
1333 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001334 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1335 RecordSimplification();
1336 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001337 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001338 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001339
Anton Kirilove14dc862016-05-13 17:56:15 +01001340 if (TryReplaceWithRotate(instruction)) {
1341 return;
1342 }
1343
1344 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1345 // so no need to return.
1346 TryHandleAssociativeAndCommutativeOperation(instruction);
1347
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001348 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001349 TrySubtractionChainSimplification(instruction)) {
1350 return;
1351 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001352
1353 if (integral_type) {
1354 // Replace code patterns looking like
1355 // SUB dst1, x, y SUB dst1, x, y
1356 // ADD dst2, dst1, y ADD dst2, y, dst1
1357 // with
1358 // SUB dst1, x, y
1359 // ADD instruction is not needed in this case, we may use
1360 // one of inputs of SUB instead.
1361 if (left->IsSub() && left->InputAt(1) == right) {
1362 instruction->ReplaceWith(left->InputAt(0));
1363 RecordSimplification();
1364 instruction->GetBlock()->RemoveInstruction(instruction);
1365 return;
1366 } else if (right->IsSub() && right->InputAt(1) == left) {
1367 instruction->ReplaceWith(right->InputAt(0));
1368 RecordSimplification();
1369 instruction->GetBlock()->RemoveInstruction(instruction);
1370 return;
1371 }
1372 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001373}
1374
1375void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001376 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001377 HConstant* input_cst = instruction->GetConstantRight();
1378 HInstruction* input_other = instruction->GetLeastConstantLeft();
1379
Vladimir Marko452c1b62015-09-25 14:44:17 +01001380 if (input_cst != nullptr) {
1381 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001382 if (value == -1 ||
1383 // Similar cases under zero extension.
1384 (DataType::IsUnsignedType(input_other->GetType()) &&
1385 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001386 // Replace code looking like
1387 // AND dst, src, 0xFFF...FF
1388 // with
1389 // src
1390 instruction->ReplaceWith(input_other);
1391 instruction->GetBlock()->RemoveInstruction(instruction);
1392 RecordSimplification();
1393 return;
1394 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001395 if (input_other->IsTypeConversion() &&
1396 input_other->GetType() == DataType::Type::kInt64 &&
1397 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1398 IsInt<32>(value) &&
1399 input_other->HasOnlyOneNonEnvironmentUse()) {
1400 // The AND can be reordered before the TypeConversion. Replace
1401 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1402 // TypeConversion<Int64> tmp, src
1403 // AND dst, tmp, cst
1404 // with
1405 // IntConstant cst, <32-bit-constant>
1406 // AND tmp, src, cst
1407 // TypeConversion<Int64> dst, tmp
1408 // This helps 32-bit targets and does not hurt 64-bit targets.
1409 // This also simplifies detection of other patterns, such as Uint8 loads.
1410 HInstruction* new_and_input = input_other->InputAt(0);
1411 // Implicit conversion Int64->Int64 would have been removed previously.
1412 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1413 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1414 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001415 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001416 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1417 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001418 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001419 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1420 input_other->GetBlock()->RemoveInstruction(input_other);
1421 RecordSimplification();
1422 // Try to process the new And now, do not wait for the next round of simplifications.
1423 instruction = new_and;
1424 input_other = new_and_input;
1425 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001426 // Eliminate And from UShr+And if the And-mask contains all the bits that
1427 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1428 // precisely clears the shifted-in sign bits.
1429 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001430 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001431 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1432 size_t num_tail_bits_set = CTZ(value + 1);
1433 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1434 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1435 instruction->ReplaceWith(input_other);
1436 instruction->GetBlock()->RemoveInstruction(instruction);
1437 RecordSimplification();
1438 return;
1439 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1440 input_other->HasOnlyOneNonEnvironmentUse()) {
1441 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1442 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001443 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001444 input_other->InputAt(0),
1445 input_other->InputAt(1),
1446 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001447 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1448 input_other->GetBlock()->RemoveInstruction(input_other);
1449 RecordSimplification();
1450 return;
1451 }
1452 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001453 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1454 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1455 // or array Get with only a single use, short-circuit the subsequent simplification
1456 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1457 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1458 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1459 if (input_other->GetType() == find_type &&
1460 input_other->HasOnlyOneNonEnvironmentUse() &&
1461 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1462 instruction->ReplaceWith(input_other);
1463 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001464 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1465 instruction->ReplaceWith(input_other);
1466 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001467 } else {
1468 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1469 new_type, input_other, instruction->GetDexPc());
1470 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1471 }
1472 RecordSimplification();
1473 return;
1474 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001475 }
1476
1477 // We assume that GVN has run before, so we only perform a pointer comparison.
1478 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001479 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001480 if (instruction->GetLeft() == instruction->GetRight()) {
1481 // Replace code looking like
1482 // AND dst, src, src
1483 // with
1484 // src
1485 instruction->ReplaceWith(instruction->GetLeft());
1486 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001487 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001488 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001489 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001490
Anton Kirilove14dc862016-05-13 17:56:15 +01001491 if (TryDeMorganNegationFactoring(instruction)) {
1492 return;
1493 }
1494
1495 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1496 // so no need to return.
1497 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001498}
1499
Mark Mendellc4701932015-04-10 13:18:51 -04001500void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1501 VisitCondition(condition);
1502}
1503
1504void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1505 VisitCondition(condition);
1506}
1507
1508void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1509 VisitCondition(condition);
1510}
1511
1512void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1513 VisitCondition(condition);
1514}
1515
Anton Shaminbdd79352016-02-15 12:48:36 +06001516void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1517 VisitCondition(condition);
1518}
1519
1520void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1521 VisitCondition(condition);
1522}
1523
1524void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1525 VisitCondition(condition);
1526}
1527
1528void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1529 VisitCondition(condition);
1530}
Aart Bike9f37602015-10-09 11:15:55 -07001531
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001532// Recognize the following pattern:
1533// obj.getClass() ==/!= Foo.class
1534// And replace it with a constant value if the type of `obj` is statically known.
1535static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1536 HInstruction* input_one = condition->InputAt(0);
1537 HInstruction* input_two = condition->InputAt(1);
1538 HLoadClass* load_class = input_one->IsLoadClass()
1539 ? input_one->AsLoadClass()
1540 : input_two->AsLoadClass();
1541 if (load_class == nullptr) {
1542 return false;
1543 }
1544
1545 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1546 if (!class_rti.IsValid()) {
1547 // Unresolved class.
1548 return false;
1549 }
1550
1551 HInstanceFieldGet* field_get = (load_class == input_one)
1552 ? input_two->AsInstanceFieldGet()
1553 : input_one->AsInstanceFieldGet();
1554 if (field_get == nullptr) {
1555 return false;
1556 }
1557
1558 HInstruction* receiver = field_get->InputAt(0);
1559 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1560 if (!receiver_type.IsExact()) {
1561 return false;
1562 }
1563
1564 {
1565 ScopedObjectAccess soa(Thread::Current());
1566 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1567 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1568 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1569 if (field_get->GetFieldInfo().GetField() != field) {
1570 return false;
1571 }
1572
1573 // We can replace the compare.
1574 int value = 0;
1575 if (receiver_type.IsEqual(class_rti)) {
1576 value = condition->IsEqual() ? 1 : 0;
1577 } else {
1578 value = condition->IsNotEqual() ? 1 : 0;
1579 }
1580 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1581 return true;
1582 }
1583}
1584
Mark Mendellc4701932015-04-10 13:18:51 -04001585void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001586 if (condition->IsEqual() || condition->IsNotEqual()) {
1587 if (RecognizeAndSimplifyClassCheck(condition)) {
1588 return;
1589 }
1590 }
1591
Anton Shaminbdd79352016-02-15 12:48:36 +06001592 // Reverse condition if left is constant. Our code generators prefer constant
1593 // on the right hand side.
1594 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1595 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001596 HCondition* replacement =
1597 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001598 // If it is a fp we must set the opposite bias.
1599 if (replacement != nullptr) {
1600 if (condition->IsLtBias()) {
1601 replacement->SetBias(ComparisonBias::kGtBias);
1602 } else if (condition->IsGtBias()) {
1603 replacement->SetBias(ComparisonBias::kLtBias);
1604 }
1605 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1606 RecordSimplification();
1607
1608 condition = replacement;
1609 }
1610 }
Mark Mendellc4701932015-04-10 13:18:51 -04001611
Mark Mendellc4701932015-04-10 13:18:51 -04001612 HInstruction* left = condition->GetLeft();
1613 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001614
1615 // Try to fold an HCompare into this HCondition.
1616
Mark Mendellc4701932015-04-10 13:18:51 -04001617 // We can only replace an HCondition which compares a Compare to 0.
1618 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1619 // condition with a long, float or double comparison as input.
1620 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1621 // Conversion is not possible.
1622 return;
1623 }
1624
1625 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001626 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001627 // Someone else also wants the result of the compare.
1628 return;
1629 }
1630
Vladimir Marko46817b82016-03-29 12:21:58 +01001631 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001632 // There is a reference to the compare result in an environment. Do we really need it?
1633 if (GetGraph()->IsDebuggable()) {
1634 return;
1635 }
1636
1637 // We have to ensure that there are no deopt points in the sequence.
1638 if (left->HasAnyEnvironmentUseBefore(condition)) {
1639 return;
1640 }
1641 }
1642
1643 // Clean up any environment uses from the HCompare, if any.
1644 left->RemoveEnvironmentUsers();
1645
1646 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1647 condition->SetBias(left->AsCompare()->GetBias());
1648
1649 // Replace the operands of the HCondition.
1650 condition->ReplaceInput(left->InputAt(0), 0);
1651 condition->ReplaceInput(left->InputAt(1), 1);
1652
1653 // Remove the HCompare.
1654 left->GetBlock()->RemoveInstruction(left);
1655
1656 RecordSimplification();
1657}
1658
Andreas Gampe9186ced2016-12-12 14:28:21 -08001659// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1660static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1661 // True, if the most significant bits of divisor are 0.
1662 return ((divisor & 0x7fffff) == 0);
1663}
1664
1665// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1666static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1667 // True, if the most significant bits of divisor are 0.
1668 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1669}
1670
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001671void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1672 HConstant* input_cst = instruction->GetConstantRight();
1673 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001674 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001675
1676 if ((input_cst != nullptr) && input_cst->IsOne()) {
1677 // Replace code looking like
1678 // DIV dst, src, 1
1679 // with
1680 // src
1681 instruction->ReplaceWith(input_other);
1682 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001683 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001684 return;
1685 }
1686
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001687 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001688 // Replace code looking like
1689 // DIV dst, src, -1
1690 // with
1691 // NEG dst, src
1692 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001693 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001694 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001695 return;
1696 }
1697
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001698 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001699 // Try replacing code looking like
1700 // DIV dst, src, constant
1701 // with
1702 // MUL dst, src, 1 / constant
1703 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001705 double value = input_cst->AsDoubleConstant()->GetValue();
1706 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1707 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1708 }
1709 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001710 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001711 float value = input_cst->AsFloatConstant()->GetValue();
1712 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1713 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1714 }
1715 }
1716
1717 if (reciprocal != nullptr) {
1718 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001719 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001720 RecordSimplification();
1721 return;
1722 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001723 }
1724}
1725
1726void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1727 HConstant* input_cst = instruction->GetConstantRight();
1728 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001729 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001730 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001731 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001732
1733 if (input_cst == nullptr) {
1734 return;
1735 }
1736
1737 if (input_cst->IsOne()) {
1738 // Replace code looking like
1739 // MUL dst, src, 1
1740 // with
1741 // src
1742 instruction->ReplaceWith(input_other);
1743 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001744 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001745 return;
1746 }
1747
1748 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001749 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001750 // Replace code looking like
1751 // MUL dst, src, -1
1752 // with
1753 // NEG dst, src
1754 HNeg* neg = new (allocator) HNeg(type, input_other);
1755 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001756 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001757 return;
1758 }
1759
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001760 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001761 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1762 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1763 // Replace code looking like
1764 // FP_MUL dst, src, 2.0
1765 // with
1766 // FP_ADD dst, src, src
1767 // The 'int' and 'long' cases are handled below.
1768 block->ReplaceAndRemoveInstructionWith(instruction,
1769 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001770 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001771 return;
1772 }
1773
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001775 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001776 // Even though constant propagation also takes care of the zero case, other
1777 // optimizations can lead to having a zero multiplication.
1778 if (factor == 0) {
1779 // Replace code looking like
1780 // MUL dst, src, 0
1781 // with
1782 // 0
1783 instruction->ReplaceWith(input_cst);
1784 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001785 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001786 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001787 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001788 // Replace code looking like
1789 // MUL dst, src, pow_of_2
1790 // with
1791 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001792 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001793 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001794 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001795 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001796 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001797 } else if (IsPowerOfTwo(factor - 1)) {
1798 // Transform code looking like
1799 // MUL dst, src, (2^n + 1)
1800 // into
1801 // SHL tmp, src, n
1802 // ADD dst, src, tmp
1803 HShl* shl = new (allocator) HShl(type,
1804 input_other,
1805 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1806 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1807
1808 block->InsertInstructionBefore(shl, instruction);
1809 block->ReplaceAndRemoveInstructionWith(instruction, add);
1810 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001811 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001812 } else if (IsPowerOfTwo(factor + 1)) {
1813 // Transform code looking like
1814 // MUL dst, src, (2^n - 1)
1815 // into
1816 // SHL tmp, src, n
1817 // SUB dst, tmp, src
1818 HShl* shl = new (allocator) HShl(type,
1819 input_other,
1820 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1821 HSub* sub = new (allocator) HSub(type, shl, input_other);
1822
1823 block->InsertInstructionBefore(shl, instruction);
1824 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1825 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001826 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001827 }
1828 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001829
1830 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1831 // so no need to return.
1832 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001833}
1834
Alexandre Rames188d4312015-04-09 18:30:21 +01001835void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1836 HInstruction* input = instruction->GetInput();
1837 if (input->IsNeg()) {
1838 // Replace code looking like
1839 // NEG tmp, src
1840 // NEG dst, tmp
1841 // with
1842 // src
1843 HNeg* previous_neg = input->AsNeg();
1844 instruction->ReplaceWith(previous_neg->GetInput());
1845 instruction->GetBlock()->RemoveInstruction(instruction);
1846 // We perform the optimization even if the input negation has environment
1847 // uses since it allows removing the current instruction. But we only delete
1848 // the input negation only if it is does not have any uses left.
1849 if (!previous_neg->HasUses()) {
1850 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1851 }
1852 RecordSimplification();
1853 return;
1854 }
1855
Serguei Katkov339dfc22015-04-20 12:29:32 +06001856 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001857 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001858 // Replace code looking like
1859 // SUB tmp, a, b
1860 // NEG dst, tmp
1861 // with
1862 // SUB dst, b, a
1863 // We do not perform the optimization if the input subtraction has
1864 // environment uses or multiple non-environment uses as it could lead to
1865 // worse code. In particular, we do not want the live ranges of `a` and `b`
1866 // to be extended if we are not sure the initial 'SUB' instruction can be
1867 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001868 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001869 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001870 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1871 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001872 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1873 if (!sub->HasUses()) {
1874 sub->GetBlock()->RemoveInstruction(sub);
1875 }
1876 RecordSimplification();
1877 }
1878}
1879
1880void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1881 HInstruction* input = instruction->GetInput();
1882 if (input->IsNot()) {
1883 // Replace code looking like
1884 // NOT tmp, src
1885 // NOT dst, tmp
1886 // with
1887 // src
1888 // We perform the optimization even if the input negation has environment
1889 // uses since it allows removing the current instruction. But we only delete
1890 // the input negation only if it is does not have any uses left.
1891 HNot* previous_not = input->AsNot();
1892 instruction->ReplaceWith(previous_not->GetInput());
1893 instruction->GetBlock()->RemoveInstruction(instruction);
1894 if (!previous_not->HasUses()) {
1895 previous_not->GetBlock()->RemoveInstruction(previous_not);
1896 }
1897 RecordSimplification();
1898 }
1899}
1900
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001901void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1902 HConstant* input_cst = instruction->GetConstantRight();
1903 HInstruction* input_other = instruction->GetLeastConstantLeft();
1904
Roland Levillain1a653882016-03-18 18:05:57 +00001905 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001906 // Replace code looking like
1907 // OR dst, src, 0
1908 // with
1909 // src
1910 instruction->ReplaceWith(input_other);
1911 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001912 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001913 return;
1914 }
1915
1916 // We assume that GVN has run before, so we only perform a pointer comparison.
1917 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001918 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001919 if (instruction->GetLeft() == instruction->GetRight()) {
1920 // Replace code looking like
1921 // OR dst, src, src
1922 // with
1923 // src
1924 instruction->ReplaceWith(instruction->GetLeft());
1925 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001926 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001927 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001928 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001929
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001930 if (TryDeMorganNegationFactoring(instruction)) return;
1931
Anton Kirilove14dc862016-05-13 17:56:15 +01001932 if (TryReplaceWithRotate(instruction)) {
1933 return;
1934 }
1935
1936 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1937 // so no need to return.
1938 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001939}
1940
1941void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1942 VisitShift(instruction);
1943}
1944
1945void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1946 VisitShift(instruction);
1947}
1948
1949void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1950 HConstant* input_cst = instruction->GetConstantRight();
1951 HInstruction* input_other = instruction->GetLeastConstantLeft();
1952
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001953 DataType::Type type = instruction->GetType();
1954 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001955 return;
1956 }
1957
Roland Levillain1a653882016-03-18 18:05:57 +00001958 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001959 // Replace code looking like
1960 // SUB dst, src, 0
1961 // with
1962 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001963 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1964 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1965 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001966 instruction->ReplaceWith(input_other);
1967 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001968 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001969 return;
1970 }
1971
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001972 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001973 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001974
Alexandre Rames188d4312015-04-09 18:30:21 +01001975 HInstruction* left = instruction->GetLeft();
1976 HInstruction* right = instruction->GetRight();
1977 if (left->IsConstant()) {
1978 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001979 // Replace code looking like
1980 // SUB dst, 0, src
1981 // with
1982 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001983 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001984 // `x` is `0.0`, the former expression yields `0.0`, while the later
1985 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001986 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001987 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001988 RecordSimplification();
1989 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001990 }
1991 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001992
1993 if (left->IsNeg() && right->IsNeg()) {
1994 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1995 return;
1996 }
1997 }
1998
1999 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
2000 // Replace code looking like
2001 // NEG tmp, b
2002 // SUB dst, a, tmp
2003 // with
2004 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002005 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002006 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2007 RecordSimplification();
2008 right->GetBlock()->RemoveInstruction(right);
2009 return;
2010 }
2011
2012 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2013 // Replace code looking like
2014 // NEG tmp, a
2015 // SUB dst, tmp, b
2016 // with
2017 // ADD tmp, a, b
2018 // NEG dst, tmp
2019 // The second version is not intrinsically better, but enables more
2020 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002021 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002022 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002023 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002024 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2025 instruction->ReplaceWith(neg);
2026 instruction->GetBlock()->RemoveInstruction(instruction);
2027 RecordSimplification();
2028 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002029 return;
2030 }
2031
2032 if (TrySubtractionChainSimplification(instruction)) {
2033 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002034 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002035
2036 if (left->IsAdd()) {
2037 // Replace code patterns looking like
2038 // ADD dst1, x, y ADD dst1, x, y
2039 // SUB dst2, dst1, y SUB dst2, dst1, x
2040 // with
2041 // ADD dst1, x, y
2042 // SUB instruction is not needed in this case, we may use
2043 // one of inputs of ADD instead.
2044 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002045 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002046 if (left->InputAt(1) == right) {
2047 instruction->ReplaceWith(left->InputAt(0));
2048 RecordSimplification();
2049 instruction->GetBlock()->RemoveInstruction(instruction);
2050 return;
2051 } else if (left->InputAt(0) == right) {
2052 instruction->ReplaceWith(left->InputAt(1));
2053 RecordSimplification();
2054 instruction->GetBlock()->RemoveInstruction(instruction);
2055 return;
2056 }
2057 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002058}
2059
2060void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2061 VisitShift(instruction);
2062}
2063
2064void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2065 HConstant* input_cst = instruction->GetConstantRight();
2066 HInstruction* input_other = instruction->GetLeastConstantLeft();
2067
Roland Levillain1a653882016-03-18 18:05:57 +00002068 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002069 // Replace code looking like
2070 // XOR dst, src, 0
2071 // with
2072 // src
2073 instruction->ReplaceWith(input_other);
2074 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002075 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002076 return;
2077 }
2078
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002079 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002080 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002081 // Replace code looking like
2082 // XOR dst, src, 1
2083 // with
2084 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002085 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002086 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2087 RecordSimplification();
2088 return;
2089 }
2090
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002091 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2092 // Replace code looking like
2093 // XOR dst, src, 0xFFF...FF
2094 // with
2095 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002096 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002097 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002098 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002099 return;
2100 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002101
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002102 HInstruction* left = instruction->GetLeft();
2103 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002104 if (((left->IsNot() && right->IsNot()) ||
2105 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002106 left->HasOnlyOneNonEnvironmentUse() &&
2107 right->HasOnlyOneNonEnvironmentUse()) {
2108 // Replace code looking like
2109 // NOT nota, a
2110 // NOT notb, b
2111 // XOR dst, nota, notb
2112 // with
2113 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002114 instruction->ReplaceInput(left->InputAt(0), 0);
2115 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002116 left->GetBlock()->RemoveInstruction(left);
2117 right->GetBlock()->RemoveInstruction(right);
2118 RecordSimplification();
2119 return;
2120 }
2121
Anton Kirilove14dc862016-05-13 17:56:15 +01002122 if (TryReplaceWithRotate(instruction)) {
2123 return;
2124 }
2125
2126 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2127 // so no need to return.
2128 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002129}
2130
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002131void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2132 HInstruction* argument = instruction->InputAt(1);
2133 HInstruction* receiver = instruction->InputAt(0);
2134 if (receiver == argument) {
2135 // Because String.equals is an instance call, the receiver is
2136 // a null check if we don't know it's null. The argument however, will
2137 // be the actual object. So we cannot end up in a situation where both
2138 // are equal but could be null.
2139 DCHECK(CanEnsureNotNullAt(argument, instruction));
2140 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2141 instruction->GetBlock()->RemoveInstruction(instruction);
2142 } else {
2143 StringEqualsOptimizations optimizations(instruction);
2144 if (CanEnsureNotNullAt(argument, instruction)) {
2145 optimizations.SetArgumentNotNull();
2146 }
2147 ScopedObjectAccess soa(Thread::Current());
2148 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2149 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2150 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002151 } else if (kUseReadBarrier) {
2152 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002153 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2154 // Object.equals() can be devirtualized to String.equals().
2155 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002156 Runtime* runtime = Runtime::Current();
2157 // For AOT, we always assume that the boot image shall contain the String.class and
2158 // we do not need a read barrier for boot image classes as they are non-moveable.
2159 // For JIT, check if we actually have a boot image; if we do, the String.class
2160 // should also be non-moveable.
2161 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2162 DCHECK(runtime->IsAotCompiler() ||
2163 !runtime->GetHeap()->IsMovableObject(
2164 instruction->GetResolvedMethod()->GetDeclaringClass()));
2165 optimizations.SetNoReadBarrierForStringClass();
2166 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002167 }
2168 }
2169}
2170
Roland Levillain22c49222016-03-18 14:04:28 +00002171void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2172 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002173 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002174 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002175 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002176 HInstruction* value = invoke->InputAt(0);
2177 HInstruction* distance = invoke->InputAt(1);
2178 // Replace the invoke with an HRor.
2179 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002180 // Unconditionally set the type of the negated distance to `int`,
2181 // as shift and rotate operations expect a 32-bit (or narrower)
2182 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002183 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002184 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2185 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002186 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002187 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2188 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002189 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002190 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2191 clinit->GetBlock()->RemoveInstruction(clinit);
2192 HInstruction* ldclass = clinit->InputAt(0);
2193 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2194 ldclass->GetBlock()->RemoveInstruction(ldclass);
2195 }
2196 }
2197}
2198
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002199static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2200 if (potential_length->IsArrayLength()) {
2201 return potential_length->InputAt(0) == potential_array;
2202 }
2203
2204 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002205 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002206 }
2207
2208 return false;
2209}
2210
2211void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2212 HInstruction* source = instruction->InputAt(0);
2213 HInstruction* destination = instruction->InputAt(2);
2214 HInstruction* count = instruction->InputAt(4);
2215 SystemArrayCopyOptimizations optimizations(instruction);
2216 if (CanEnsureNotNullAt(source, instruction)) {
2217 optimizations.SetSourceIsNotNull();
2218 }
2219 if (CanEnsureNotNullAt(destination, instruction)) {
2220 optimizations.SetDestinationIsNotNull();
2221 }
2222 if (destination == source) {
2223 optimizations.SetDestinationIsSource();
2224 }
2225
2226 if (IsArrayLengthOf(count, source)) {
2227 optimizations.SetCountIsSourceLength();
2228 }
2229
2230 if (IsArrayLengthOf(count, destination)) {
2231 optimizations.SetCountIsDestinationLength();
2232 }
2233
2234 {
2235 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002236 DataType::Type source_component_type = DataType::Type::kVoid;
2237 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002238 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2239 if (destination_rti.IsValid()) {
2240 if (destination_rti.IsObjectArray()) {
2241 if (destination_rti.IsExact()) {
2242 optimizations.SetDoesNotNeedTypeCheck();
2243 }
2244 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002245 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002246 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002247 destination_component_type = DataTypeFromPrimitive(
2248 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002249 optimizations.SetDestinationIsPrimitiveArray();
2250 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2251 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002252 }
2253 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002254 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2255 if (source_rti.IsValid()) {
2256 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2257 optimizations.SetDoesNotNeedTypeCheck();
2258 }
2259 if (source_rti.IsPrimitiveArrayClass()) {
2260 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002261 source_component_type = DataTypeFromPrimitive(
2262 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002263 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2264 optimizations.SetSourceIsNonPrimitiveArray();
2265 }
2266 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002267 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002268 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002269 (source_component_type == destination_component_type)) {
2270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2271 PointerSize image_size = class_linker->GetImagePointerSize();
2272 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2273 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2274 ArtMethod* method = nullptr;
2275 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002276 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002277 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002278 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002279 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002280 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002281 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002282 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002283 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002284 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002285 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002286 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002287 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002288 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002289 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002290 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002291 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002292 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002293 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002294 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002295 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002296 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002297 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002298 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002299 break;
2300 default:
2301 LOG(FATAL) << "Unreachable";
2302 }
2303 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002304 DCHECK(method->IsStatic());
2305 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002306 invoke->SetResolvedMethod(method);
2307 // Sharpen the new invoke. Note that we do not update the dex method index of
2308 // the invoke, as we would need to look it up in the current dex file, and it
2309 // is unlikely that it exists. The most usual situation for such typed
2310 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002311 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002312 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002313 }
2314}
2315
Roland Levillaina5c4a402016-03-15 15:02:50 +00002316void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2317 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002318 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002319 DCHECK(invoke->IsInvokeStaticOrDirect());
2320 uint32_t dex_pc = invoke->GetDexPc();
2321 HInstruction* left = invoke->InputAt(0);
2322 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002323 if (!is_signum) {
2324 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002325 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002326 right = GetGraph()->GetLongConstant(0);
2327 } else {
2328 right = GetGraph()->GetIntConstant(0);
2329 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002330 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002331 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2332 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2333}
2334
Aart Bik75a38b22016-02-17 10:41:50 -08002335void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2336 DCHECK(invoke->IsInvokeStaticOrDirect());
2337 uint32_t dex_pc = invoke->GetDexPc();
2338 // IsNaN(x) is the same as x != x.
2339 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002340 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002341 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002342 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2343}
2344
Aart Bik2a6aad92016-02-25 11:32:32 -08002345void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2346 DCHECK(invoke->IsInvokeStaticOrDirect());
2347 uint32_t dex_pc = invoke->GetDexPc();
2348 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002349 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002350 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2351 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002352 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002353 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2354 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2355 kNeedsEnvironmentOrCache,
2356 kNoSideEffects,
2357 kNoThrow);
2358 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002359 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002360 nan = GetGraph()->GetIntConstant(0x7fc00000);
2361 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2362 kNeedsEnvironmentOrCache,
2363 kNoSideEffects,
2364 kNoThrow);
2365 }
2366 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002367 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002368 condition->SetBias(ComparisonBias::kLtBias);
2369 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2370 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002371 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002372 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2373 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2374}
2375
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002376void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2377 HInstruction* str = invoke->InputAt(0);
2378 HInstruction* index = invoke->InputAt(1);
2379 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002380 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002381 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2382 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002383 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002384 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002385 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002386 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002387 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002388 HArrayGet* array_get = new (allocator) HArrayGet(str,
2389 bounds_check,
2390 DataType::Type::kUint16,
2391 SideEffects::None(), // Strings are immutable.
2392 dex_pc,
2393 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002394 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2395 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2396 GetGraph()->SetHasBoundsChecks(true);
2397}
2398
Vladimir Markodce016e2016-04-28 13:10:02 +01002399void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2400 HInstruction* str = invoke->InputAt(0);
2401 uint32_t dex_pc = invoke->GetDexPc();
2402 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2403 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002404 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002405 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002406 HInstruction* replacement;
2407 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2408 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2409 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2410 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002411 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002412 replacement = equal;
2413 } else {
2414 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2415 replacement = length;
2416 }
2417 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2418}
2419
Aart Bikff7d89c2016-11-07 08:49:28 -08002420// This method should only be used on intrinsics whose sole way of throwing an
2421// exception is raising a NPE when the nth argument is null. If that argument
2422// is provably non-null, we can clear the flag.
2423void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2424 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002425 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002426 invoke->SetCanThrow(false);
2427 }
2428}
2429
Aart Bik71bf7b42016-11-16 10:17:46 -08002430// Methods that return "this" can replace the returned value with the receiver.
2431void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2432 if (invoke->HasUses()) {
2433 HInstruction* receiver = invoke->InputAt(0);
2434 invoke->ReplaceWith(receiver);
2435 RecordSimplification();
2436 }
2437}
2438
2439// Helper method for StringBuffer escape analysis.
2440static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2441 if (user->IsInvokeStaticOrDirect()) {
2442 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002443 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2444 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002445 user->InputAt(0) == reference;
2446 } else if (user->IsInvokeVirtual()) {
2447 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2448 case Intrinsics::kStringBufferLength:
2449 case Intrinsics::kStringBufferToString:
2450 DCHECK_EQ(user->InputAt(0), reference);
2451 return true;
2452 case Intrinsics::kStringBufferAppend:
2453 // Returns "this", so only okay if no further uses.
2454 DCHECK_EQ(user->InputAt(0), reference);
2455 DCHECK_NE(user->InputAt(1), reference);
2456 return !user->HasUses();
2457 default:
2458 break;
2459 }
2460 }
2461 return false;
2462}
2463
2464// Certain allocation intrinsics are not removed by dead code elimination
2465// because of potentially throwing an OOM exception or other side effects.
2466// This method removes such intrinsics when special circumstances allow.
2467void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2468 if (!invoke->HasUses()) {
2469 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2470 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2471 // call does not escape since only thread-local synchronization may be removed.
2472 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2473 HInstruction* receiver = invoke->InputAt(0);
2474 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2475 invoke->GetBlock()->RemoveInstruction(invoke);
2476 RecordSimplification();
2477 }
2478 }
2479}
2480
Vladimir Markoca6fff82017-10-03 14:49:14 +01002481void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2482 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002483 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002484 HMemoryBarrier* mem_barrier =
2485 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002486 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2487}
2488
Aart Bik1f8d51b2018-02-15 10:42:37 -08002489void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2490 DCHECK(invoke->IsInvokeStaticOrDirect());
2491 HMin* min = new (GetGraph()->GetAllocator())
2492 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2493 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2494}
2495
2496void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2497 DCHECK(invoke->IsInvokeStaticOrDirect());
2498 HMax* max = new (GetGraph()->GetAllocator())
2499 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2500 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2501}
2502
Aart Bik3dad3412018-02-28 12:01:46 -08002503void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2504 DCHECK(invoke->IsInvokeStaticOrDirect());
2505 HAbs* abs = new (GetGraph()->GetAllocator())
2506 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2507 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2508}
2509
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002510void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002511 switch (instruction->GetIntrinsic()) {
2512 case Intrinsics::kStringEquals:
2513 SimplifyStringEquals(instruction);
2514 break;
2515 case Intrinsics::kSystemArrayCopy:
2516 SimplifySystemArrayCopy(instruction);
2517 break;
2518 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002519 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002520 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002521 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002522 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002523 break;
2524 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002525 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002526 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002527 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002528 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002529 break;
2530 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002531 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002532 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002533 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002534 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002535 break;
2536 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002537 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002538 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002539 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002540 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002541 break;
2542 case Intrinsics::kFloatIsNaN:
2543 case Intrinsics::kDoubleIsNaN:
2544 SimplifyIsNaN(instruction);
2545 break;
2546 case Intrinsics::kFloatFloatToIntBits:
2547 case Intrinsics::kDoubleDoubleToLongBits:
2548 SimplifyFP2Int(instruction);
2549 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002550 case Intrinsics::kStringCharAt:
2551 SimplifyStringCharAt(instruction);
2552 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002553 case Intrinsics::kStringIsEmpty:
2554 case Intrinsics::kStringLength:
2555 SimplifyStringIsEmptyOrLength(instruction);
2556 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002557 case Intrinsics::kStringStringIndexOf:
2558 case Intrinsics::kStringStringIndexOfAfter:
2559 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2560 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002561 case Intrinsics::kStringBufferAppend:
2562 case Intrinsics::kStringBuilderAppend:
2563 SimplifyReturnThis(instruction);
2564 break;
2565 case Intrinsics::kStringBufferToString:
2566 case Intrinsics::kStringBuilderToString:
2567 SimplifyAllocationIntrinsic(instruction);
2568 break;
Aart Bik11932592016-03-08 12:42:25 -08002569 case Intrinsics::kUnsafeLoadFence:
2570 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2571 break;
2572 case Intrinsics::kUnsafeStoreFence:
2573 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2574 break;
2575 case Intrinsics::kUnsafeFullFence:
2576 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2577 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002578 case Intrinsics::kVarHandleFullFence:
2579 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2580 break;
2581 case Intrinsics::kVarHandleAcquireFence:
2582 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2583 break;
2584 case Intrinsics::kVarHandleReleaseFence:
2585 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2586 break;
2587 case Intrinsics::kVarHandleLoadLoadFence:
2588 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2589 break;
2590 case Intrinsics::kVarHandleStoreStoreFence:
2591 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2592 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002593 case Intrinsics::kMathMinIntInt:
2594 SimplifyMin(instruction, DataType::Type::kInt32);
2595 break;
2596 case Intrinsics::kMathMinLongLong:
2597 SimplifyMin(instruction, DataType::Type::kInt64);
2598 break;
2599 case Intrinsics::kMathMinFloatFloat:
2600 SimplifyMin(instruction, DataType::Type::kFloat32);
2601 break;
2602 case Intrinsics::kMathMinDoubleDouble:
2603 SimplifyMin(instruction, DataType::Type::kFloat64);
2604 break;
2605 case Intrinsics::kMathMaxIntInt:
2606 SimplifyMax(instruction, DataType::Type::kInt32);
2607 break;
2608 case Intrinsics::kMathMaxLongLong:
2609 SimplifyMax(instruction, DataType::Type::kInt64);
2610 break;
2611 case Intrinsics::kMathMaxFloatFloat:
2612 SimplifyMax(instruction, DataType::Type::kFloat32);
2613 break;
2614 case Intrinsics::kMathMaxDoubleDouble:
2615 SimplifyMax(instruction, DataType::Type::kFloat64);
2616 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002617 case Intrinsics::kMathAbsInt:
2618 SimplifyAbs(instruction, DataType::Type::kInt32);
2619 break;
2620 case Intrinsics::kMathAbsLong:
2621 SimplifyAbs(instruction, DataType::Type::kInt64);
2622 break;
2623 case Intrinsics::kMathAbsFloat:
2624 SimplifyAbs(instruction, DataType::Type::kFloat32);
2625 break;
2626 case Intrinsics::kMathAbsDouble:
2627 SimplifyAbs(instruction, DataType::Type::kFloat64);
2628 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002629 default:
2630 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002631 }
2632}
2633
Aart Bikbb245d12015-10-19 11:05:03 -07002634void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2635 HInstruction* cond = deoptimize->InputAt(0);
2636 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002637 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002638 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002639 if (deoptimize->GuardsAnInput()) {
2640 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2641 }
Aart Bikbb245d12015-10-19 11:05:03 -07002642 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2643 } else {
2644 // Always deopt.
2645 }
2646 }
2647}
2648
Anton Kirilove14dc862016-05-13 17:56:15 +01002649// Replace code looking like
2650// OP y, x, const1
2651// OP z, y, const2
2652// with
2653// OP z, x, const3
2654// where OP is both an associative and a commutative operation.
2655bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2656 HBinaryOperation* instruction) {
2657 DCHECK(instruction->IsCommutative());
2658
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002659 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002660 return false;
2661 }
2662
2663 HInstruction* left = instruction->GetLeft();
2664 HInstruction* right = instruction->GetRight();
2665 // Variable names as described above.
2666 HConstant* const2;
2667 HBinaryOperation* y;
2668
2669 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2670 const2 = right->AsConstant();
2671 y = left->AsBinaryOperation();
2672 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2673 const2 = left->AsConstant();
2674 y = right->AsBinaryOperation();
2675 } else {
2676 // The node does not match the pattern.
2677 return false;
2678 }
2679
2680 // If `y` has more than one use, we do not perform the optimization
2681 // because it might increase code size (e.g. if the new constant is
2682 // no longer encodable as an immediate operand in the target ISA).
2683 if (!y->HasOnlyOneNonEnvironmentUse()) {
2684 return false;
2685 }
2686
2687 // GetConstantRight() can return both left and right constants
2688 // for commutative operations.
2689 HConstant* const1 = y->GetConstantRight();
2690 if (const1 == nullptr) {
2691 return false;
2692 }
2693
2694 instruction->ReplaceInput(const1, 0);
2695 instruction->ReplaceInput(const2, 1);
2696 HConstant* const3 = instruction->TryStaticEvaluation();
2697 DCHECK(const3 != nullptr);
2698 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2699 instruction->ReplaceInput(const3, 1);
2700 RecordSimplification();
2701 return true;
2702}
2703
2704static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2705 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2706}
2707
2708// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002709static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002710 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002711 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002712 return HAdd::Compute<int32_t>(x, y);
2713 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002714 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002715 return HAdd::Compute<int64_t>(x, y);
2716 }
2717}
2718
2719// Helper function that handles the child classes of HConstant
2720// and returns an integer with the appropriate sign.
2721static int64_t GetValue(HConstant* constant, bool is_negated) {
2722 int64_t ret = Int64FromConstant(constant);
2723 return is_negated ? -ret : ret;
2724}
2725
2726// Replace code looking like
2727// OP1 y, x, const1
2728// OP2 z, y, const2
2729// with
2730// OP3 z, x, const3
2731// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2732bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2733 HBinaryOperation* instruction) {
2734 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2735
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002736 DataType::Type type = instruction->GetType();
2737 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002738 return false;
2739 }
2740
2741 HInstruction* left = instruction->GetLeft();
2742 HInstruction* right = instruction->GetRight();
2743 // Variable names as described above.
2744 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2745 if (const2 == nullptr) {
2746 return false;
2747 }
2748
2749 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2750 ? left->AsBinaryOperation()
2751 : AsAddOrSub(right);
2752 // If y has more than one use, we do not perform the optimization because
2753 // it might increase code size (e.g. if the new constant is no longer
2754 // encodable as an immediate operand in the target ISA).
2755 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2756 return false;
2757 }
2758
2759 left = y->GetLeft();
2760 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2761 if (const1 == nullptr) {
2762 return false;
2763 }
2764
2765 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2766 // If both inputs are constants, let the constant folding pass deal with it.
2767 if (x->IsConstant()) {
2768 return false;
2769 }
2770
2771 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2772 int64_t const2_val = GetValue(const2, is_const2_negated);
2773 bool is_y_negated = (y == right) && instruction->IsSub();
2774 right = y->GetRight();
2775 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2776 int64_t const1_val = GetValue(const1, is_const1_negated);
2777 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2778 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2779 HBasicBlock* block = instruction->GetBlock();
2780 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002781 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002782 HInstruction* z;
2783
2784 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002785 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002786 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002787 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002788 }
2789
2790 block->ReplaceAndRemoveInstructionWith(instruction, z);
2791 RecordSimplification();
2792 return true;
2793}
2794
Lena Djokicbc5460b2017-07-20 16:07:36 +02002795void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2796 if (TryCombineVecMultiplyAccumulate(instruction)) {
2797 RecordSimplification();
2798 }
2799}
2800
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002801} // namespace art