blob: 2538fa38f127862459f1f3a18e2d9501e193ec33 [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
45 void 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);
70
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000071 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010072 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
73 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010074 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
75 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000076 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000077 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000078 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080079 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000080 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
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);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100123
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000124 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100125 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000126 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100127 bool simplification_occurred_ = false;
128 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700129 // We ensure we do not loop infinitely. The value should not be too high, since that
130 // would allow looping around the same basic block too many times. The value should
131 // not be too low either, however, since we want to allow revisiting a basic block
132 // with many statements and simplifications at least once.
133 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000134};
135
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100136void InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100137 if (kTestInstructionClonerExhaustively) {
138 CloneAndReplaceInstructionVisitor visitor(graph_);
139 visitor.VisitReversePostOrder();
140 }
141
Vladimir Marko65979462017-05-19 17:25:12 +0100142 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100143 visitor.Run();
144}
145
146void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100147 // Iterate in reverse post order to open up more simplifications to users
148 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100149 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100150 // The simplification of an instruction to another instruction may yield
151 // possibilities for other simplifications. So although we perform a reverse
152 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100153 do {
154 simplification_occurred_ = false;
155 VisitBasicBlock(block);
156 } while (simplification_occurred_ &&
157 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100158 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100159 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100160}
161
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000162namespace {
163
164bool AreAllBitsSet(HConstant* constant) {
165 return Int64FromConstant(constant) == -1;
166}
167
168} // namespace
169
Alexandre Rames188d4312015-04-09 18:30:21 +0100170// Returns true if the code was simplified to use only one negation operation
171// after the binary operation instead of one on each of the inputs.
172bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
173 DCHECK(binop->IsAdd() || binop->IsSub());
174 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
175 HNeg* left_neg = binop->GetLeft()->AsNeg();
176 HNeg* right_neg = binop->GetRight()->AsNeg();
177 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
178 !right_neg->HasOnlyOneNonEnvironmentUse()) {
179 return false;
180 }
181 // Replace code looking like
182 // NEG tmp1, a
183 // NEG tmp2, b
184 // ADD dst, tmp1, tmp2
185 // with
186 // ADD tmp, a, b
187 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600188 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
189 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
190 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100191 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600192 return false;
193 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100194 binop->ReplaceInput(left_neg->GetInput(), 0);
195 binop->ReplaceInput(right_neg->GetInput(), 1);
196 left_neg->GetBlock()->RemoveInstruction(left_neg);
197 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100198 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100199 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
200 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
201 RecordSimplification();
202 return true;
203}
204
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000205bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
206 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100207 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000208 HInstruction* left = op->GetLeft();
209 HInstruction* right = op->GetRight();
210
211 // We can apply De Morgan's laws if both inputs are Not's and are only used
212 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000213 if (((left->IsNot() && right->IsNot()) ||
214 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000215 left->HasOnlyOneNonEnvironmentUse() &&
216 right->HasOnlyOneNonEnvironmentUse()) {
217 // Replace code looking like
218 // NOT nota, a
219 // NOT notb, b
220 // AND dst, nota, notb (respectively OR)
221 // with
222 // OR or, a, b (respectively AND)
223 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000224 HInstruction* src_left = left->InputAt(0);
225 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000226 uint32_t dex_pc = op->GetDexPc();
227
228 // Remove the negations on the inputs.
229 left->ReplaceWith(src_left);
230 right->ReplaceWith(src_right);
231 left->GetBlock()->RemoveInstruction(left);
232 right->GetBlock()->RemoveInstruction(right);
233
234 // Replace the `HAnd` or `HOr`.
235 HBinaryOperation* hbin;
236 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100237 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000238 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100239 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000240 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000241 HInstruction* hnot;
242 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100243 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000244 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100245 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000246 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000247
248 op->GetBlock()->InsertInstructionBefore(hbin, op);
249 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
250
251 RecordSimplification();
252 return true;
253 }
254
255 return false;
256}
257
Lena Djokicbc5460b2017-07-20 16:07:36 +0200258bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100259 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200260 InstructionSet isa = codegen_->GetInstructionSet();
261 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000262 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100263 if (!(type == DataType::Type::kUint8 ||
264 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100265 type == DataType::Type::kUint16 ||
266 type == DataType::Type::kInt16 ||
267 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200268 return false;
269 }
270 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000271 case InstructionSet::kMips:
272 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100273 if (!(type == DataType::Type::kUint8 ||
274 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100275 type == DataType::Type::kUint16 ||
276 type == DataType::Type::kInt16 ||
277 type == DataType::Type::kInt32 ||
278 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200279 return false;
280 }
281 break;
282 default:
283 return false;
284 }
285
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100286 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200287
288 if (mul->HasOnlyOneNonEnvironmentUse()) {
289 HInstruction* use = mul->GetUses().front().GetUser();
290 if (use->IsVecAdd() || use->IsVecSub()) {
291 // Replace code looking like
292 // VECMUL tmp, x, y
293 // VECADD/SUB dst, acc, tmp
294 // with
295 // VECMULACC dst, acc, x, y
296 // Note that we do not want to (unconditionally) perform the merge when the
297 // multiplication has multiple uses and it can be merged in all of them.
298 // Multiple uses could happen on the same control-flow path, and we would
299 // then increase the amount of work. In the future we could try to evaluate
300 // whether all uses are on different control-flow paths (using dominance and
301 // reverse-dominance information) and only perform the merge when they are.
302 HInstruction* accumulator = nullptr;
303 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
304 HInstruction* binop_left = binop->GetLeft();
305 HInstruction* binop_right = binop->GetRight();
306 // This is always true since the `HVecMul` has only one use (which is checked above).
307 DCHECK_NE(binop_left, binop_right);
308 if (binop_right == mul) {
309 accumulator = binop_left;
310 } else if (use->IsVecAdd()) {
311 DCHECK_EQ(binop_left, mul);
312 accumulator = binop_right;
313 }
314
315 HInstruction::InstructionKind kind =
316 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
317 if (accumulator != nullptr) {
318 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100319 new (allocator) HVecMultiplyAccumulate(allocator,
320 kind,
321 accumulator,
322 mul->GetLeft(),
323 mul->GetRight(),
324 binop->GetPackedType(),
325 binop->GetVectorLength(),
326 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200327
328 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
329 DCHECK(!mul->HasUses());
330 mul->GetBlock()->RemoveInstruction(mul);
331 return true;
332 }
333 }
334 }
335
336 return false;
337}
338
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000339void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
340 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100341 HInstruction* shift_amount = instruction->GetRight();
342 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000343
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100344 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100345 ? kMaxLongShiftDistance
346 : kMaxIntShiftDistance;
347
348 if (shift_amount->IsConstant()) {
349 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700350 int64_t masked_cst = cst & implicit_mask;
351 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400352 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100353 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400354 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100355 // value
356 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400357 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100358 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100359 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700360 } else if (masked_cst != cst) {
361 // Replace code looking like
362 // SHL dst, value, cst
363 // where cst exceeds maximum distance with the equivalent
364 // SHL dst, value, cst & implicit_mask
365 // (as defined by shift semantics). This ensures other
366 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100367 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700368 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
369 RecordSimplification();
370 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100371 }
372 }
373
374 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100375 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
376 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100377 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100378 // AND adjusted_shift, shift, <superset of implicit mask>
379 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
380 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
381 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100382 // with
383 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100384 if (shift_amount->IsAnd() ||
385 shift_amount->IsOr() ||
386 shift_amount->IsXor() ||
387 shift_amount->IsAdd() ||
388 shift_amount->IsSub()) {
389 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
390 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
391 HConstant* mask = bin_op->GetConstantRight();
392 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
393 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100394 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100395 return;
396 }
397 } else if (shift_amount->IsTypeConversion()) {
398 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
399 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
400 // Non-integral and 64-bit source types require an explicit type conversion.
401 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
402 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
403 RecordSimplification();
404 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400405 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000406 }
407}
408
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000409static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
410 return (sub->GetRight() == other &&
411 sub->GetLeft()->IsConstant() &&
412 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
413}
414
415bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
416 HUShr* ushr,
417 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000418 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100419 HRor* ror =
420 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000421 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
422 if (!ushr->HasUses()) {
423 ushr->GetBlock()->RemoveInstruction(ushr);
424 }
425 if (!ushr->GetRight()->HasUses()) {
426 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
427 }
428 if (!shl->HasUses()) {
429 shl->GetBlock()->RemoveInstruction(shl);
430 }
431 if (!shl->GetRight()->HasUses()) {
432 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
433 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100434 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000435 return true;
436}
437
438// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
439bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000440 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
441 HInstruction* left = op->GetLeft();
442 HInstruction* right = op->GetRight();
443 // If we have an UShr and a Shl (in either order).
444 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
445 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
446 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100447 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000448 if (ushr->GetType() == shl->GetType() &&
449 ushr->GetLeft() == shl->GetLeft()) {
450 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
451 // Shift distances are both constant, try replacing with Ror if they
452 // add up to the register size.
453 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
454 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
455 // Shift distances are potentially of the form x and (reg_size - x).
456 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
457 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
458 // Shift distances are potentially of the form d and -d.
459 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
460 }
461 }
462 }
463 return false;
464}
465
466// Try replacing code looking like (x >>> #rdist OP x << #ldist):
467// UShr dst, x, #rdist
468// Shl tmp, x, #ldist
469// OP dst, dst, tmp
470// or like (x >>> #rdist OP x << #-ldist):
471// UShr dst, x, #rdist
472// Shl tmp, x, #-ldist
473// OP dst, dst, tmp
474// with
475// Ror dst, x, #rdist
476bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
477 HUShr* ushr,
478 HShl* shl) {
479 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100480 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000481 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
482 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
483 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
484 ReplaceRotateWithRor(op, ushr, shl);
485 return true;
486 }
487 return false;
488}
489
490// Replace code looking like (x >>> -d OP x << d):
491// Neg neg, d
492// UShr dst, x, neg
493// Shl tmp, x, d
494// OP dst, dst, tmp
495// with
496// Neg neg, d
497// Ror dst, x, neg
498// *** OR ***
499// Replace code looking like (x >>> d OP x << -d):
500// UShr dst, x, d
501// Neg neg, d
502// Shl tmp, x, neg
503// OP dst, dst, tmp
504// with
505// Ror dst, x, d
506bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
507 HUShr* ushr,
508 HShl* shl) {
509 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
510 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
511 bool neg_is_left = shl->GetRight()->IsNeg();
512 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
513 // And the shift distance being negated is the distance being shifted the other way.
514 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
515 ReplaceRotateWithRor(op, ushr, shl);
516 }
517 return false;
518}
519
520// Try replacing code looking like (x >>> d OP x << (#bits - d)):
521// UShr dst, x, d
522// Sub ld, #bits, d
523// Shl tmp, x, ld
524// OP dst, dst, tmp
525// with
526// Ror dst, x, d
527// *** OR ***
528// Replace code looking like (x >>> (#bits - d) OP x << d):
529// Sub rd, #bits, d
530// UShr dst, x, rd
531// Shl tmp, x, d
532// OP dst, dst, tmp
533// with
534// Neg neg, d
535// Ror dst, x, neg
536bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
537 HUShr* ushr,
538 HShl* shl) {
539 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
540 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100541 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000542 HInstruction* shl_shift = shl->GetRight();
543 HInstruction* ushr_shift = ushr->GetRight();
544 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
545 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
546 return ReplaceRotateWithRor(op, ushr, shl);
547 }
548 return false;
549}
550
Calin Juravle10e244f2015-01-26 18:54:32 +0000551void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
552 HInstruction* obj = null_check->InputAt(0);
553 if (!obj->CanBeNull()) {
554 null_check->ReplaceWith(obj);
555 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000556 if (stats_ != nullptr) {
557 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
558 }
559 }
560}
561
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100562bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
563 if (!input->CanBeNull()) {
564 return true;
565 }
566
Vladimir Marko46817b82016-03-29 12:21:58 +0100567 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
568 HInstruction* user = use.GetUser();
569 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100570 return true;
571 }
572 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100573
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100574 return false;
575}
576
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577// Returns whether doing a type test between the class of `object` against `klass` has
578// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000579static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
580 HInstruction* object,
581 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000582 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
583 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
584 ScopedObjectAccess soa(Thread::Current());
585 if (!obj_rti.IsValid()) {
586 // We run the simplifier before the reference type propagation so type info might not be
587 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100588 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000589 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100590
Calin Juravle98893e12015-10-02 21:05:03 +0100591 if (!class_rti.IsValid()) {
592 // Happens when the loaded class is unresolved.
593 return false;
594 }
595 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000596 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100597 *outcome = true;
598 return true;
599 } else if (obj_rti.IsExact()) {
600 // The test failed at compile time so will also fail at runtime.
601 *outcome = false;
602 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100603 } else if (!class_rti.IsInterface()
604 && !obj_rti.IsInterface()
605 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100606 // Different type hierarchy. The test will fail.
607 *outcome = false;
608 return true;
609 }
610 return false;
611}
612
613void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
614 HInstruction* object = check_cast->InputAt(0);
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000615 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
616 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100617 // If we need to perform an access check we cannot remove the instruction.
618 return;
619 }
620
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100621 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100622 check_cast->ClearMustDoNullCheck();
623 }
624
625 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000626 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700627 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100628 return;
629 }
630
Vladimir Markoa65ed302016-03-14 21:21:29 +0000631 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
632 // the return value check with the `outcome` check, b/27651442 .
633 bool outcome = false;
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000634 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100635 if (outcome) {
636 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700637 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000638 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
639 HLoadClass* load_class = check_cast->GetTargetClass();
640 if (!load_class->HasUses()) {
641 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
642 // However, here we know that it cannot because the checkcast was successfull, hence
643 // the class was already loaded.
644 load_class->GetBlock()->RemoveInstruction(load_class);
645 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700646 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100647 } else {
648 // Don't do anything for exceptional cases for now. Ideally we should remove
649 // all instructions and blocks this instruction dominates.
650 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000651 }
652}
653
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100654void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100655 HInstruction* object = instruction->InputAt(0);
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000656 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
657 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100658 // If we need to perform an access check we cannot remove the instruction.
659 return;
660 }
661
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100662 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100663 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100664 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100665 instruction->ClearMustDoNullCheck();
666 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100667
668 HGraph* graph = GetGraph();
669 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000670 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100671 instruction->ReplaceWith(graph->GetIntConstant(0));
672 instruction->GetBlock()->RemoveInstruction(instruction);
673 RecordSimplification();
674 return;
675 }
676
Vladimir Marko24bd8952016-03-15 10:40:33 +0000677 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
678 // the return value check with the `outcome` check, b/27651442 .
679 bool outcome = false;
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000680 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000681 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100682 if (outcome && can_be_null) {
683 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100684 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100685 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
686 instruction->ReplaceWith(test);
687 } else {
688 // We've statically determined the result of the instanceof.
689 instruction->ReplaceWith(graph->GetIntConstant(outcome));
690 }
691 RecordSimplification();
692 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000693 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
694 HLoadClass* load_class = instruction->GetTargetClass();
695 if (!load_class->HasUses()) {
696 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
697 // However, here we know that it cannot because the instanceof check was successfull, hence
698 // the class was already loaded.
699 load_class->GetBlock()->RemoveInstruction(load_class);
700 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700701 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100702 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100703}
704
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100705void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100706 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100707 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100708 instruction->ClearValueCanBeNull();
709 }
710}
711
712void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100713 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100714 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100715 instruction->ClearValueCanBeNull();
716 }
717}
718
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100719static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600720 HInstruction *lhs = cond->InputAt(0);
721 HInstruction *rhs = cond->InputAt(1);
722 switch (cond->GetKind()) {
723 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100724 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600725 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100726 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600727 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100728 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600729 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100730 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600731 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100732 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600733 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100734 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600735 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100736 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600737 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100738 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600739 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100740 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600741 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100742 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600743 default:
744 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
745 }
746 return nullptr;
747}
748
Aart Bik2767f4b2016-10-28 15:03:53 -0700749static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100750 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700751 return true; // input has direct boolean type
752 } else if (cmp->GetUses().HasExactlyOneElement()) {
753 // Comparison also has boolean type if both its input and the instruction
754 // itself feed into the same phi node.
755 HInstruction* user = cmp->GetUses().front().GetUser();
756 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
757 }
758 return false;
759}
760
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000761void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 HInstruction* input_const = equal->GetConstantRight();
763 if (input_const != nullptr) {
764 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700765 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100766 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100767 // We are comparing the boolean to a constant which is of type int and can
768 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000769 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100770 // Replace (bool_value == true) with bool_value
771 equal->ReplaceWith(input_value);
772 block->RemoveInstruction(equal);
773 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000774 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700775 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500776 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
777 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100778 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100779 } else {
780 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
781 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
782 block->RemoveInstruction(equal);
783 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100784 }
Mark Mendellc4701932015-04-10 13:18:51 -0400785 } else {
786 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100787 }
Mark Mendellc4701932015-04-10 13:18:51 -0400788 } else {
789 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100790 }
791}
792
David Brazdil0d13fee2015-04-17 14:52:19 +0100793void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
794 HInstruction* input_const = not_equal->GetConstantRight();
795 if (input_const != nullptr) {
796 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700797 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100798 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100799 // We are comparing the boolean to a constant which is of type int and can
800 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000801 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700802 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500803 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
804 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100805 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000806 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100807 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100808 not_equal->ReplaceWith(input_value);
809 block->RemoveInstruction(not_equal);
810 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100811 } else {
812 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
813 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
814 block->RemoveInstruction(not_equal);
815 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100816 }
Mark Mendellc4701932015-04-10 13:18:51 -0400817 } else {
818 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100819 }
Mark Mendellc4701932015-04-10 13:18:51 -0400820 } else {
821 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100822 }
823}
824
825void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000826 HInstruction* input = bool_not->InputAt(0);
827 HInstruction* replace_with = nullptr;
828
829 if (input->IsIntConstant()) {
830 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000831 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000832 replace_with = GetGraph()->GetIntConstant(0);
833 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000834 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 replace_with = GetGraph()->GetIntConstant(1);
836 }
837 } else if (input->IsBooleanNot()) {
838 // Replace (!(!bool_value)) with bool_value.
839 replace_with = input->InputAt(0);
840 } else if (input->IsCondition() &&
841 // Don't change FP compares. The definition of compares involving
842 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100843 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000844 // Replace condition with its opposite.
845 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
846 }
847
848 if (replace_with != nullptr) {
849 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100850 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000851 RecordSimplification();
852 }
853}
854
Aart Bik4f7dd342017-09-12 13:12:57 -0700855// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100856static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
857 HInstruction* x,
858 HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100859 DataType::Type type = x->GetType();
860 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700861 // Construct a fake intrinsic with as much context as is needed to allocate one.
862 // The intrinsic will always be lowered into code later anyway.
863 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
864 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
865 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
866 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
867 0u
868 };
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100869 HInvokeStaticOrDirect* invoke = new (allocator) HInvokeStaticOrDirect(
870 allocator,
Aart Bik4f7dd342017-09-12 13:12:57 -0700871 1,
872 type,
873 x->GetDexPc(),
874 /*method_idx*/ -1,
875 /*resolved_method*/ nullptr,
876 dispatch_info,
877 kStatic,
878 MethodReference(nullptr, dex::kDexNoIndex),
879 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
880 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100881 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
882 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700883 kNoEnvironmentOrCache,
884 kNoSideEffects,
885 kNoThrow);
886 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
887 return invoke;
888}
889
890// Returns true if operands a and b consists of widening type conversions
891// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100892static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700893 if (a->IsTypeConversion() && a->GetType() == to_type) {
894 a = a->InputAt(0);
895 }
896 if (b->IsTypeConversion() && b->GetType() == to_type) {
897 b = b->InputAt(0);
898 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100899 DataType::Type type1 = a->GetType();
900 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100901 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
902 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
903 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
904 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
905 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100906 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700907}
908
David Brazdil74eb1b22015-12-14 11:44:01 +0000909void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
910 HInstruction* replace_with = nullptr;
911 HInstruction* condition = select->GetCondition();
912 HInstruction* true_value = select->GetTrueValue();
913 HInstruction* false_value = select->GetFalseValue();
914
915 if (condition->IsBooleanNot()) {
916 // Change ((!cond) ? x : y) to (cond ? y : x).
917 condition = condition->InputAt(0);
918 std::swap(true_value, false_value);
919 select->ReplaceInput(false_value, 0);
920 select->ReplaceInput(true_value, 1);
921 select->ReplaceInput(condition, 2);
922 RecordSimplification();
923 }
924
925 if (true_value == false_value) {
926 // Replace (cond ? x : x) with (x).
927 replace_with = true_value;
928 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000929 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000930 // Replace (true ? x : y) with (x).
931 replace_with = true_value;
932 } else {
933 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000934 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000935 replace_with = false_value;
936 }
937 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000938 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000939 // Replace (cond ? true : false) with (cond).
940 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000941 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000942 // Replace (cond ? false : true) with (!cond).
943 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
944 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700945 } else if (condition->IsCondition()) {
946 IfCondition cmp = condition->AsCondition()->GetCondition();
947 HInstruction* a = condition->InputAt(0);
948 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100949 DataType::Type t_type = true_value->GetType();
950 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700951 // Here we have a <cmp> b ? true_value : false_value.
952 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100953 if (t_type == f_type &&
954 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700955 // Try to replace typical integral ABS constructs.
956 if (true_value->IsNeg()) {
957 HInstruction* negated = true_value->InputAt(0);
958 if ((cmp == kCondLT || cmp == kCondLE) &&
959 (a == negated && a == false_value && IsInt64Value(b, 0))) {
960 // Found a < 0 ? -a : a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100961 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), false_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700962 }
963 } else if (false_value->IsNeg()) {
964 HInstruction* negated = false_value->InputAt(0);
965 if ((cmp == kCondGT || cmp == kCondGE) &&
966 (a == true_value && a == negated && IsInt64Value(b, 0))) {
967 // Found a > 0 ? a : -a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100968 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700969 }
970 } else if (true_value->IsSub() && false_value->IsSub()) {
971 HInstruction* true_sub1 = true_value->InputAt(0);
972 HInstruction* true_sub2 = true_value->InputAt(1);
973 HInstruction* false_sub1 = false_value->InputAt(0);
974 HInstruction* false_sub2 = false_value->InputAt(1);
975 if ((((cmp == kCondGT || cmp == kCondGE) &&
976 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
977 ((cmp == kCondLT || cmp == kCondLE) &&
978 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
979 AreLowerPrecisionArgs(t_type, a, b)) {
980 // Found a > b ? a - b : b - a or
981 // a < b ? b - a : a - b
982 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100983 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700984 }
985 }
986 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000987 }
988
989 if (replace_with != nullptr) {
990 select->ReplaceWith(replace_with);
991 select->GetBlock()->RemoveInstruction(select);
992 RecordSimplification();
993 }
994}
995
996void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
997 HInstruction* condition = instruction->InputAt(0);
998 if (condition->IsBooleanNot()) {
999 // Swap successors if input is negated.
1000 instruction->ReplaceInput(condition->InputAt(0), 0);
1001 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001002 RecordSimplification();
1003 }
1004}
1005
Mingyao Yang0304e182015-01-30 16:41:29 -08001006void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1007 HInstruction* input = instruction->InputAt(0);
1008 // If the array is a NewArray with constant size, replace the array length
1009 // with the constant instruction. This helps the bounds check elimination phase.
1010 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001011 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001012 if (input->IsIntConstant()) {
1013 instruction->ReplaceWith(input);
1014 }
1015 }
1016}
1017
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001018void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001019 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001020 if (value->GetType() != DataType::Type::kReference) {
1021 return;
1022 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001023
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001024 if (CanEnsureNotNullAt(value, instruction)) {
1025 instruction->ClearValueCanBeNull();
1026 }
1027
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001028 if (value->IsArrayGet()) {
1029 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1030 // If the code is just swapping elements in the array, no need for a type check.
1031 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001032 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001033 }
1034 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001035
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001036 if (value->IsNullConstant()) {
1037 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001038 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001039 }
1040
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001041 ScopedObjectAccess soa(Thread::Current());
1042 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1043 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1044 if (!array_rti.IsValid()) {
1045 return;
1046 }
1047
1048 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1049 instruction->ClearNeedsTypeCheck();
1050 return;
1051 }
1052
1053 if (array_rti.IsObjectArray()) {
1054 if (array_rti.IsExact()) {
1055 instruction->ClearNeedsTypeCheck();
1056 return;
1057 }
1058 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001059 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001060}
1061
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001062static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001063 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1064 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1065 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001066 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001067 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001068 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1069 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001070 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001071 return DataType::Size(result_type) > DataType::Size(input_type) &&
1072 result_type != DataType::Type::kUint16 &&
1073 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001074}
1075
Vladimir Marko61b92282017-10-11 13:23:17 +01001076static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1077 if (maybe_get->IsInstanceFieldGet()) {
1078 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1079 return true;
1080 } else if (maybe_get->IsStaticFieldGet()) {
1081 maybe_get->AsStaticFieldGet()->SetType(new_type);
1082 return true;
1083 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1084 maybe_get->AsArrayGet()->SetType(new_type);
1085 return true;
1086 } else {
1087 return false;
1088 }
1089}
1090
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001091// The type conversion is only used for storing into a field/element of the
1092// same/narrower size.
1093static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1094 if (type_conversion->HasEnvironmentUses()) {
1095 return false;
1096 }
1097 DataType::Type input_type = type_conversion->GetInputType();
1098 DataType::Type result_type = type_conversion->GetResultType();
1099 if (!DataType::IsIntegralType(input_type) ||
1100 !DataType::IsIntegralType(result_type) ||
1101 input_type == DataType::Type::kInt64 ||
1102 result_type == DataType::Type::kInt64) {
1103 // Type conversion is needed if non-integer types are involved, or 64-bit
1104 // types are involved, which may use different number of registers.
1105 return false;
1106 }
1107 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1108 // Type conversion is not necessary when storing to a field/element of the
1109 // same/smaller size.
1110 } else {
1111 // We do not handle this case here.
1112 return false;
1113 }
1114
1115 // Check if the converted value is only used for storing into heap.
1116 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1117 HInstruction* instruction = use.GetUser();
1118 if (instruction->IsInstanceFieldSet() &&
1119 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1120 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1121 continue;
1122 }
1123 if (instruction->IsStaticFieldSet() &&
1124 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1125 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1126 continue;
1127 }
1128 if (instruction->IsArraySet() &&
1129 instruction->AsArraySet()->GetComponentType() == result_type &&
1130 // not index use.
1131 instruction->AsArraySet()->GetIndex() != type_conversion) {
1132 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1133 continue;
1134 }
1135 // The use is not as a store value, or the field/element type is not the
1136 // same as the result_type, keep the type conversion.
1137 return false;
1138 }
1139 // Codegen automatically handles the type conversion during the store.
1140 return true;
1141}
1142
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001143void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001144 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001145 DataType::Type input_type = input->GetType();
1146 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001147 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001148 // Remove the implicit conversion; this includes conversion to the same type.
1149 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001150 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001151 RecordSimplification();
1152 return;
1153 }
1154
1155 if (input->IsTypeConversion()) {
1156 HTypeConversion* input_conversion = input->AsTypeConversion();
1157 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001158 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001159
1160 // When the first conversion is lossless, a direct conversion from the original type
1161 // to the final type yields the same result, even for a lossy second conversion, for
1162 // example float->double->int or int->double->float.
1163 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1164
1165 // For integral conversions, see if the first conversion loses only bits that the second
1166 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1167 // conversion yields the same result, for example long->int->short or int->char->short.
1168 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001169 DataType::IsIntegralType(input_type) &&
1170 DataType::IsIntegralType(original_type) &&
1171 DataType::IsIntegralType(result_type) &&
1172 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001173
1174 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1175 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001176 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001177 instruction->ReplaceWith(original_input);
1178 instruction->GetBlock()->RemoveInstruction(instruction);
1179 if (!input_conversion->HasUses()) {
1180 // Don't wait for DCE.
1181 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1182 }
1183 RecordSimplification();
1184 return;
1185 }
1186 // Otherwise simplify only if the first conversion has no other use.
1187 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1188 input_conversion->ReplaceWith(original_input);
1189 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1190 RecordSimplification();
1191 return;
1192 }
1193 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001194 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1195 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001196 HAnd* input_and = input->AsAnd();
1197 HConstant* constant = input_and->GetConstantRight();
1198 if (constant != nullptr) {
1199 int64_t value = Int64FromConstant(constant);
1200 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1201 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001202 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001203 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001204 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001205 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001206 instruction->ReplaceWith(original_input);
1207 instruction->GetBlock()->RemoveInstruction(instruction);
1208 RecordSimplification();
1209 return;
1210 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1211 input_and->ReplaceWith(original_input);
1212 input_and->GetBlock()->RemoveInstruction(input_and);
1213 RecordSimplification();
1214 return;
1215 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001216 }
1217 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001218 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1219 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1220 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1221 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1222 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1223 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1224 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1225 instruction->ReplaceWith(input);
1226 instruction->GetBlock()->RemoveInstruction(instruction);
1227 RecordSimplification();
1228 return;
1229 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001230 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001231
1232 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1233 instruction->ReplaceWith(input);
1234 instruction->GetBlock()->RemoveInstruction(instruction);
1235 RecordSimplification();
1236 return;
1237 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001238}
1239
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001240void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1241 HConstant* input_cst = instruction->GetConstantRight();
1242 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001243 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001244 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001245 // Replace code looking like
1246 // ADD dst, src, 0
1247 // with
1248 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001249 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1250 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1251 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001252 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001253 instruction->ReplaceWith(input_other);
1254 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001255 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001256 return;
1257 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001258 }
1259
1260 HInstruction* left = instruction->GetLeft();
1261 HInstruction* right = instruction->GetRight();
1262 bool left_is_neg = left->IsNeg();
1263 bool right_is_neg = right->IsNeg();
1264
1265 if (left_is_neg && right_is_neg) {
1266 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1267 return;
1268 }
1269 }
1270
1271 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1272 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1273 // Replace code looking like
1274 // NEG tmp, b
1275 // ADD dst, a, tmp
1276 // with
1277 // SUB dst, a, b
1278 // We do not perform the optimization if the input negation has environment
1279 // uses or multiple non-environment uses as it could lead to worse code. In
1280 // particular, we do not want the live range of `b` to be extended if we are
1281 // not sure the initial 'NEG' instruction can be removed.
1282 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001283 HSub* sub =
1284 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001285 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1286 RecordSimplification();
1287 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001288 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001289 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001290
Anton Kirilove14dc862016-05-13 17:56:15 +01001291 if (TryReplaceWithRotate(instruction)) {
1292 return;
1293 }
1294
1295 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1296 // so no need to return.
1297 TryHandleAssociativeAndCommutativeOperation(instruction);
1298
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001299 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001300 TrySubtractionChainSimplification(instruction)) {
1301 return;
1302 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001303
1304 if (integral_type) {
1305 // Replace code patterns looking like
1306 // SUB dst1, x, y SUB dst1, x, y
1307 // ADD dst2, dst1, y ADD dst2, y, dst1
1308 // with
1309 // SUB dst1, x, y
1310 // ADD instruction is not needed in this case, we may use
1311 // one of inputs of SUB instead.
1312 if (left->IsSub() && left->InputAt(1) == right) {
1313 instruction->ReplaceWith(left->InputAt(0));
1314 RecordSimplification();
1315 instruction->GetBlock()->RemoveInstruction(instruction);
1316 return;
1317 } else if (right->IsSub() && right->InputAt(1) == left) {
1318 instruction->ReplaceWith(right->InputAt(0));
1319 RecordSimplification();
1320 instruction->GetBlock()->RemoveInstruction(instruction);
1321 return;
1322 }
1323 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001324}
1325
1326void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001327 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001328 HConstant* input_cst = instruction->GetConstantRight();
1329 HInstruction* input_other = instruction->GetLeastConstantLeft();
1330
Vladimir Marko452c1b62015-09-25 14:44:17 +01001331 if (input_cst != nullptr) {
1332 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001333 if (value == -1 ||
1334 // Similar cases under zero extension.
1335 (DataType::IsUnsignedType(input_other->GetType()) &&
1336 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001337 // Replace code looking like
1338 // AND dst, src, 0xFFF...FF
1339 // with
1340 // src
1341 instruction->ReplaceWith(input_other);
1342 instruction->GetBlock()->RemoveInstruction(instruction);
1343 RecordSimplification();
1344 return;
1345 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001346 if (input_other->IsTypeConversion() &&
1347 input_other->GetType() == DataType::Type::kInt64 &&
1348 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1349 IsInt<32>(value) &&
1350 input_other->HasOnlyOneNonEnvironmentUse()) {
1351 // The AND can be reordered before the TypeConversion. Replace
1352 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1353 // TypeConversion<Int64> tmp, src
1354 // AND dst, tmp, cst
1355 // with
1356 // IntConstant cst, <32-bit-constant>
1357 // AND tmp, src, cst
1358 // TypeConversion<Int64> dst, tmp
1359 // This helps 32-bit targets and does not hurt 64-bit targets.
1360 // This also simplifies detection of other patterns, such as Uint8 loads.
1361 HInstruction* new_and_input = input_other->InputAt(0);
1362 // Implicit conversion Int64->Int64 would have been removed previously.
1363 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1364 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1365 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001366 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001367 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1368 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001369 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001370 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1371 input_other->GetBlock()->RemoveInstruction(input_other);
1372 RecordSimplification();
1373 // Try to process the new And now, do not wait for the next round of simplifications.
1374 instruction = new_and;
1375 input_other = new_and_input;
1376 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001377 // Eliminate And from UShr+And if the And-mask contains all the bits that
1378 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1379 // precisely clears the shifted-in sign bits.
1380 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001381 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001382 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1383 size_t num_tail_bits_set = CTZ(value + 1);
1384 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1385 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1386 instruction->ReplaceWith(input_other);
1387 instruction->GetBlock()->RemoveInstruction(instruction);
1388 RecordSimplification();
1389 return;
1390 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1391 input_other->HasOnlyOneNonEnvironmentUse()) {
1392 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1393 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001394 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001395 input_other->InputAt(0),
1396 input_other->InputAt(1),
1397 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001398 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1399 input_other->GetBlock()->RemoveInstruction(input_other);
1400 RecordSimplification();
1401 return;
1402 }
1403 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001404 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1405 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1406 // or array Get with only a single use, short-circuit the subsequent simplification
1407 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1408 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1409 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1410 if (input_other->GetType() == find_type &&
1411 input_other->HasOnlyOneNonEnvironmentUse() &&
1412 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1413 instruction->ReplaceWith(input_other);
1414 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001415 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1416 instruction->ReplaceWith(input_other);
1417 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001418 } else {
1419 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1420 new_type, input_other, instruction->GetDexPc());
1421 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1422 }
1423 RecordSimplification();
1424 return;
1425 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001426 }
1427
1428 // We assume that GVN has run before, so we only perform a pointer comparison.
1429 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001430 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001431 if (instruction->GetLeft() == instruction->GetRight()) {
1432 // Replace code looking like
1433 // AND dst, src, src
1434 // with
1435 // src
1436 instruction->ReplaceWith(instruction->GetLeft());
1437 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001438 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001439 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001440 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001441
Anton Kirilove14dc862016-05-13 17:56:15 +01001442 if (TryDeMorganNegationFactoring(instruction)) {
1443 return;
1444 }
1445
1446 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1447 // so no need to return.
1448 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001449}
1450
Mark Mendellc4701932015-04-10 13:18:51 -04001451void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1452 VisitCondition(condition);
1453}
1454
1455void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1456 VisitCondition(condition);
1457}
1458
1459void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1460 VisitCondition(condition);
1461}
1462
1463void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1464 VisitCondition(condition);
1465}
1466
Anton Shaminbdd79352016-02-15 12:48:36 +06001467void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1468 VisitCondition(condition);
1469}
1470
1471void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1472 VisitCondition(condition);
1473}
1474
1475void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1476 VisitCondition(condition);
1477}
1478
1479void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1480 VisitCondition(condition);
1481}
Aart Bike9f37602015-10-09 11:15:55 -07001482
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001483// Recognize the following pattern:
1484// obj.getClass() ==/!= Foo.class
1485// And replace it with a constant value if the type of `obj` is statically known.
1486static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1487 HInstruction* input_one = condition->InputAt(0);
1488 HInstruction* input_two = condition->InputAt(1);
1489 HLoadClass* load_class = input_one->IsLoadClass()
1490 ? input_one->AsLoadClass()
1491 : input_two->AsLoadClass();
1492 if (load_class == nullptr) {
1493 return false;
1494 }
1495
1496 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1497 if (!class_rti.IsValid()) {
1498 // Unresolved class.
1499 return false;
1500 }
1501
1502 HInstanceFieldGet* field_get = (load_class == input_one)
1503 ? input_two->AsInstanceFieldGet()
1504 : input_one->AsInstanceFieldGet();
1505 if (field_get == nullptr) {
1506 return false;
1507 }
1508
1509 HInstruction* receiver = field_get->InputAt(0);
1510 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1511 if (!receiver_type.IsExact()) {
1512 return false;
1513 }
1514
1515 {
1516 ScopedObjectAccess soa(Thread::Current());
1517 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1518 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1519 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1520 if (field_get->GetFieldInfo().GetField() != field) {
1521 return false;
1522 }
1523
1524 // We can replace the compare.
1525 int value = 0;
1526 if (receiver_type.IsEqual(class_rti)) {
1527 value = condition->IsEqual() ? 1 : 0;
1528 } else {
1529 value = condition->IsNotEqual() ? 1 : 0;
1530 }
1531 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1532 return true;
1533 }
1534}
1535
Mark Mendellc4701932015-04-10 13:18:51 -04001536void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001537 if (condition->IsEqual() || condition->IsNotEqual()) {
1538 if (RecognizeAndSimplifyClassCheck(condition)) {
1539 return;
1540 }
1541 }
1542
Anton Shaminbdd79352016-02-15 12:48:36 +06001543 // Reverse condition if left is constant. Our code generators prefer constant
1544 // on the right hand side.
1545 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1546 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001547 HCondition* replacement =
1548 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001549 // If it is a fp we must set the opposite bias.
1550 if (replacement != nullptr) {
1551 if (condition->IsLtBias()) {
1552 replacement->SetBias(ComparisonBias::kGtBias);
1553 } else if (condition->IsGtBias()) {
1554 replacement->SetBias(ComparisonBias::kLtBias);
1555 }
1556 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1557 RecordSimplification();
1558
1559 condition = replacement;
1560 }
1561 }
Mark Mendellc4701932015-04-10 13:18:51 -04001562
Mark Mendellc4701932015-04-10 13:18:51 -04001563 HInstruction* left = condition->GetLeft();
1564 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001565
1566 // Try to fold an HCompare into this HCondition.
1567
Mark Mendellc4701932015-04-10 13:18:51 -04001568 // We can only replace an HCondition which compares a Compare to 0.
1569 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1570 // condition with a long, float or double comparison as input.
1571 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1572 // Conversion is not possible.
1573 return;
1574 }
1575
1576 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001577 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001578 // Someone else also wants the result of the compare.
1579 return;
1580 }
1581
Vladimir Marko46817b82016-03-29 12:21:58 +01001582 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001583 // There is a reference to the compare result in an environment. Do we really need it?
1584 if (GetGraph()->IsDebuggable()) {
1585 return;
1586 }
1587
1588 // We have to ensure that there are no deopt points in the sequence.
1589 if (left->HasAnyEnvironmentUseBefore(condition)) {
1590 return;
1591 }
1592 }
1593
1594 // Clean up any environment uses from the HCompare, if any.
1595 left->RemoveEnvironmentUsers();
1596
1597 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1598 condition->SetBias(left->AsCompare()->GetBias());
1599
1600 // Replace the operands of the HCondition.
1601 condition->ReplaceInput(left->InputAt(0), 0);
1602 condition->ReplaceInput(left->InputAt(1), 1);
1603
1604 // Remove the HCompare.
1605 left->GetBlock()->RemoveInstruction(left);
1606
1607 RecordSimplification();
1608}
1609
Andreas Gampe9186ced2016-12-12 14:28:21 -08001610// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1611static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1612 // True, if the most significant bits of divisor are 0.
1613 return ((divisor & 0x7fffff) == 0);
1614}
1615
1616// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1617static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1618 // True, if the most significant bits of divisor are 0.
1619 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1620}
1621
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001622void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1623 HConstant* input_cst = instruction->GetConstantRight();
1624 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001626
1627 if ((input_cst != nullptr) && input_cst->IsOne()) {
1628 // Replace code looking like
1629 // DIV dst, src, 1
1630 // with
1631 // src
1632 instruction->ReplaceWith(input_other);
1633 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001634 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001635 return;
1636 }
1637
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001638 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001639 // Replace code looking like
1640 // DIV dst, src, -1
1641 // with
1642 // NEG dst, src
1643 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001644 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001645 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001646 return;
1647 }
1648
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001650 // Try replacing code looking like
1651 // DIV dst, src, constant
1652 // with
1653 // MUL dst, src, 1 / constant
1654 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001655 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001656 double value = input_cst->AsDoubleConstant()->GetValue();
1657 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1658 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1659 }
1660 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001661 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001662 float value = input_cst->AsFloatConstant()->GetValue();
1663 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1664 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1665 }
1666 }
1667
1668 if (reciprocal != nullptr) {
1669 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001670 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001671 RecordSimplification();
1672 return;
1673 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001674 }
1675}
1676
1677void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1678 HConstant* input_cst = instruction->GetConstantRight();
1679 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001681 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001682 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001683
1684 if (input_cst == nullptr) {
1685 return;
1686 }
1687
1688 if (input_cst->IsOne()) {
1689 // Replace code looking like
1690 // MUL dst, src, 1
1691 // with
1692 // src
1693 instruction->ReplaceWith(input_other);
1694 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001695 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001696 return;
1697 }
1698
1699 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001700 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001701 // Replace code looking like
1702 // MUL dst, src, -1
1703 // with
1704 // NEG dst, src
1705 HNeg* neg = new (allocator) HNeg(type, input_other);
1706 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001707 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001708 return;
1709 }
1710
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001711 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001712 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1713 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1714 // Replace code looking like
1715 // FP_MUL dst, src, 2.0
1716 // with
1717 // FP_ADD dst, src, src
1718 // The 'int' and 'long' cases are handled below.
1719 block->ReplaceAndRemoveInstructionWith(instruction,
1720 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001721 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001722 return;
1723 }
1724
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001725 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001726 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001727 // Even though constant propagation also takes care of the zero case, other
1728 // optimizations can lead to having a zero multiplication.
1729 if (factor == 0) {
1730 // Replace code looking like
1731 // MUL dst, src, 0
1732 // with
1733 // 0
1734 instruction->ReplaceWith(input_cst);
1735 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001736 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001737 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001738 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001739 // Replace code looking like
1740 // MUL dst, src, pow_of_2
1741 // with
1742 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001743 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001744 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001745 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001746 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001747 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001748 } else if (IsPowerOfTwo(factor - 1)) {
1749 // Transform code looking like
1750 // MUL dst, src, (2^n + 1)
1751 // into
1752 // SHL tmp, src, n
1753 // ADD dst, src, tmp
1754 HShl* shl = new (allocator) HShl(type,
1755 input_other,
1756 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1757 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1758
1759 block->InsertInstructionBefore(shl, instruction);
1760 block->ReplaceAndRemoveInstructionWith(instruction, add);
1761 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001762 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001763 } else if (IsPowerOfTwo(factor + 1)) {
1764 // Transform code looking like
1765 // MUL dst, src, (2^n - 1)
1766 // into
1767 // SHL tmp, src, n
1768 // SUB dst, tmp, src
1769 HShl* shl = new (allocator) HShl(type,
1770 input_other,
1771 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1772 HSub* sub = new (allocator) HSub(type, shl, input_other);
1773
1774 block->InsertInstructionBefore(shl, instruction);
1775 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1776 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001777 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001778 }
1779 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001780
1781 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1782 // so no need to return.
1783 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001784}
1785
Alexandre Rames188d4312015-04-09 18:30:21 +01001786void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1787 HInstruction* input = instruction->GetInput();
1788 if (input->IsNeg()) {
1789 // Replace code looking like
1790 // NEG tmp, src
1791 // NEG dst, tmp
1792 // with
1793 // src
1794 HNeg* previous_neg = input->AsNeg();
1795 instruction->ReplaceWith(previous_neg->GetInput());
1796 instruction->GetBlock()->RemoveInstruction(instruction);
1797 // We perform the optimization even if the input negation has environment
1798 // uses since it allows removing the current instruction. But we only delete
1799 // the input negation only if it is does not have any uses left.
1800 if (!previous_neg->HasUses()) {
1801 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1802 }
1803 RecordSimplification();
1804 return;
1805 }
1806
Serguei Katkov339dfc22015-04-20 12:29:32 +06001807 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001809 // Replace code looking like
1810 // SUB tmp, a, b
1811 // NEG dst, tmp
1812 // with
1813 // SUB dst, b, a
1814 // We do not perform the optimization if the input subtraction has
1815 // environment uses or multiple non-environment uses as it could lead to
1816 // worse code. In particular, we do not want the live ranges of `a` and `b`
1817 // to be extended if we are not sure the initial 'SUB' instruction can be
1818 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001819 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001820 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001821 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1822 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001823 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1824 if (!sub->HasUses()) {
1825 sub->GetBlock()->RemoveInstruction(sub);
1826 }
1827 RecordSimplification();
1828 }
1829}
1830
1831void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1832 HInstruction* input = instruction->GetInput();
1833 if (input->IsNot()) {
1834 // Replace code looking like
1835 // NOT tmp, src
1836 // NOT dst, tmp
1837 // with
1838 // src
1839 // We perform the optimization even if the input negation has environment
1840 // uses since it allows removing the current instruction. But we only delete
1841 // the input negation only if it is does not have any uses left.
1842 HNot* previous_not = input->AsNot();
1843 instruction->ReplaceWith(previous_not->GetInput());
1844 instruction->GetBlock()->RemoveInstruction(instruction);
1845 if (!previous_not->HasUses()) {
1846 previous_not->GetBlock()->RemoveInstruction(previous_not);
1847 }
1848 RecordSimplification();
1849 }
1850}
1851
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001852void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1853 HConstant* input_cst = instruction->GetConstantRight();
1854 HInstruction* input_other = instruction->GetLeastConstantLeft();
1855
Roland Levillain1a653882016-03-18 18:05:57 +00001856 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001857 // Replace code looking like
1858 // OR dst, src, 0
1859 // with
1860 // src
1861 instruction->ReplaceWith(input_other);
1862 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001863 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001864 return;
1865 }
1866
1867 // We assume that GVN has run before, so we only perform a pointer comparison.
1868 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001869 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001870 if (instruction->GetLeft() == instruction->GetRight()) {
1871 // Replace code looking like
1872 // OR dst, src, src
1873 // with
1874 // src
1875 instruction->ReplaceWith(instruction->GetLeft());
1876 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001877 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001878 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001879 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001880
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001881 if (TryDeMorganNegationFactoring(instruction)) return;
1882
Anton Kirilove14dc862016-05-13 17:56:15 +01001883 if (TryReplaceWithRotate(instruction)) {
1884 return;
1885 }
1886
1887 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1888 // so no need to return.
1889 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001890}
1891
1892void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1893 VisitShift(instruction);
1894}
1895
1896void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1897 VisitShift(instruction);
1898}
1899
1900void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1901 HConstant* input_cst = instruction->GetConstantRight();
1902 HInstruction* input_other = instruction->GetLeastConstantLeft();
1903
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001904 DataType::Type type = instruction->GetType();
1905 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001906 return;
1907 }
1908
Roland Levillain1a653882016-03-18 18:05:57 +00001909 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001910 // Replace code looking like
1911 // SUB dst, src, 0
1912 // with
1913 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001914 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1915 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1916 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001917 instruction->ReplaceWith(input_other);
1918 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001919 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001920 return;
1921 }
1922
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001923 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001924 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001925
Alexandre Rames188d4312015-04-09 18:30:21 +01001926 HInstruction* left = instruction->GetLeft();
1927 HInstruction* right = instruction->GetRight();
1928 if (left->IsConstant()) {
1929 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001930 // Replace code looking like
1931 // SUB dst, 0, src
1932 // with
1933 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001934 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001935 // `x` is `0.0`, the former expression yields `0.0`, while the later
1936 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001937 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001938 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001939 RecordSimplification();
1940 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001941 }
1942 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001943
1944 if (left->IsNeg() && right->IsNeg()) {
1945 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1946 return;
1947 }
1948 }
1949
1950 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1951 // Replace code looking like
1952 // NEG tmp, b
1953 // SUB dst, a, tmp
1954 // with
1955 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001956 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001957 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1958 RecordSimplification();
1959 right->GetBlock()->RemoveInstruction(right);
1960 return;
1961 }
1962
1963 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1964 // Replace code looking like
1965 // NEG tmp, a
1966 // SUB dst, tmp, b
1967 // with
1968 // ADD tmp, a, b
1969 // NEG dst, tmp
1970 // The second version is not intrinsically better, but enables more
1971 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001972 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01001973 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001974 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01001975 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1976 instruction->ReplaceWith(neg);
1977 instruction->GetBlock()->RemoveInstruction(instruction);
1978 RecordSimplification();
1979 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001980 return;
1981 }
1982
1983 if (TrySubtractionChainSimplification(instruction)) {
1984 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001985 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001986
1987 if (left->IsAdd()) {
1988 // Replace code patterns looking like
1989 // ADD dst1, x, y ADD dst1, x, y
1990 // SUB dst2, dst1, y SUB dst2, dst1, x
1991 // with
1992 // ADD dst1, x, y
1993 // SUB instruction is not needed in this case, we may use
1994 // one of inputs of ADD instead.
1995 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001996 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001997 if (left->InputAt(1) == right) {
1998 instruction->ReplaceWith(left->InputAt(0));
1999 RecordSimplification();
2000 instruction->GetBlock()->RemoveInstruction(instruction);
2001 return;
2002 } else if (left->InputAt(0) == right) {
2003 instruction->ReplaceWith(left->InputAt(1));
2004 RecordSimplification();
2005 instruction->GetBlock()->RemoveInstruction(instruction);
2006 return;
2007 }
2008 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002009}
2010
2011void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2012 VisitShift(instruction);
2013}
2014
2015void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2016 HConstant* input_cst = instruction->GetConstantRight();
2017 HInstruction* input_other = instruction->GetLeastConstantLeft();
2018
Roland Levillain1a653882016-03-18 18:05:57 +00002019 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002020 // Replace code looking like
2021 // XOR dst, src, 0
2022 // with
2023 // src
2024 instruction->ReplaceWith(input_other);
2025 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002026 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002027 return;
2028 }
2029
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002030 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002031 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002032 // Replace code looking like
2033 // XOR dst, src, 1
2034 // with
2035 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002036 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002037 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2038 RecordSimplification();
2039 return;
2040 }
2041
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002042 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2043 // Replace code looking like
2044 // XOR dst, src, 0xFFF...FF
2045 // with
2046 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002047 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002048 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002049 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002050 return;
2051 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002052
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002053 HInstruction* left = instruction->GetLeft();
2054 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002055 if (((left->IsNot() && right->IsNot()) ||
2056 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002057 left->HasOnlyOneNonEnvironmentUse() &&
2058 right->HasOnlyOneNonEnvironmentUse()) {
2059 // Replace code looking like
2060 // NOT nota, a
2061 // NOT notb, b
2062 // XOR dst, nota, notb
2063 // with
2064 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002065 instruction->ReplaceInput(left->InputAt(0), 0);
2066 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002067 left->GetBlock()->RemoveInstruction(left);
2068 right->GetBlock()->RemoveInstruction(right);
2069 RecordSimplification();
2070 return;
2071 }
2072
Anton Kirilove14dc862016-05-13 17:56:15 +01002073 if (TryReplaceWithRotate(instruction)) {
2074 return;
2075 }
2076
2077 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2078 // so no need to return.
2079 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002080}
2081
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002082void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2083 HInstruction* argument = instruction->InputAt(1);
2084 HInstruction* receiver = instruction->InputAt(0);
2085 if (receiver == argument) {
2086 // Because String.equals is an instance call, the receiver is
2087 // a null check if we don't know it's null. The argument however, will
2088 // be the actual object. So we cannot end up in a situation where both
2089 // are equal but could be null.
2090 DCHECK(CanEnsureNotNullAt(argument, instruction));
2091 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2092 instruction->GetBlock()->RemoveInstruction(instruction);
2093 } else {
2094 StringEqualsOptimizations optimizations(instruction);
2095 if (CanEnsureNotNullAt(argument, instruction)) {
2096 optimizations.SetArgumentNotNull();
2097 }
2098 ScopedObjectAccess soa(Thread::Current());
2099 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2100 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2101 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002102 } else if (kUseReadBarrier) {
2103 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002104 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2105 // Object.equals() can be devirtualized to String.equals().
2106 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002107 Runtime* runtime = Runtime::Current();
2108 // For AOT, we always assume that the boot image shall contain the String.class and
2109 // we do not need a read barrier for boot image classes as they are non-moveable.
2110 // For JIT, check if we actually have a boot image; if we do, the String.class
2111 // should also be non-moveable.
2112 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2113 DCHECK(runtime->IsAotCompiler() ||
2114 !runtime->GetHeap()->IsMovableObject(
2115 instruction->GetResolvedMethod()->GetDeclaringClass()));
2116 optimizations.SetNoReadBarrierForStringClass();
2117 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002118 }
2119 }
2120}
2121
Roland Levillain22c49222016-03-18 14:04:28 +00002122void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2123 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002124 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002125 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002126 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002127 HInstruction* value = invoke->InputAt(0);
2128 HInstruction* distance = invoke->InputAt(1);
2129 // Replace the invoke with an HRor.
2130 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002131 // Unconditionally set the type of the negated distance to `int`,
2132 // as shift and rotate operations expect a 32-bit (or narrower)
2133 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002134 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002135 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2136 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002137 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002138 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2139 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002140 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002141 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2142 clinit->GetBlock()->RemoveInstruction(clinit);
2143 HInstruction* ldclass = clinit->InputAt(0);
2144 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2145 ldclass->GetBlock()->RemoveInstruction(ldclass);
2146 }
2147 }
2148}
2149
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002150static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2151 if (potential_length->IsArrayLength()) {
2152 return potential_length->InputAt(0) == potential_array;
2153 }
2154
2155 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002156 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002157 }
2158
2159 return false;
2160}
2161
2162void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2163 HInstruction* source = instruction->InputAt(0);
2164 HInstruction* destination = instruction->InputAt(2);
2165 HInstruction* count = instruction->InputAt(4);
2166 SystemArrayCopyOptimizations optimizations(instruction);
2167 if (CanEnsureNotNullAt(source, instruction)) {
2168 optimizations.SetSourceIsNotNull();
2169 }
2170 if (CanEnsureNotNullAt(destination, instruction)) {
2171 optimizations.SetDestinationIsNotNull();
2172 }
2173 if (destination == source) {
2174 optimizations.SetDestinationIsSource();
2175 }
2176
2177 if (IsArrayLengthOf(count, source)) {
2178 optimizations.SetCountIsSourceLength();
2179 }
2180
2181 if (IsArrayLengthOf(count, destination)) {
2182 optimizations.SetCountIsDestinationLength();
2183 }
2184
2185 {
2186 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002187 DataType::Type source_component_type = DataType::Type::kVoid;
2188 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002189 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2190 if (destination_rti.IsValid()) {
2191 if (destination_rti.IsObjectArray()) {
2192 if (destination_rti.IsExact()) {
2193 optimizations.SetDoesNotNeedTypeCheck();
2194 }
2195 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002196 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002197 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002198 destination_component_type = DataTypeFromPrimitive(
2199 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002200 optimizations.SetDestinationIsPrimitiveArray();
2201 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2202 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002203 }
2204 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002205 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2206 if (source_rti.IsValid()) {
2207 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2208 optimizations.SetDoesNotNeedTypeCheck();
2209 }
2210 if (source_rti.IsPrimitiveArrayClass()) {
2211 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002212 source_component_type = DataTypeFromPrimitive(
2213 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002214 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2215 optimizations.SetSourceIsNonPrimitiveArray();
2216 }
2217 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002218 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002219 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002220 (source_component_type == destination_component_type)) {
2221 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2222 PointerSize image_size = class_linker->GetImagePointerSize();
2223 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2224 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2225 ArtMethod* method = nullptr;
2226 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002227 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002228 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002229 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002230 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002231 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002232 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002233 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002234 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002235 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002236 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002237 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002238 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002239 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002240 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002241 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002242 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002243 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002244 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002245 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002246 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002247 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002248 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002249 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002250 break;
2251 default:
2252 LOG(FATAL) << "Unreachable";
2253 }
2254 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002255 DCHECK(method->IsStatic());
2256 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002257 invoke->SetResolvedMethod(method);
2258 // Sharpen the new invoke. Note that we do not update the dex method index of
2259 // the invoke, as we would need to look it up in the current dex file, and it
2260 // is unlikely that it exists. The most usual situation for such typed
2261 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002262 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002263 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002264 }
2265}
2266
Roland Levillaina5c4a402016-03-15 15:02:50 +00002267void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2268 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002269 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002270 DCHECK(invoke->IsInvokeStaticOrDirect());
2271 uint32_t dex_pc = invoke->GetDexPc();
2272 HInstruction* left = invoke->InputAt(0);
2273 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002274 if (!is_signum) {
2275 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002276 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002277 right = GetGraph()->GetLongConstant(0);
2278 } else {
2279 right = GetGraph()->GetIntConstant(0);
2280 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002281 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002282 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2283 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2284}
2285
Aart Bik75a38b22016-02-17 10:41:50 -08002286void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2287 DCHECK(invoke->IsInvokeStaticOrDirect());
2288 uint32_t dex_pc = invoke->GetDexPc();
2289 // IsNaN(x) is the same as x != x.
2290 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002291 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002292 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002293 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2294}
2295
Aart Bik2a6aad92016-02-25 11:32:32 -08002296void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2297 DCHECK(invoke->IsInvokeStaticOrDirect());
2298 uint32_t dex_pc = invoke->GetDexPc();
2299 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002300 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002301 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2302 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002303 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002304 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2305 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2306 kNeedsEnvironmentOrCache,
2307 kNoSideEffects,
2308 kNoThrow);
2309 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002310 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002311 nan = GetGraph()->GetIntConstant(0x7fc00000);
2312 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2313 kNeedsEnvironmentOrCache,
2314 kNoSideEffects,
2315 kNoThrow);
2316 }
2317 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002318 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002319 condition->SetBias(ComparisonBias::kLtBias);
2320 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2321 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002322 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002323 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2324 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2325}
2326
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002327void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2328 HInstruction* str = invoke->InputAt(0);
2329 HInstruction* index = invoke->InputAt(1);
2330 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002331 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002332 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2333 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002334 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002335 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002336 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002337 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002338 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002339 HArrayGet* array_get = new (allocator) HArrayGet(str,
2340 bounds_check,
2341 DataType::Type::kUint16,
2342 SideEffects::None(), // Strings are immutable.
2343 dex_pc,
2344 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002345 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2346 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2347 GetGraph()->SetHasBoundsChecks(true);
2348}
2349
Vladimir Markodce016e2016-04-28 13:10:02 +01002350void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2351 HInstruction* str = invoke->InputAt(0);
2352 uint32_t dex_pc = invoke->GetDexPc();
2353 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2354 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002355 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002356 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002357 HInstruction* replacement;
2358 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2359 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2360 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2361 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002362 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002363 replacement = equal;
2364 } else {
2365 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2366 replacement = length;
2367 }
2368 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2369}
2370
Aart Bikff7d89c2016-11-07 08:49:28 -08002371// This method should only be used on intrinsics whose sole way of throwing an
2372// exception is raising a NPE when the nth argument is null. If that argument
2373// is provably non-null, we can clear the flag.
2374void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2375 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002376 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002377 invoke->SetCanThrow(false);
2378 }
2379}
2380
Aart Bik71bf7b42016-11-16 10:17:46 -08002381// Methods that return "this" can replace the returned value with the receiver.
2382void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2383 if (invoke->HasUses()) {
2384 HInstruction* receiver = invoke->InputAt(0);
2385 invoke->ReplaceWith(receiver);
2386 RecordSimplification();
2387 }
2388}
2389
2390// Helper method for StringBuffer escape analysis.
2391static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2392 if (user->IsInvokeStaticOrDirect()) {
2393 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002394 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2395 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002396 user->InputAt(0) == reference;
2397 } else if (user->IsInvokeVirtual()) {
2398 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2399 case Intrinsics::kStringBufferLength:
2400 case Intrinsics::kStringBufferToString:
2401 DCHECK_EQ(user->InputAt(0), reference);
2402 return true;
2403 case Intrinsics::kStringBufferAppend:
2404 // Returns "this", so only okay if no further uses.
2405 DCHECK_EQ(user->InputAt(0), reference);
2406 DCHECK_NE(user->InputAt(1), reference);
2407 return !user->HasUses();
2408 default:
2409 break;
2410 }
2411 }
2412 return false;
2413}
2414
2415// Certain allocation intrinsics are not removed by dead code elimination
2416// because of potentially throwing an OOM exception or other side effects.
2417// This method removes such intrinsics when special circumstances allow.
2418void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2419 if (!invoke->HasUses()) {
2420 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2421 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2422 // call does not escape since only thread-local synchronization may be removed.
2423 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2424 HInstruction* receiver = invoke->InputAt(0);
2425 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2426 invoke->GetBlock()->RemoveInstruction(invoke);
2427 RecordSimplification();
2428 }
2429 }
2430}
2431
Vladimir Markoca6fff82017-10-03 14:49:14 +01002432void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2433 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002434 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002435 HMemoryBarrier* mem_barrier =
2436 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002437 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2438}
2439
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002440void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002441 switch (instruction->GetIntrinsic()) {
2442 case Intrinsics::kStringEquals:
2443 SimplifyStringEquals(instruction);
2444 break;
2445 case Intrinsics::kSystemArrayCopy:
2446 SimplifySystemArrayCopy(instruction);
2447 break;
2448 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002449 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002450 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002451 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002452 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002453 break;
2454 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002455 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002456 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002457 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002458 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002459 break;
2460 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002461 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002462 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002463 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002464 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002465 break;
2466 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002467 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002468 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002469 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002470 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002471 break;
2472 case Intrinsics::kFloatIsNaN:
2473 case Intrinsics::kDoubleIsNaN:
2474 SimplifyIsNaN(instruction);
2475 break;
2476 case Intrinsics::kFloatFloatToIntBits:
2477 case Intrinsics::kDoubleDoubleToLongBits:
2478 SimplifyFP2Int(instruction);
2479 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002480 case Intrinsics::kStringCharAt:
2481 SimplifyStringCharAt(instruction);
2482 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002483 case Intrinsics::kStringIsEmpty:
2484 case Intrinsics::kStringLength:
2485 SimplifyStringIsEmptyOrLength(instruction);
2486 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002487 case Intrinsics::kStringStringIndexOf:
2488 case Intrinsics::kStringStringIndexOfAfter:
2489 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2490 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002491 case Intrinsics::kStringBufferAppend:
2492 case Intrinsics::kStringBuilderAppend:
2493 SimplifyReturnThis(instruction);
2494 break;
2495 case Intrinsics::kStringBufferToString:
2496 case Intrinsics::kStringBuilderToString:
2497 SimplifyAllocationIntrinsic(instruction);
2498 break;
Aart Bik11932592016-03-08 12:42:25 -08002499 case Intrinsics::kUnsafeLoadFence:
2500 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2501 break;
2502 case Intrinsics::kUnsafeStoreFence:
2503 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2504 break;
2505 case Intrinsics::kUnsafeFullFence:
2506 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2507 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002508 case Intrinsics::kVarHandleFullFence:
2509 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2510 break;
2511 case Intrinsics::kVarHandleAcquireFence:
2512 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2513 break;
2514 case Intrinsics::kVarHandleReleaseFence:
2515 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2516 break;
2517 case Intrinsics::kVarHandleLoadLoadFence:
2518 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2519 break;
2520 case Intrinsics::kVarHandleStoreStoreFence:
2521 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2522 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002523 default:
2524 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002525 }
2526}
2527
Aart Bikbb245d12015-10-19 11:05:03 -07002528void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2529 HInstruction* cond = deoptimize->InputAt(0);
2530 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002531 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002532 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002533 if (deoptimize->GuardsAnInput()) {
2534 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2535 }
Aart Bikbb245d12015-10-19 11:05:03 -07002536 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2537 } else {
2538 // Always deopt.
2539 }
2540 }
2541}
2542
Anton Kirilove14dc862016-05-13 17:56:15 +01002543// Replace code looking like
2544// OP y, x, const1
2545// OP z, y, const2
2546// with
2547// OP z, x, const3
2548// where OP is both an associative and a commutative operation.
2549bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2550 HBinaryOperation* instruction) {
2551 DCHECK(instruction->IsCommutative());
2552
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002553 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002554 return false;
2555 }
2556
2557 HInstruction* left = instruction->GetLeft();
2558 HInstruction* right = instruction->GetRight();
2559 // Variable names as described above.
2560 HConstant* const2;
2561 HBinaryOperation* y;
2562
2563 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2564 const2 = right->AsConstant();
2565 y = left->AsBinaryOperation();
2566 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2567 const2 = left->AsConstant();
2568 y = right->AsBinaryOperation();
2569 } else {
2570 // The node does not match the pattern.
2571 return false;
2572 }
2573
2574 // If `y` has more than one use, we do not perform the optimization
2575 // because it might increase code size (e.g. if the new constant is
2576 // no longer encodable as an immediate operand in the target ISA).
2577 if (!y->HasOnlyOneNonEnvironmentUse()) {
2578 return false;
2579 }
2580
2581 // GetConstantRight() can return both left and right constants
2582 // for commutative operations.
2583 HConstant* const1 = y->GetConstantRight();
2584 if (const1 == nullptr) {
2585 return false;
2586 }
2587
2588 instruction->ReplaceInput(const1, 0);
2589 instruction->ReplaceInput(const2, 1);
2590 HConstant* const3 = instruction->TryStaticEvaluation();
2591 DCHECK(const3 != nullptr);
2592 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2593 instruction->ReplaceInput(const3, 1);
2594 RecordSimplification();
2595 return true;
2596}
2597
2598static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2599 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2600}
2601
2602// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002603static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002604 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002605 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002606 return HAdd::Compute<int32_t>(x, y);
2607 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002608 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002609 return HAdd::Compute<int64_t>(x, y);
2610 }
2611}
2612
2613// Helper function that handles the child classes of HConstant
2614// and returns an integer with the appropriate sign.
2615static int64_t GetValue(HConstant* constant, bool is_negated) {
2616 int64_t ret = Int64FromConstant(constant);
2617 return is_negated ? -ret : ret;
2618}
2619
2620// Replace code looking like
2621// OP1 y, x, const1
2622// OP2 z, y, const2
2623// with
2624// OP3 z, x, const3
2625// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2626bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2627 HBinaryOperation* instruction) {
2628 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2629
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002630 DataType::Type type = instruction->GetType();
2631 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002632 return false;
2633 }
2634
2635 HInstruction* left = instruction->GetLeft();
2636 HInstruction* right = instruction->GetRight();
2637 // Variable names as described above.
2638 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2639 if (const2 == nullptr) {
2640 return false;
2641 }
2642
2643 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2644 ? left->AsBinaryOperation()
2645 : AsAddOrSub(right);
2646 // If y has more than one use, we do not perform the optimization because
2647 // it might increase code size (e.g. if the new constant is no longer
2648 // encodable as an immediate operand in the target ISA).
2649 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2650 return false;
2651 }
2652
2653 left = y->GetLeft();
2654 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2655 if (const1 == nullptr) {
2656 return false;
2657 }
2658
2659 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2660 // If both inputs are constants, let the constant folding pass deal with it.
2661 if (x->IsConstant()) {
2662 return false;
2663 }
2664
2665 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2666 int64_t const2_val = GetValue(const2, is_const2_negated);
2667 bool is_y_negated = (y == right) && instruction->IsSub();
2668 right = y->GetRight();
2669 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2670 int64_t const1_val = GetValue(const1, is_const1_negated);
2671 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2672 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2673 HBasicBlock* block = instruction->GetBlock();
2674 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002675 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002676 HInstruction* z;
2677
2678 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002679 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002680 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002681 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002682 }
2683
2684 block->ReplaceAndRemoveInstructionWith(instruction, z);
2685 RecordSimplification();
2686 return true;
2687}
2688
Lena Djokicbc5460b2017-07-20 16:07:36 +02002689void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2690 if (TryCombineVecMultiplyAccumulate(instruction)) {
2691 RecordSimplification();
2692 }
2693}
2694
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002695} // namespace art