blob: d81a752853c3fff0d26829104f59a7eeae79f98c [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
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010030class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000032 InstructionSimplifierVisitor(HGraph* graph,
33 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010034 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000035 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010038 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010039 stats_(stats) {}
40
41 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000042
43 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010044 void RecordSimplification() {
45 simplification_occurred_ = true;
46 simplifications_at_current_position_++;
Igor Murashkin1e065a52017-08-09 13:20:34 -070047 MaybeRecordStat(stats_, kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010048 }
49
Scott Wakeling40a04bf2015-12-11 09:50:36 +000050 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51 bool TryReplaceWithRotate(HBinaryOperation* instruction);
52 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
53 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55
Alexandre Rames188d4312015-04-09 18:30:21 +010056 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000057 // `op` should be either HOr or HAnd.
58 // De Morgan's laws:
59 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
60 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010061 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
62 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020063 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010064
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000065 void VisitShift(HBinaryOperation* shift);
66
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010068 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
69 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010070 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
71 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000072 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000073 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000074 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080075 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000076 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitAdd(HAdd* instruction) OVERRIDE;
78 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040079 void VisitCondition(HCondition* instruction) OVERRIDE;
80 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
81 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
82 void VisitLessThan(HLessThan* condition) OVERRIDE;
83 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060084 void VisitBelow(HBelow* condition) OVERRIDE;
85 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
86 void VisitAbove(HAbove* condition) OVERRIDE;
87 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitDiv(HDiv* instruction) OVERRIDE;
89 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010090 void VisitNeg(HNeg* instruction) OVERRIDE;
91 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitOr(HOr* instruction) OVERRIDE;
93 void VisitShl(HShl* instruction) OVERRIDE;
94 void VisitShr(HShr* instruction) OVERRIDE;
95 void VisitSub(HSub* instruction) OVERRIDE;
96 void VisitUShr(HUShr* instruction) OVERRIDE;
97 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000098 void VisitSelect(HSelect* select) OVERRIDE;
99 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100100 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100101 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700102 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200103 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100104
105 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000106
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100107 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100108 void SimplifySystemArrayCopy(HInvoke* invoke);
109 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800111 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800112 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100113 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100114 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800115 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800116 void SimplifyReturnThis(HInvoke* invoke);
117 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800118 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100119
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000120 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100121 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000122 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 bool simplification_occurred_ = false;
124 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700125 // We ensure we do not loop infinitely. The value should not be too high, since that
126 // would allow looping around the same basic block too many times. The value should
127 // not be too low either, however, since we want to allow revisiting a basic block
128 // with many statements and simplifications at least once.
129 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000130};
131
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100132void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100133 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100134 visitor.Run();
135}
136
137void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100138 // Iterate in reverse post order to open up more simplifications to users
139 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100140 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100141 // The simplification of an instruction to another instruction may yield
142 // possibilities for other simplifications. So although we perform a reverse
143 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100144 do {
145 simplification_occurred_ = false;
146 VisitBasicBlock(block);
147 } while (simplification_occurred_ &&
148 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100149 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100150 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100151}
152
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000153namespace {
154
155bool AreAllBitsSet(HConstant* constant) {
156 return Int64FromConstant(constant) == -1;
157}
158
159} // namespace
160
Alexandre Rames188d4312015-04-09 18:30:21 +0100161// Returns true if the code was simplified to use only one negation operation
162// after the binary operation instead of one on each of the inputs.
163bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
164 DCHECK(binop->IsAdd() || binop->IsSub());
165 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
166 HNeg* left_neg = binop->GetLeft()->AsNeg();
167 HNeg* right_neg = binop->GetRight()->AsNeg();
168 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
169 !right_neg->HasOnlyOneNonEnvironmentUse()) {
170 return false;
171 }
172 // Replace code looking like
173 // NEG tmp1, a
174 // NEG tmp2, b
175 // ADD dst, tmp1, tmp2
176 // with
177 // ADD tmp, a, b
178 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600179 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
180 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
181 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100182 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600183 return false;
184 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100185 binop->ReplaceInput(left_neg->GetInput(), 0);
186 binop->ReplaceInput(right_neg->GetInput(), 1);
187 left_neg->GetBlock()->RemoveInstruction(left_neg);
188 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100189 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100190 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
191 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
192 RecordSimplification();
193 return true;
194}
195
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000196bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
197 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100198 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000199 HInstruction* left = op->GetLeft();
200 HInstruction* right = op->GetRight();
201
202 // We can apply De Morgan's laws if both inputs are Not's and are only used
203 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000204 if (((left->IsNot() && right->IsNot()) ||
205 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000206 left->HasOnlyOneNonEnvironmentUse() &&
207 right->HasOnlyOneNonEnvironmentUse()) {
208 // Replace code looking like
209 // NOT nota, a
210 // NOT notb, b
211 // AND dst, nota, notb (respectively OR)
212 // with
213 // OR or, a, b (respectively AND)
214 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* src_left = left->InputAt(0);
216 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000217 uint32_t dex_pc = op->GetDexPc();
218
219 // Remove the negations on the inputs.
220 left->ReplaceWith(src_left);
221 right->ReplaceWith(src_right);
222 left->GetBlock()->RemoveInstruction(left);
223 right->GetBlock()->RemoveInstruction(right);
224
225 // Replace the `HAnd` or `HOr`.
226 HBinaryOperation* hbin;
227 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100228 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000229 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100230 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100234 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000235 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100236 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000237 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000238
239 op->GetBlock()->InsertInstructionBefore(hbin, op);
240 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
241
242 RecordSimplification();
243 return true;
244 }
245
246 return false;
247}
248
Lena Djokicbc5460b2017-07-20 16:07:36 +0200249bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200251 InstructionSet isa = codegen_->GetInstructionSet();
252 switch (isa) {
253 case kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100254 if (!(type == DataType::Type::kUint8 ||
255 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100256 type == DataType::Type::kUint16 ||
257 type == DataType::Type::kInt16 ||
258 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200259 return false;
260 }
261 break;
262 case kMips:
263 case kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 if (!(type == DataType::Type::kUint8 ||
265 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 type == DataType::Type::kUint16 ||
267 type == DataType::Type::kInt16 ||
268 type == DataType::Type::kInt32 ||
269 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200270 return false;
271 }
272 break;
273 default:
274 return false;
275 }
276
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100277 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278
279 if (mul->HasOnlyOneNonEnvironmentUse()) {
280 HInstruction* use = mul->GetUses().front().GetUser();
281 if (use->IsVecAdd() || use->IsVecSub()) {
282 // Replace code looking like
283 // VECMUL tmp, x, y
284 // VECADD/SUB dst, acc, tmp
285 // with
286 // VECMULACC dst, acc, x, y
287 // Note that we do not want to (unconditionally) perform the merge when the
288 // multiplication has multiple uses and it can be merged in all of them.
289 // Multiple uses could happen on the same control-flow path, and we would
290 // then increase the amount of work. In the future we could try to evaluate
291 // whether all uses are on different control-flow paths (using dominance and
292 // reverse-dominance information) and only perform the merge when they are.
293 HInstruction* accumulator = nullptr;
294 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
295 HInstruction* binop_left = binop->GetLeft();
296 HInstruction* binop_right = binop->GetRight();
297 // This is always true since the `HVecMul` has only one use (which is checked above).
298 DCHECK_NE(binop_left, binop_right);
299 if (binop_right == mul) {
300 accumulator = binop_left;
301 } else if (use->IsVecAdd()) {
302 DCHECK_EQ(binop_left, mul);
303 accumulator = binop_right;
304 }
305
306 HInstruction::InstructionKind kind =
307 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
308 if (accumulator != nullptr) {
309 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100310 new (allocator) HVecMultiplyAccumulate(allocator,
311 kind,
312 accumulator,
313 mul->GetLeft(),
314 mul->GetRight(),
315 binop->GetPackedType(),
316 binop->GetVectorLength(),
317 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200318
319 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
320 DCHECK(!mul->HasUses());
321 mul->GetBlock()->RemoveInstruction(mul);
322 return true;
323 }
324 }
325 }
326
327 return false;
328}
329
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000330void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
331 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100332 HInstruction* shift_amount = instruction->GetRight();
333 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000334
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100335 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100336 ? kMaxLongShiftDistance
337 : kMaxIntShiftDistance;
338
339 if (shift_amount->IsConstant()) {
340 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700341 int64_t masked_cst = cst & implicit_mask;
342 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400343 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100344 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400345 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100346 // value
347 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400348 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100349 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100350 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700351 } else if (masked_cst != cst) {
352 // Replace code looking like
353 // SHL dst, value, cst
354 // where cst exceeds maximum distance with the equivalent
355 // SHL dst, value, cst & implicit_mask
356 // (as defined by shift semantics). This ensures other
357 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100358 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700359 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
360 RecordSimplification();
361 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100362 }
363 }
364
365 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100366 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
367 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100368 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100369 // AND adjusted_shift, shift, <superset of implicit mask>
370 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
371 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
372 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100373 // with
374 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100375 if (shift_amount->IsAnd() ||
376 shift_amount->IsOr() ||
377 shift_amount->IsXor() ||
378 shift_amount->IsAdd() ||
379 shift_amount->IsSub()) {
380 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
381 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
382 HConstant* mask = bin_op->GetConstantRight();
383 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
384 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100385 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 return;
387 }
388 } else if (shift_amount->IsTypeConversion()) {
389 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
390 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
391 // Non-integral and 64-bit source types require an explicit type conversion.
392 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
393 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
394 RecordSimplification();
395 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400396 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000397 }
398}
399
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000400static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
401 return (sub->GetRight() == other &&
402 sub->GetLeft()->IsConstant() &&
403 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
404}
405
406bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
407 HUShr* ushr,
408 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000409 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100410 HRor* ror =
411 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000412 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
413 if (!ushr->HasUses()) {
414 ushr->GetBlock()->RemoveInstruction(ushr);
415 }
416 if (!ushr->GetRight()->HasUses()) {
417 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
418 }
419 if (!shl->HasUses()) {
420 shl->GetBlock()->RemoveInstruction(shl);
421 }
422 if (!shl->GetRight()->HasUses()) {
423 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
424 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100425 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000426 return true;
427}
428
429// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
430bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000431 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
432 HInstruction* left = op->GetLeft();
433 HInstruction* right = op->GetRight();
434 // If we have an UShr and a Shl (in either order).
435 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
436 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
437 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100438 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000439 if (ushr->GetType() == shl->GetType() &&
440 ushr->GetLeft() == shl->GetLeft()) {
441 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
442 // Shift distances are both constant, try replacing with Ror if they
443 // add up to the register size.
444 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
445 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
446 // Shift distances are potentially of the form x and (reg_size - x).
447 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
448 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
449 // Shift distances are potentially of the form d and -d.
450 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
451 }
452 }
453 }
454 return false;
455}
456
457// Try replacing code looking like (x >>> #rdist OP x << #ldist):
458// UShr dst, x, #rdist
459// Shl tmp, x, #ldist
460// OP dst, dst, tmp
461// or like (x >>> #rdist OP x << #-ldist):
462// UShr dst, x, #rdist
463// Shl tmp, x, #-ldist
464// OP dst, dst, tmp
465// with
466// Ror dst, x, #rdist
467bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
468 HUShr* ushr,
469 HShl* shl) {
470 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100471 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000472 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
473 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
474 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
475 ReplaceRotateWithRor(op, ushr, shl);
476 return true;
477 }
478 return false;
479}
480
481// Replace code looking like (x >>> -d OP x << d):
482// Neg neg, d
483// UShr dst, x, neg
484// Shl tmp, x, d
485// OP dst, dst, tmp
486// with
487// Neg neg, d
488// Ror dst, x, neg
489// *** OR ***
490// Replace code looking like (x >>> d OP x << -d):
491// UShr dst, x, d
492// Neg neg, d
493// Shl tmp, x, neg
494// OP dst, dst, tmp
495// with
496// Ror dst, x, d
497bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
498 HUShr* ushr,
499 HShl* shl) {
500 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
501 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
502 bool neg_is_left = shl->GetRight()->IsNeg();
503 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
504 // And the shift distance being negated is the distance being shifted the other way.
505 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
506 ReplaceRotateWithRor(op, ushr, shl);
507 }
508 return false;
509}
510
511// Try replacing code looking like (x >>> d OP x << (#bits - d)):
512// UShr dst, x, d
513// Sub ld, #bits, d
514// Shl tmp, x, ld
515// OP dst, dst, tmp
516// with
517// Ror dst, x, d
518// *** OR ***
519// Replace code looking like (x >>> (#bits - d) OP x << d):
520// Sub rd, #bits, d
521// UShr dst, x, rd
522// Shl tmp, x, d
523// OP dst, dst, tmp
524// with
525// Neg neg, d
526// Ror dst, x, neg
527bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
528 HUShr* ushr,
529 HShl* shl) {
530 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
531 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100532 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000533 HInstruction* shl_shift = shl->GetRight();
534 HInstruction* ushr_shift = ushr->GetRight();
535 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
536 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
537 return ReplaceRotateWithRor(op, ushr, shl);
538 }
539 return false;
540}
541
Calin Juravle10e244f2015-01-26 18:54:32 +0000542void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
543 HInstruction* obj = null_check->InputAt(0);
544 if (!obj->CanBeNull()) {
545 null_check->ReplaceWith(obj);
546 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000547 if (stats_ != nullptr) {
548 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
549 }
550 }
551}
552
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100553bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
554 if (!input->CanBeNull()) {
555 return true;
556 }
557
Vladimir Marko46817b82016-03-29 12:21:58 +0100558 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
559 HInstruction* user = use.GetUser();
560 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100561 return true;
562 }
563 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100564
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100565 return false;
566}
567
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100568// Returns whether doing a type test between the class of `object` against `klass` has
569// a statically known outcome. The result of the test is stored in `outcome`.
570static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000571 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
572 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
573 ScopedObjectAccess soa(Thread::Current());
574 if (!obj_rti.IsValid()) {
575 // We run the simplifier before the reference type propagation so type info might not be
576 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000578 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100579
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100580 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100581 if (!class_rti.IsValid()) {
582 // Happens when the loaded class is unresolved.
583 return false;
584 }
585 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000586 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100587 *outcome = true;
588 return true;
589 } else if (obj_rti.IsExact()) {
590 // The test failed at compile time so will also fail at runtime.
591 *outcome = false;
592 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100593 } else if (!class_rti.IsInterface()
594 && !obj_rti.IsInterface()
595 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 // Different type hierarchy. The test will fail.
597 *outcome = false;
598 return true;
599 }
600 return false;
601}
602
603void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
604 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100605 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
606 if (load_class->NeedsAccessCheck()) {
607 // If we need to perform an access check we cannot remove the instruction.
608 return;
609 }
610
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100611 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100612 check_cast->ClearMustDoNullCheck();
613 }
614
615 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000616 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700617 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100618 return;
619 }
620
Vladimir Markoa65ed302016-03-14 21:21:29 +0000621 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
622 // the return value check with the `outcome` check, b/27651442 .
623 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700624 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100625 if (outcome) {
626 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700627 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700628 if (!load_class->HasUses()) {
629 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
630 // However, here we know that it cannot because the checkcast was successfull, hence
631 // the class was already loaded.
632 load_class->GetBlock()->RemoveInstruction(load_class);
633 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100634 } else {
635 // Don't do anything for exceptional cases for now. Ideally we should remove
636 // all instructions and blocks this instruction dominates.
637 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000638 }
639}
640
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100641void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100642 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100643 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
644 if (load_class->NeedsAccessCheck()) {
645 // If we need to perform an access check we cannot remove the instruction.
646 return;
647 }
648
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100649 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100650 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100651 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100652 instruction->ClearMustDoNullCheck();
653 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654
655 HGraph* graph = GetGraph();
656 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700657 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100658 instruction->ReplaceWith(graph->GetIntConstant(0));
659 instruction->GetBlock()->RemoveInstruction(instruction);
660 RecordSimplification();
661 return;
662 }
663
Vladimir Marko24bd8952016-03-15 10:40:33 +0000664 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
665 // the return value check with the `outcome` check, b/27651442 .
666 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700667 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700668 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100669 if (outcome && can_be_null) {
670 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100671 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
673 instruction->ReplaceWith(test);
674 } else {
675 // We've statically determined the result of the instanceof.
676 instruction->ReplaceWith(graph->GetIntConstant(outcome));
677 }
678 RecordSimplification();
679 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700680 if (outcome && !load_class->HasUses()) {
681 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
682 // However, here we know that it cannot because the instanceof check was successfull, hence
683 // the class was already loaded.
684 load_class->GetBlock()->RemoveInstruction(load_class);
685 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100686 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100687}
688
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100689void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100690 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100691 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100692 instruction->ClearValueCanBeNull();
693 }
694}
695
696void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100697 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100698 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100699 instruction->ClearValueCanBeNull();
700 }
701}
702
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100703static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600704 HInstruction *lhs = cond->InputAt(0);
705 HInstruction *rhs = cond->InputAt(1);
706 switch (cond->GetKind()) {
707 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100708 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600709 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100710 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600711 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100712 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600713 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100714 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600715 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100716 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600717 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100718 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600719 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100720 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600721 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100722 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600723 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100724 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600725 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100726 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600727 default:
728 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
729 }
730 return nullptr;
731}
732
Aart Bik2767f4b2016-10-28 15:03:53 -0700733static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100734 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700735 return true; // input has direct boolean type
736 } else if (cmp->GetUses().HasExactlyOneElement()) {
737 // Comparison also has boolean type if both its input and the instruction
738 // itself feed into the same phi node.
739 HInstruction* user = cmp->GetUses().front().GetUser();
740 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
741 }
742 return false;
743}
744
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000745void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100746 HInstruction* input_const = equal->GetConstantRight();
747 if (input_const != nullptr) {
748 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700749 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100750 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100751 // We are comparing the boolean to a constant which is of type int and can
752 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000753 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100754 // Replace (bool_value == true) with bool_value
755 equal->ReplaceWith(input_value);
756 block->RemoveInstruction(equal);
757 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000758 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700759 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500760 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
761 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100763 } else {
764 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
765 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
766 block->RemoveInstruction(equal);
767 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100768 }
Mark Mendellc4701932015-04-10 13:18:51 -0400769 } else {
770 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100771 }
Mark Mendellc4701932015-04-10 13:18:51 -0400772 } else {
773 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100774 }
775}
776
David Brazdil0d13fee2015-04-17 14:52:19 +0100777void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
778 HInstruction* input_const = not_equal->GetConstantRight();
779 if (input_const != nullptr) {
780 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700781 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100782 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100783 // We are comparing the boolean to a constant which is of type int and can
784 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000785 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700786 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500787 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
788 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000790 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100791 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100792 not_equal->ReplaceWith(input_value);
793 block->RemoveInstruction(not_equal);
794 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100795 } else {
796 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
797 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
798 block->RemoveInstruction(not_equal);
799 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100800 }
Mark Mendellc4701932015-04-10 13:18:51 -0400801 } else {
802 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100803 }
Mark Mendellc4701932015-04-10 13:18:51 -0400804 } else {
805 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100806 }
807}
808
809void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000810 HInstruction* input = bool_not->InputAt(0);
811 HInstruction* replace_with = nullptr;
812
813 if (input->IsIntConstant()) {
814 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000815 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000816 replace_with = GetGraph()->GetIntConstant(0);
817 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000818 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000819 replace_with = GetGraph()->GetIntConstant(1);
820 }
821 } else if (input->IsBooleanNot()) {
822 // Replace (!(!bool_value)) with bool_value.
823 replace_with = input->InputAt(0);
824 } else if (input->IsCondition() &&
825 // Don't change FP compares. The definition of compares involving
826 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100827 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000828 // Replace condition with its opposite.
829 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
830 }
831
832 if (replace_with != nullptr) {
833 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100834 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 RecordSimplification();
836 }
837}
838
Aart Bik4f7dd342017-09-12 13:12:57 -0700839// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100840static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
841 HInstruction* x,
842 HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100843 DataType::Type type = x->GetType();
844 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700845 // Construct a fake intrinsic with as much context as is needed to allocate one.
846 // The intrinsic will always be lowered into code later anyway.
847 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
848 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
849 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
850 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
851 0u
852 };
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100853 HInvokeStaticOrDirect* invoke = new (allocator) HInvokeStaticOrDirect(
854 allocator,
Aart Bik4f7dd342017-09-12 13:12:57 -0700855 1,
856 type,
857 x->GetDexPc(),
858 /*method_idx*/ -1,
859 /*resolved_method*/ nullptr,
860 dispatch_info,
861 kStatic,
862 MethodReference(nullptr, dex::kDexNoIndex),
863 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
864 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100865 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
866 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700867 kNoEnvironmentOrCache,
868 kNoSideEffects,
869 kNoThrow);
870 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
871 return invoke;
872}
873
874// Returns true if operands a and b consists of widening type conversions
875// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100876static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700877 if (a->IsTypeConversion() && a->GetType() == to_type) {
878 a = a->InputAt(0);
879 }
880 if (b->IsTypeConversion() && b->GetType() == to_type) {
881 b = b->InputAt(0);
882 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100883 DataType::Type type1 = a->GetType();
884 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100885 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
886 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
887 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
888 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
889 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100890 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700891}
892
David Brazdil74eb1b22015-12-14 11:44:01 +0000893void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
894 HInstruction* replace_with = nullptr;
895 HInstruction* condition = select->GetCondition();
896 HInstruction* true_value = select->GetTrueValue();
897 HInstruction* false_value = select->GetFalseValue();
898
899 if (condition->IsBooleanNot()) {
900 // Change ((!cond) ? x : y) to (cond ? y : x).
901 condition = condition->InputAt(0);
902 std::swap(true_value, false_value);
903 select->ReplaceInput(false_value, 0);
904 select->ReplaceInput(true_value, 1);
905 select->ReplaceInput(condition, 2);
906 RecordSimplification();
907 }
908
909 if (true_value == false_value) {
910 // Replace (cond ? x : x) with (x).
911 replace_with = true_value;
912 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000913 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000914 // Replace (true ? x : y) with (x).
915 replace_with = true_value;
916 } else {
917 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000918 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000919 replace_with = false_value;
920 }
921 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000922 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000923 // Replace (cond ? true : false) with (cond).
924 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000925 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000926 // Replace (cond ? false : true) with (!cond).
927 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
928 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700929 } else if (condition->IsCondition()) {
930 IfCondition cmp = condition->AsCondition()->GetCondition();
931 HInstruction* a = condition->InputAt(0);
932 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100933 DataType::Type t_type = true_value->GetType();
934 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700935 // Here we have a <cmp> b ? true_value : false_value.
936 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100937 if (t_type == f_type &&
938 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700939 // Try to replace typical integral ABS constructs.
940 if (true_value->IsNeg()) {
941 HInstruction* negated = true_value->InputAt(0);
942 if ((cmp == kCondLT || cmp == kCondLE) &&
943 (a == negated && a == false_value && IsInt64Value(b, 0))) {
944 // Found a < 0 ? -a : a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100945 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), false_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700946 }
947 } else if (false_value->IsNeg()) {
948 HInstruction* negated = false_value->InputAt(0);
949 if ((cmp == kCondGT || cmp == kCondGE) &&
950 (a == true_value && a == negated && IsInt64Value(b, 0))) {
951 // Found a > 0 ? a : -a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100952 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700953 }
954 } else if (true_value->IsSub() && false_value->IsSub()) {
955 HInstruction* true_sub1 = true_value->InputAt(0);
956 HInstruction* true_sub2 = true_value->InputAt(1);
957 HInstruction* false_sub1 = false_value->InputAt(0);
958 HInstruction* false_sub2 = false_value->InputAt(1);
959 if ((((cmp == kCondGT || cmp == kCondGE) &&
960 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
961 ((cmp == kCondLT || cmp == kCondLE) &&
962 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
963 AreLowerPrecisionArgs(t_type, a, b)) {
964 // Found a > b ? a - b : b - a or
965 // a < b ? b - a : a - b
966 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100967 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700968 }
969 }
970 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000971 }
972
973 if (replace_with != nullptr) {
974 select->ReplaceWith(replace_with);
975 select->GetBlock()->RemoveInstruction(select);
976 RecordSimplification();
977 }
978}
979
980void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
981 HInstruction* condition = instruction->InputAt(0);
982 if (condition->IsBooleanNot()) {
983 // Swap successors if input is negated.
984 instruction->ReplaceInput(condition->InputAt(0), 0);
985 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100986 RecordSimplification();
987 }
988}
989
Mingyao Yang0304e182015-01-30 16:41:29 -0800990void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
991 HInstruction* input = instruction->InputAt(0);
992 // If the array is a NewArray with constant size, replace the array length
993 // with the constant instruction. This helps the bounds check elimination phase.
994 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000995 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800996 if (input->IsIntConstant()) {
997 instruction->ReplaceWith(input);
998 }
999 }
1000}
1001
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001002void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001003 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001004 if (value->GetType() != DataType::Type::kReference) {
1005 return;
1006 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001007
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001008 if (CanEnsureNotNullAt(value, instruction)) {
1009 instruction->ClearValueCanBeNull();
1010 }
1011
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001012 if (value->IsArrayGet()) {
1013 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1014 // If the code is just swapping elements in the array, no need for a type check.
1015 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001016 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001017 }
1018 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001019
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001020 if (value->IsNullConstant()) {
1021 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001022 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001023 }
1024
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001025 ScopedObjectAccess soa(Thread::Current());
1026 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1027 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1028 if (!array_rti.IsValid()) {
1029 return;
1030 }
1031
1032 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1033 instruction->ClearNeedsTypeCheck();
1034 return;
1035 }
1036
1037 if (array_rti.IsObjectArray()) {
1038 if (array_rti.IsExact()) {
1039 instruction->ClearNeedsTypeCheck();
1040 return;
1041 }
1042 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001043 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001044}
1045
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001046static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001047 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001048 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001049 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1050 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001051 // Note: The size check excludes Uint8 as the result type.
1052 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001053 return DataType::Size(result_type) > DataType::Size(input_type) &&
1054 result_type != DataType::Type::kUint16 &&
1055 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001056}
1057
Vladimir Marko61b92282017-10-11 13:23:17 +01001058static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1059 if (maybe_get->IsInstanceFieldGet()) {
1060 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1061 return true;
1062 } else if (maybe_get->IsStaticFieldGet()) {
1063 maybe_get->AsStaticFieldGet()->SetType(new_type);
1064 return true;
1065 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1066 maybe_get->AsArrayGet()->SetType(new_type);
1067 return true;
1068 } else {
1069 return false;
1070 }
1071}
1072
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001073void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001074 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001075 DataType::Type input_type = input->GetType();
1076 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001077 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001078 // Remove the implicit conversion; this includes conversion to the same type.
1079 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001080 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001081 RecordSimplification();
1082 return;
1083 }
1084
1085 if (input->IsTypeConversion()) {
1086 HTypeConversion* input_conversion = input->AsTypeConversion();
1087 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001088 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001089
1090 // When the first conversion is lossless, a direct conversion from the original type
1091 // to the final type yields the same result, even for a lossy second conversion, for
1092 // example float->double->int or int->double->float.
1093 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1094
1095 // For integral conversions, see if the first conversion loses only bits that the second
1096 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1097 // conversion yields the same result, for example long->int->short or int->char->short.
1098 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001099 DataType::IsIntegralType(input_type) &&
1100 DataType::IsIntegralType(original_type) &&
1101 DataType::IsIntegralType(result_type) &&
1102 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001103
1104 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1105 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001106 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001107 instruction->ReplaceWith(original_input);
1108 instruction->GetBlock()->RemoveInstruction(instruction);
1109 if (!input_conversion->HasUses()) {
1110 // Don't wait for DCE.
1111 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1112 }
1113 RecordSimplification();
1114 return;
1115 }
1116 // Otherwise simplify only if the first conversion has no other use.
1117 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1118 input_conversion->ReplaceWith(original_input);
1119 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1120 RecordSimplification();
1121 return;
1122 }
1123 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001124 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1125 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001126 HAnd* input_and = input->AsAnd();
1127 HConstant* constant = input_and->GetConstantRight();
1128 if (constant != nullptr) {
1129 int64_t value = Int64FromConstant(constant);
1130 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1131 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001132 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001133 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001134 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001135 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001136 instruction->ReplaceWith(original_input);
1137 instruction->GetBlock()->RemoveInstruction(instruction);
1138 RecordSimplification();
1139 return;
1140 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1141 input_and->ReplaceWith(original_input);
1142 input_and->GetBlock()->RemoveInstruction(input_and);
1143 RecordSimplification();
1144 return;
1145 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001146 }
1147 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001148 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1149 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1150 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1151 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1152 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1153 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1154 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1155 instruction->ReplaceWith(input);
1156 instruction->GetBlock()->RemoveInstruction(instruction);
1157 RecordSimplification();
1158 return;
1159 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001160 }
1161}
1162
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001163void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1164 HConstant* input_cst = instruction->GetConstantRight();
1165 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001166 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001167 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001168 // Replace code looking like
1169 // ADD dst, src, 0
1170 // with
1171 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001172 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1173 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1174 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001175 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001176 instruction->ReplaceWith(input_other);
1177 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001178 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001179 return;
1180 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001181 }
1182
1183 HInstruction* left = instruction->GetLeft();
1184 HInstruction* right = instruction->GetRight();
1185 bool left_is_neg = left->IsNeg();
1186 bool right_is_neg = right->IsNeg();
1187
1188 if (left_is_neg && right_is_neg) {
1189 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1190 return;
1191 }
1192 }
1193
1194 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1195 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1196 // Replace code looking like
1197 // NEG tmp, b
1198 // ADD dst, a, tmp
1199 // with
1200 // SUB dst, a, b
1201 // We do not perform the optimization if the input negation has environment
1202 // uses or multiple non-environment uses as it could lead to worse code. In
1203 // particular, we do not want the live range of `b` to be extended if we are
1204 // not sure the initial 'NEG' instruction can be removed.
1205 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001206 HSub* sub =
1207 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001208 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1209 RecordSimplification();
1210 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001211 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001212 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001213
Anton Kirilove14dc862016-05-13 17:56:15 +01001214 if (TryReplaceWithRotate(instruction)) {
1215 return;
1216 }
1217
1218 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1219 // so no need to return.
1220 TryHandleAssociativeAndCommutativeOperation(instruction);
1221
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001222 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001223 TrySubtractionChainSimplification(instruction)) {
1224 return;
1225 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001226
1227 if (integral_type) {
1228 // Replace code patterns looking like
1229 // SUB dst1, x, y SUB dst1, x, y
1230 // ADD dst2, dst1, y ADD dst2, y, dst1
1231 // with
1232 // SUB dst1, x, y
1233 // ADD instruction is not needed in this case, we may use
1234 // one of inputs of SUB instead.
1235 if (left->IsSub() && left->InputAt(1) == right) {
1236 instruction->ReplaceWith(left->InputAt(0));
1237 RecordSimplification();
1238 instruction->GetBlock()->RemoveInstruction(instruction);
1239 return;
1240 } else if (right->IsSub() && right->InputAt(1) == left) {
1241 instruction->ReplaceWith(right->InputAt(0));
1242 RecordSimplification();
1243 instruction->GetBlock()->RemoveInstruction(instruction);
1244 return;
1245 }
1246 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001247}
1248
1249void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001250 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001251 HConstant* input_cst = instruction->GetConstantRight();
1252 HInstruction* input_other = instruction->GetLeastConstantLeft();
1253
Vladimir Marko452c1b62015-09-25 14:44:17 +01001254 if (input_cst != nullptr) {
1255 int64_t value = Int64FromConstant(input_cst);
1256 if (value == -1) {
1257 // Replace code looking like
1258 // AND dst, src, 0xFFF...FF
1259 // with
1260 // src
1261 instruction->ReplaceWith(input_other);
1262 instruction->GetBlock()->RemoveInstruction(instruction);
1263 RecordSimplification();
1264 return;
1265 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001266 if (input_other->IsTypeConversion() &&
1267 input_other->GetType() == DataType::Type::kInt64 &&
1268 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1269 IsInt<32>(value) &&
1270 input_other->HasOnlyOneNonEnvironmentUse()) {
1271 // The AND can be reordered before the TypeConversion. Replace
1272 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1273 // TypeConversion<Int64> tmp, src
1274 // AND dst, tmp, cst
1275 // with
1276 // IntConstant cst, <32-bit-constant>
1277 // AND tmp, src, cst
1278 // TypeConversion<Int64> dst, tmp
1279 // This helps 32-bit targets and does not hurt 64-bit targets.
1280 // This also simplifies detection of other patterns, such as Uint8 loads.
1281 HInstruction* new_and_input = input_other->InputAt(0);
1282 // Implicit conversion Int64->Int64 would have been removed previously.
1283 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1284 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1285 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001286 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001287 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1288 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001289 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001290 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1291 input_other->GetBlock()->RemoveInstruction(input_other);
1292 RecordSimplification();
1293 // Try to process the new And now, do not wait for the next round of simplifications.
1294 instruction = new_and;
1295 input_other = new_and_input;
1296 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001297 // Eliminate And from UShr+And if the And-mask contains all the bits that
1298 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1299 // precisely clears the shifted-in sign bits.
1300 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001301 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001302 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1303 size_t num_tail_bits_set = CTZ(value + 1);
1304 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1305 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1306 instruction->ReplaceWith(input_other);
1307 instruction->GetBlock()->RemoveInstruction(instruction);
1308 RecordSimplification();
1309 return;
1310 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1311 input_other->HasOnlyOneNonEnvironmentUse()) {
1312 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1313 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001314 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001315 input_other->InputAt(0),
1316 input_other->InputAt(1),
1317 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001318 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1319 input_other->GetBlock()->RemoveInstruction(input_other);
1320 RecordSimplification();
1321 return;
1322 }
1323 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001324 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1325 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1326 // or array Get with only a single use, short-circuit the subsequent simplification
1327 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1328 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1329 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1330 if (input_other->GetType() == find_type &&
1331 input_other->HasOnlyOneNonEnvironmentUse() &&
1332 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1333 instruction->ReplaceWith(input_other);
1334 instruction->GetBlock()->RemoveInstruction(instruction);
1335 } else {
1336 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1337 new_type, input_other, instruction->GetDexPc());
1338 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1339 }
1340 RecordSimplification();
1341 return;
1342 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001343 }
1344
1345 // We assume that GVN has run before, so we only perform a pointer comparison.
1346 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001347 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001348 if (instruction->GetLeft() == instruction->GetRight()) {
1349 // Replace code looking like
1350 // AND dst, src, src
1351 // with
1352 // src
1353 instruction->ReplaceWith(instruction->GetLeft());
1354 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001355 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001356 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001357 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001358
Anton Kirilove14dc862016-05-13 17:56:15 +01001359 if (TryDeMorganNegationFactoring(instruction)) {
1360 return;
1361 }
1362
1363 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1364 // so no need to return.
1365 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001366}
1367
Mark Mendellc4701932015-04-10 13:18:51 -04001368void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1369 VisitCondition(condition);
1370}
1371
1372void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1373 VisitCondition(condition);
1374}
1375
1376void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1377 VisitCondition(condition);
1378}
1379
1380void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1381 VisitCondition(condition);
1382}
1383
Anton Shaminbdd79352016-02-15 12:48:36 +06001384void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1385 VisitCondition(condition);
1386}
1387
1388void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1389 VisitCondition(condition);
1390}
1391
1392void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1393 VisitCondition(condition);
1394}
1395
1396void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1397 VisitCondition(condition);
1398}
Aart Bike9f37602015-10-09 11:15:55 -07001399
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001400// Recognize the following pattern:
1401// obj.getClass() ==/!= Foo.class
1402// And replace it with a constant value if the type of `obj` is statically known.
1403static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1404 HInstruction* input_one = condition->InputAt(0);
1405 HInstruction* input_two = condition->InputAt(1);
1406 HLoadClass* load_class = input_one->IsLoadClass()
1407 ? input_one->AsLoadClass()
1408 : input_two->AsLoadClass();
1409 if (load_class == nullptr) {
1410 return false;
1411 }
1412
1413 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1414 if (!class_rti.IsValid()) {
1415 // Unresolved class.
1416 return false;
1417 }
1418
1419 HInstanceFieldGet* field_get = (load_class == input_one)
1420 ? input_two->AsInstanceFieldGet()
1421 : input_one->AsInstanceFieldGet();
1422 if (field_get == nullptr) {
1423 return false;
1424 }
1425
1426 HInstruction* receiver = field_get->InputAt(0);
1427 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1428 if (!receiver_type.IsExact()) {
1429 return false;
1430 }
1431
1432 {
1433 ScopedObjectAccess soa(Thread::Current());
1434 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1435 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1436 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1437 if (field_get->GetFieldInfo().GetField() != field) {
1438 return false;
1439 }
1440
1441 // We can replace the compare.
1442 int value = 0;
1443 if (receiver_type.IsEqual(class_rti)) {
1444 value = condition->IsEqual() ? 1 : 0;
1445 } else {
1446 value = condition->IsNotEqual() ? 1 : 0;
1447 }
1448 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1449 return true;
1450 }
1451}
1452
Mark Mendellc4701932015-04-10 13:18:51 -04001453void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001454 if (condition->IsEqual() || condition->IsNotEqual()) {
1455 if (RecognizeAndSimplifyClassCheck(condition)) {
1456 return;
1457 }
1458 }
1459
Anton Shaminbdd79352016-02-15 12:48:36 +06001460 // Reverse condition if left is constant. Our code generators prefer constant
1461 // on the right hand side.
1462 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1463 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001464 HCondition* replacement =
1465 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001466 // If it is a fp we must set the opposite bias.
1467 if (replacement != nullptr) {
1468 if (condition->IsLtBias()) {
1469 replacement->SetBias(ComparisonBias::kGtBias);
1470 } else if (condition->IsGtBias()) {
1471 replacement->SetBias(ComparisonBias::kLtBias);
1472 }
1473 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1474 RecordSimplification();
1475
1476 condition = replacement;
1477 }
1478 }
Mark Mendellc4701932015-04-10 13:18:51 -04001479
Mark Mendellc4701932015-04-10 13:18:51 -04001480 HInstruction* left = condition->GetLeft();
1481 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001482
1483 // Try to fold an HCompare into this HCondition.
1484
Mark Mendellc4701932015-04-10 13:18:51 -04001485 // We can only replace an HCondition which compares a Compare to 0.
1486 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1487 // condition with a long, float or double comparison as input.
1488 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1489 // Conversion is not possible.
1490 return;
1491 }
1492
1493 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001494 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001495 // Someone else also wants the result of the compare.
1496 return;
1497 }
1498
Vladimir Marko46817b82016-03-29 12:21:58 +01001499 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001500 // There is a reference to the compare result in an environment. Do we really need it?
1501 if (GetGraph()->IsDebuggable()) {
1502 return;
1503 }
1504
1505 // We have to ensure that there are no deopt points in the sequence.
1506 if (left->HasAnyEnvironmentUseBefore(condition)) {
1507 return;
1508 }
1509 }
1510
1511 // Clean up any environment uses from the HCompare, if any.
1512 left->RemoveEnvironmentUsers();
1513
1514 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1515 condition->SetBias(left->AsCompare()->GetBias());
1516
1517 // Replace the operands of the HCondition.
1518 condition->ReplaceInput(left->InputAt(0), 0);
1519 condition->ReplaceInput(left->InputAt(1), 1);
1520
1521 // Remove the HCompare.
1522 left->GetBlock()->RemoveInstruction(left);
1523
1524 RecordSimplification();
1525}
1526
Andreas Gampe9186ced2016-12-12 14:28:21 -08001527// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1528static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1529 // True, if the most significant bits of divisor are 0.
1530 return ((divisor & 0x7fffff) == 0);
1531}
1532
1533// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1534static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1535 // True, if the most significant bits of divisor are 0.
1536 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1537}
1538
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001539void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1540 HConstant* input_cst = instruction->GetConstantRight();
1541 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001542 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001543
1544 if ((input_cst != nullptr) && input_cst->IsOne()) {
1545 // Replace code looking like
1546 // DIV dst, src, 1
1547 // with
1548 // src
1549 instruction->ReplaceWith(input_other);
1550 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001551 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001552 return;
1553 }
1554
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001555 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001556 // Replace code looking like
1557 // DIV dst, src, -1
1558 // with
1559 // NEG dst, src
1560 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001561 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001562 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001563 return;
1564 }
1565
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001567 // Try replacing code looking like
1568 // DIV dst, src, constant
1569 // with
1570 // MUL dst, src, 1 / constant
1571 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001573 double value = input_cst->AsDoubleConstant()->GetValue();
1574 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1575 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1576 }
1577 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001578 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001579 float value = input_cst->AsFloatConstant()->GetValue();
1580 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1581 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1582 }
1583 }
1584
1585 if (reciprocal != nullptr) {
1586 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001587 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001588 RecordSimplification();
1589 return;
1590 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001591 }
1592}
1593
1594void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1595 HConstant* input_cst = instruction->GetConstantRight();
1596 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001597 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001598 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001599 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001600
1601 if (input_cst == nullptr) {
1602 return;
1603 }
1604
1605 if (input_cst->IsOne()) {
1606 // Replace code looking like
1607 // MUL dst, src, 1
1608 // with
1609 // src
1610 instruction->ReplaceWith(input_other);
1611 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001612 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001613 return;
1614 }
1615
1616 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001617 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001618 // Replace code looking like
1619 // MUL dst, src, -1
1620 // with
1621 // NEG dst, src
1622 HNeg* neg = new (allocator) HNeg(type, input_other);
1623 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001624 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001625 return;
1626 }
1627
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001629 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1630 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1631 // Replace code looking like
1632 // FP_MUL dst, src, 2.0
1633 // with
1634 // FP_ADD dst, src, src
1635 // The 'int' and 'long' cases are handled below.
1636 block->ReplaceAndRemoveInstructionWith(instruction,
1637 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001638 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001639 return;
1640 }
1641
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001642 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001643 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001644 // Even though constant propagation also takes care of the zero case, other
1645 // optimizations can lead to having a zero multiplication.
1646 if (factor == 0) {
1647 // Replace code looking like
1648 // MUL dst, src, 0
1649 // with
1650 // 0
1651 instruction->ReplaceWith(input_cst);
1652 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001653 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001654 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001655 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001656 // Replace code looking like
1657 // MUL dst, src, pow_of_2
1658 // with
1659 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001660 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001661 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001662 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001663 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001664 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001665 } else if (IsPowerOfTwo(factor - 1)) {
1666 // Transform code looking like
1667 // MUL dst, src, (2^n + 1)
1668 // into
1669 // SHL tmp, src, n
1670 // ADD dst, src, tmp
1671 HShl* shl = new (allocator) HShl(type,
1672 input_other,
1673 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1674 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1675
1676 block->InsertInstructionBefore(shl, instruction);
1677 block->ReplaceAndRemoveInstructionWith(instruction, add);
1678 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001679 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001680 } else if (IsPowerOfTwo(factor + 1)) {
1681 // Transform code looking like
1682 // MUL dst, src, (2^n - 1)
1683 // into
1684 // SHL tmp, src, n
1685 // SUB dst, tmp, src
1686 HShl* shl = new (allocator) HShl(type,
1687 input_other,
1688 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1689 HSub* sub = new (allocator) HSub(type, shl, input_other);
1690
1691 block->InsertInstructionBefore(shl, instruction);
1692 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1693 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001694 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001695 }
1696 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001697
1698 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1699 // so no need to return.
1700 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001701}
1702
Alexandre Rames188d4312015-04-09 18:30:21 +01001703void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1704 HInstruction* input = instruction->GetInput();
1705 if (input->IsNeg()) {
1706 // Replace code looking like
1707 // NEG tmp, src
1708 // NEG dst, tmp
1709 // with
1710 // src
1711 HNeg* previous_neg = input->AsNeg();
1712 instruction->ReplaceWith(previous_neg->GetInput());
1713 instruction->GetBlock()->RemoveInstruction(instruction);
1714 // We perform the optimization even if the input negation has environment
1715 // uses since it allows removing the current instruction. But we only delete
1716 // the input negation only if it is does not have any uses left.
1717 if (!previous_neg->HasUses()) {
1718 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1719 }
1720 RecordSimplification();
1721 return;
1722 }
1723
Serguei Katkov339dfc22015-04-20 12:29:32 +06001724 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001725 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001726 // Replace code looking like
1727 // SUB tmp, a, b
1728 // NEG dst, tmp
1729 // with
1730 // SUB dst, b, a
1731 // We do not perform the optimization if the input subtraction has
1732 // environment uses or multiple non-environment uses as it could lead to
1733 // worse code. In particular, we do not want the live ranges of `a` and `b`
1734 // to be extended if we are not sure the initial 'SUB' instruction can be
1735 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001736 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001737 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001738 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1739 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001740 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1741 if (!sub->HasUses()) {
1742 sub->GetBlock()->RemoveInstruction(sub);
1743 }
1744 RecordSimplification();
1745 }
1746}
1747
1748void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1749 HInstruction* input = instruction->GetInput();
1750 if (input->IsNot()) {
1751 // Replace code looking like
1752 // NOT tmp, src
1753 // NOT dst, tmp
1754 // with
1755 // src
1756 // We perform the optimization even if the input negation has environment
1757 // uses since it allows removing the current instruction. But we only delete
1758 // the input negation only if it is does not have any uses left.
1759 HNot* previous_not = input->AsNot();
1760 instruction->ReplaceWith(previous_not->GetInput());
1761 instruction->GetBlock()->RemoveInstruction(instruction);
1762 if (!previous_not->HasUses()) {
1763 previous_not->GetBlock()->RemoveInstruction(previous_not);
1764 }
1765 RecordSimplification();
1766 }
1767}
1768
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001769void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1770 HConstant* input_cst = instruction->GetConstantRight();
1771 HInstruction* input_other = instruction->GetLeastConstantLeft();
1772
Roland Levillain1a653882016-03-18 18:05:57 +00001773 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001774 // Replace code looking like
1775 // OR dst, src, 0
1776 // with
1777 // src
1778 instruction->ReplaceWith(input_other);
1779 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001780 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001781 return;
1782 }
1783
1784 // We assume that GVN has run before, so we only perform a pointer comparison.
1785 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001786 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001787 if (instruction->GetLeft() == instruction->GetRight()) {
1788 // Replace code looking like
1789 // OR dst, src, src
1790 // with
1791 // src
1792 instruction->ReplaceWith(instruction->GetLeft());
1793 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001794 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001795 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001796 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001797
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001798 if (TryDeMorganNegationFactoring(instruction)) return;
1799
Anton Kirilove14dc862016-05-13 17:56:15 +01001800 if (TryReplaceWithRotate(instruction)) {
1801 return;
1802 }
1803
1804 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1805 // so no need to return.
1806 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001807}
1808
1809void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1810 VisitShift(instruction);
1811}
1812
1813void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1814 VisitShift(instruction);
1815}
1816
1817void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1818 HConstant* input_cst = instruction->GetConstantRight();
1819 HInstruction* input_other = instruction->GetLeastConstantLeft();
1820
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001821 DataType::Type type = instruction->GetType();
1822 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001823 return;
1824 }
1825
Roland Levillain1a653882016-03-18 18:05:57 +00001826 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001827 // Replace code looking like
1828 // SUB dst, src, 0
1829 // with
1830 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001831 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1832 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1833 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001834 instruction->ReplaceWith(input_other);
1835 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001836 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001837 return;
1838 }
1839
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001840 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001841 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001842
Alexandre Rames188d4312015-04-09 18:30:21 +01001843 HInstruction* left = instruction->GetLeft();
1844 HInstruction* right = instruction->GetRight();
1845 if (left->IsConstant()) {
1846 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001847 // Replace code looking like
1848 // SUB dst, 0, src
1849 // with
1850 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001851 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001852 // `x` is `0.0`, the former expression yields `0.0`, while the later
1853 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001854 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001855 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001856 RecordSimplification();
1857 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001858 }
1859 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001860
1861 if (left->IsNeg() && right->IsNeg()) {
1862 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1863 return;
1864 }
1865 }
1866
1867 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1868 // Replace code looking like
1869 // NEG tmp, b
1870 // SUB dst, a, tmp
1871 // with
1872 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001873 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001874 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1875 RecordSimplification();
1876 right->GetBlock()->RemoveInstruction(right);
1877 return;
1878 }
1879
1880 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1881 // Replace code looking like
1882 // NEG tmp, a
1883 // SUB dst, tmp, b
1884 // with
1885 // ADD tmp, a, b
1886 // NEG dst, tmp
1887 // The second version is not intrinsically better, but enables more
1888 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001889 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01001890 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001891 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01001892 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1893 instruction->ReplaceWith(neg);
1894 instruction->GetBlock()->RemoveInstruction(instruction);
1895 RecordSimplification();
1896 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001897 return;
1898 }
1899
1900 if (TrySubtractionChainSimplification(instruction)) {
1901 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001902 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001903
1904 if (left->IsAdd()) {
1905 // Replace code patterns looking like
1906 // ADD dst1, x, y ADD dst1, x, y
1907 // SUB dst2, dst1, y SUB dst2, dst1, x
1908 // with
1909 // ADD dst1, x, y
1910 // SUB instruction is not needed in this case, we may use
1911 // one of inputs of ADD instead.
1912 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001913 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001914 if (left->InputAt(1) == right) {
1915 instruction->ReplaceWith(left->InputAt(0));
1916 RecordSimplification();
1917 instruction->GetBlock()->RemoveInstruction(instruction);
1918 return;
1919 } else if (left->InputAt(0) == right) {
1920 instruction->ReplaceWith(left->InputAt(1));
1921 RecordSimplification();
1922 instruction->GetBlock()->RemoveInstruction(instruction);
1923 return;
1924 }
1925 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001926}
1927
1928void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1929 VisitShift(instruction);
1930}
1931
1932void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1933 HConstant* input_cst = instruction->GetConstantRight();
1934 HInstruction* input_other = instruction->GetLeastConstantLeft();
1935
Roland Levillain1a653882016-03-18 18:05:57 +00001936 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001937 // Replace code looking like
1938 // XOR dst, src, 0
1939 // with
1940 // src
1941 instruction->ReplaceWith(input_other);
1942 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001943 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001944 return;
1945 }
1946
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001947 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001948 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001949 // Replace code looking like
1950 // XOR dst, src, 1
1951 // with
1952 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001953 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001954 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1955 RecordSimplification();
1956 return;
1957 }
1958
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001959 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1960 // Replace code looking like
1961 // XOR dst, src, 0xFFF...FF
1962 // with
1963 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001964 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001965 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001966 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001967 return;
1968 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001969
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001970 HInstruction* left = instruction->GetLeft();
1971 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001972 if (((left->IsNot() && right->IsNot()) ||
1973 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001974 left->HasOnlyOneNonEnvironmentUse() &&
1975 right->HasOnlyOneNonEnvironmentUse()) {
1976 // Replace code looking like
1977 // NOT nota, a
1978 // NOT notb, b
1979 // XOR dst, nota, notb
1980 // with
1981 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001982 instruction->ReplaceInput(left->InputAt(0), 0);
1983 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001984 left->GetBlock()->RemoveInstruction(left);
1985 right->GetBlock()->RemoveInstruction(right);
1986 RecordSimplification();
1987 return;
1988 }
1989
Anton Kirilove14dc862016-05-13 17:56:15 +01001990 if (TryReplaceWithRotate(instruction)) {
1991 return;
1992 }
1993
1994 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1995 // so no need to return.
1996 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001997}
1998
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001999void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2000 HInstruction* argument = instruction->InputAt(1);
2001 HInstruction* receiver = instruction->InputAt(0);
2002 if (receiver == argument) {
2003 // Because String.equals is an instance call, the receiver is
2004 // a null check if we don't know it's null. The argument however, will
2005 // be the actual object. So we cannot end up in a situation where both
2006 // are equal but could be null.
2007 DCHECK(CanEnsureNotNullAt(argument, instruction));
2008 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2009 instruction->GetBlock()->RemoveInstruction(instruction);
2010 } else {
2011 StringEqualsOptimizations optimizations(instruction);
2012 if (CanEnsureNotNullAt(argument, instruction)) {
2013 optimizations.SetArgumentNotNull();
2014 }
2015 ScopedObjectAccess soa(Thread::Current());
2016 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2017 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2018 optimizations.SetArgumentIsString();
2019 }
2020 }
2021}
2022
Roland Levillain22c49222016-03-18 14:04:28 +00002023void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2024 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002025 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002026 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002027 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002028 HInstruction* value = invoke->InputAt(0);
2029 HInstruction* distance = invoke->InputAt(1);
2030 // Replace the invoke with an HRor.
2031 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002032 // Unconditionally set the type of the negated distance to `int`,
2033 // as shift and rotate operations expect a 32-bit (or narrower)
2034 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002035 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002036 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2037 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002038 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002039 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2040 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002041 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002042 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2043 clinit->GetBlock()->RemoveInstruction(clinit);
2044 HInstruction* ldclass = clinit->InputAt(0);
2045 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2046 ldclass->GetBlock()->RemoveInstruction(ldclass);
2047 }
2048 }
2049}
2050
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002051static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2052 if (potential_length->IsArrayLength()) {
2053 return potential_length->InputAt(0) == potential_array;
2054 }
2055
2056 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002057 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002058 }
2059
2060 return false;
2061}
2062
2063void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2064 HInstruction* source = instruction->InputAt(0);
2065 HInstruction* destination = instruction->InputAt(2);
2066 HInstruction* count = instruction->InputAt(4);
2067 SystemArrayCopyOptimizations optimizations(instruction);
2068 if (CanEnsureNotNullAt(source, instruction)) {
2069 optimizations.SetSourceIsNotNull();
2070 }
2071 if (CanEnsureNotNullAt(destination, instruction)) {
2072 optimizations.SetDestinationIsNotNull();
2073 }
2074 if (destination == source) {
2075 optimizations.SetDestinationIsSource();
2076 }
2077
2078 if (IsArrayLengthOf(count, source)) {
2079 optimizations.SetCountIsSourceLength();
2080 }
2081
2082 if (IsArrayLengthOf(count, destination)) {
2083 optimizations.SetCountIsDestinationLength();
2084 }
2085
2086 {
2087 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002088 DataType::Type source_component_type = DataType::Type::kVoid;
2089 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002090 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2091 if (destination_rti.IsValid()) {
2092 if (destination_rti.IsObjectArray()) {
2093 if (destination_rti.IsExact()) {
2094 optimizations.SetDoesNotNeedTypeCheck();
2095 }
2096 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002097 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002098 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002099 destination_component_type = DataTypeFromPrimitive(
2100 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002101 optimizations.SetDestinationIsPrimitiveArray();
2102 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2103 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002104 }
2105 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002106 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2107 if (source_rti.IsValid()) {
2108 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2109 optimizations.SetDoesNotNeedTypeCheck();
2110 }
2111 if (source_rti.IsPrimitiveArrayClass()) {
2112 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002113 source_component_type = DataTypeFromPrimitive(
2114 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002115 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2116 optimizations.SetSourceIsNonPrimitiveArray();
2117 }
2118 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002119 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002120 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002121 (source_component_type == destination_component_type)) {
2122 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2123 PointerSize image_size = class_linker->GetImagePointerSize();
2124 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2125 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2126 ArtMethod* method = nullptr;
2127 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002128 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002129 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002130 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002131 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002132 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002133 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002134 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002135 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002136 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002137 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002138 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002139 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002140 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002141 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002142 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002143 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002144 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002145 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002146 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002147 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002148 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002149 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002150 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002151 break;
2152 default:
2153 LOG(FATAL) << "Unreachable";
2154 }
2155 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002156 DCHECK(method->IsStatic());
2157 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002158 invoke->SetResolvedMethod(method);
2159 // Sharpen the new invoke. Note that we do not update the dex method index of
2160 // the invoke, as we would need to look it up in the current dex file, and it
2161 // is unlikely that it exists. The most usual situation for such typed
2162 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002163 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002164 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002165 }
2166}
2167
Roland Levillaina5c4a402016-03-15 15:02:50 +00002168void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2169 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002170 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002171 DCHECK(invoke->IsInvokeStaticOrDirect());
2172 uint32_t dex_pc = invoke->GetDexPc();
2173 HInstruction* left = invoke->InputAt(0);
2174 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002175 if (!is_signum) {
2176 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002177 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002178 right = GetGraph()->GetLongConstant(0);
2179 } else {
2180 right = GetGraph()->GetIntConstant(0);
2181 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002182 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002183 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2184 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2185}
2186
Aart Bik75a38b22016-02-17 10:41:50 -08002187void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2188 DCHECK(invoke->IsInvokeStaticOrDirect());
2189 uint32_t dex_pc = invoke->GetDexPc();
2190 // IsNaN(x) is the same as x != x.
2191 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002192 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002193 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002194 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2195}
2196
Aart Bik2a6aad92016-02-25 11:32:32 -08002197void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2198 DCHECK(invoke->IsInvokeStaticOrDirect());
2199 uint32_t dex_pc = invoke->GetDexPc();
2200 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002201 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002202 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2203 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002204 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002205 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2206 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2207 kNeedsEnvironmentOrCache,
2208 kNoSideEffects,
2209 kNoThrow);
2210 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002211 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002212 nan = GetGraph()->GetIntConstant(0x7fc00000);
2213 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2214 kNeedsEnvironmentOrCache,
2215 kNoSideEffects,
2216 kNoThrow);
2217 }
2218 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002219 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002220 condition->SetBias(ComparisonBias::kLtBias);
2221 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2222 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002223 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002224 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2225 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2226}
2227
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002228void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2229 HInstruction* str = invoke->InputAt(0);
2230 HInstruction* index = invoke->InputAt(1);
2231 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002232 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002233 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2234 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002235 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002236 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002237 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002238 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002239 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002240 HArrayGet* array_get = new (allocator) HArrayGet(str,
2241 bounds_check,
2242 DataType::Type::kUint16,
2243 SideEffects::None(), // Strings are immutable.
2244 dex_pc,
2245 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002246 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2247 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2248 GetGraph()->SetHasBoundsChecks(true);
2249}
2250
Vladimir Markodce016e2016-04-28 13:10:02 +01002251void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2252 HInstruction* str = invoke->InputAt(0);
2253 uint32_t dex_pc = invoke->GetDexPc();
2254 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2255 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002256 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002257 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002258 HInstruction* replacement;
2259 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2260 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2261 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2262 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002263 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002264 replacement = equal;
2265 } else {
2266 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2267 replacement = length;
2268 }
2269 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2270}
2271
Aart Bikff7d89c2016-11-07 08:49:28 -08002272// This method should only be used on intrinsics whose sole way of throwing an
2273// exception is raising a NPE when the nth argument is null. If that argument
2274// is provably non-null, we can clear the flag.
2275void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2276 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002277 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002278 invoke->SetCanThrow(false);
2279 }
2280}
2281
Aart Bik71bf7b42016-11-16 10:17:46 -08002282// Methods that return "this" can replace the returned value with the receiver.
2283void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2284 if (invoke->HasUses()) {
2285 HInstruction* receiver = invoke->InputAt(0);
2286 invoke->ReplaceWith(receiver);
2287 RecordSimplification();
2288 }
2289}
2290
2291// Helper method for StringBuffer escape analysis.
2292static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2293 if (user->IsInvokeStaticOrDirect()) {
2294 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002295 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2296 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002297 user->InputAt(0) == reference;
2298 } else if (user->IsInvokeVirtual()) {
2299 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2300 case Intrinsics::kStringBufferLength:
2301 case Intrinsics::kStringBufferToString:
2302 DCHECK_EQ(user->InputAt(0), reference);
2303 return true;
2304 case Intrinsics::kStringBufferAppend:
2305 // Returns "this", so only okay if no further uses.
2306 DCHECK_EQ(user->InputAt(0), reference);
2307 DCHECK_NE(user->InputAt(1), reference);
2308 return !user->HasUses();
2309 default:
2310 break;
2311 }
2312 }
2313 return false;
2314}
2315
2316// Certain allocation intrinsics are not removed by dead code elimination
2317// because of potentially throwing an OOM exception or other side effects.
2318// This method removes such intrinsics when special circumstances allow.
2319void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2320 if (!invoke->HasUses()) {
2321 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2322 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2323 // call does not escape since only thread-local synchronization may be removed.
2324 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2325 HInstruction* receiver = invoke->InputAt(0);
2326 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2327 invoke->GetBlock()->RemoveInstruction(invoke);
2328 RecordSimplification();
2329 }
2330 }
2331}
2332
Vladimir Markoca6fff82017-10-03 14:49:14 +01002333void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2334 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002335 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002336 HMemoryBarrier* mem_barrier =
2337 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002338 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2339}
2340
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002341void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002342 switch (instruction->GetIntrinsic()) {
2343 case Intrinsics::kStringEquals:
2344 SimplifyStringEquals(instruction);
2345 break;
2346 case Intrinsics::kSystemArrayCopy:
2347 SimplifySystemArrayCopy(instruction);
2348 break;
2349 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002350 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002351 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002352 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002353 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002354 break;
2355 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002356 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002357 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002358 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002359 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002360 break;
2361 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002362 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002363 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002364 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002365 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002366 break;
2367 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002368 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002369 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002370 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002371 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002372 break;
2373 case Intrinsics::kFloatIsNaN:
2374 case Intrinsics::kDoubleIsNaN:
2375 SimplifyIsNaN(instruction);
2376 break;
2377 case Intrinsics::kFloatFloatToIntBits:
2378 case Intrinsics::kDoubleDoubleToLongBits:
2379 SimplifyFP2Int(instruction);
2380 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002381 case Intrinsics::kStringCharAt:
2382 SimplifyStringCharAt(instruction);
2383 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002384 case Intrinsics::kStringIsEmpty:
2385 case Intrinsics::kStringLength:
2386 SimplifyStringIsEmptyOrLength(instruction);
2387 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002388 case Intrinsics::kStringStringIndexOf:
2389 case Intrinsics::kStringStringIndexOfAfter:
2390 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2391 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002392 case Intrinsics::kStringBufferAppend:
2393 case Intrinsics::kStringBuilderAppend:
2394 SimplifyReturnThis(instruction);
2395 break;
2396 case Intrinsics::kStringBufferToString:
2397 case Intrinsics::kStringBuilderToString:
2398 SimplifyAllocationIntrinsic(instruction);
2399 break;
Aart Bik11932592016-03-08 12:42:25 -08002400 case Intrinsics::kUnsafeLoadFence:
2401 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2402 break;
2403 case Intrinsics::kUnsafeStoreFence:
2404 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2405 break;
2406 case Intrinsics::kUnsafeFullFence:
2407 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2408 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002409 case Intrinsics::kVarHandleFullFence:
2410 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2411 break;
2412 case Intrinsics::kVarHandleAcquireFence:
2413 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2414 break;
2415 case Intrinsics::kVarHandleReleaseFence:
2416 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2417 break;
2418 case Intrinsics::kVarHandleLoadLoadFence:
2419 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2420 break;
2421 case Intrinsics::kVarHandleStoreStoreFence:
2422 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2423 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002424 default:
2425 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002426 }
2427}
2428
Aart Bikbb245d12015-10-19 11:05:03 -07002429void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2430 HInstruction* cond = deoptimize->InputAt(0);
2431 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002432 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002433 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002434 if (deoptimize->GuardsAnInput()) {
2435 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2436 }
Aart Bikbb245d12015-10-19 11:05:03 -07002437 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2438 } else {
2439 // Always deopt.
2440 }
2441 }
2442}
2443
Anton Kirilove14dc862016-05-13 17:56:15 +01002444// Replace code looking like
2445// OP y, x, const1
2446// OP z, y, const2
2447// with
2448// OP z, x, const3
2449// where OP is both an associative and a commutative operation.
2450bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2451 HBinaryOperation* instruction) {
2452 DCHECK(instruction->IsCommutative());
2453
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002454 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002455 return false;
2456 }
2457
2458 HInstruction* left = instruction->GetLeft();
2459 HInstruction* right = instruction->GetRight();
2460 // Variable names as described above.
2461 HConstant* const2;
2462 HBinaryOperation* y;
2463
2464 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2465 const2 = right->AsConstant();
2466 y = left->AsBinaryOperation();
2467 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2468 const2 = left->AsConstant();
2469 y = right->AsBinaryOperation();
2470 } else {
2471 // The node does not match the pattern.
2472 return false;
2473 }
2474
2475 // If `y` has more than one use, we do not perform the optimization
2476 // because it might increase code size (e.g. if the new constant is
2477 // no longer encodable as an immediate operand in the target ISA).
2478 if (!y->HasOnlyOneNonEnvironmentUse()) {
2479 return false;
2480 }
2481
2482 // GetConstantRight() can return both left and right constants
2483 // for commutative operations.
2484 HConstant* const1 = y->GetConstantRight();
2485 if (const1 == nullptr) {
2486 return false;
2487 }
2488
2489 instruction->ReplaceInput(const1, 0);
2490 instruction->ReplaceInput(const2, 1);
2491 HConstant* const3 = instruction->TryStaticEvaluation();
2492 DCHECK(const3 != nullptr);
2493 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2494 instruction->ReplaceInput(const3, 1);
2495 RecordSimplification();
2496 return true;
2497}
2498
2499static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2500 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2501}
2502
2503// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002504static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002505 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002506 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002507 return HAdd::Compute<int32_t>(x, y);
2508 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002509 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002510 return HAdd::Compute<int64_t>(x, y);
2511 }
2512}
2513
2514// Helper function that handles the child classes of HConstant
2515// and returns an integer with the appropriate sign.
2516static int64_t GetValue(HConstant* constant, bool is_negated) {
2517 int64_t ret = Int64FromConstant(constant);
2518 return is_negated ? -ret : ret;
2519}
2520
2521// Replace code looking like
2522// OP1 y, x, const1
2523// OP2 z, y, const2
2524// with
2525// OP3 z, x, const3
2526// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2527bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2528 HBinaryOperation* instruction) {
2529 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2530
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002531 DataType::Type type = instruction->GetType();
2532 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002533 return false;
2534 }
2535
2536 HInstruction* left = instruction->GetLeft();
2537 HInstruction* right = instruction->GetRight();
2538 // Variable names as described above.
2539 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2540 if (const2 == nullptr) {
2541 return false;
2542 }
2543
2544 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2545 ? left->AsBinaryOperation()
2546 : AsAddOrSub(right);
2547 // If y has more than one use, we do not perform the optimization because
2548 // it might increase code size (e.g. if the new constant is no longer
2549 // encodable as an immediate operand in the target ISA).
2550 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2551 return false;
2552 }
2553
2554 left = y->GetLeft();
2555 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2556 if (const1 == nullptr) {
2557 return false;
2558 }
2559
2560 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2561 // If both inputs are constants, let the constant folding pass deal with it.
2562 if (x->IsConstant()) {
2563 return false;
2564 }
2565
2566 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2567 int64_t const2_val = GetValue(const2, is_const2_negated);
2568 bool is_y_negated = (y == right) && instruction->IsSub();
2569 right = y->GetRight();
2570 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2571 int64_t const1_val = GetValue(const1, is_const1_negated);
2572 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2573 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2574 HBasicBlock* block = instruction->GetBlock();
2575 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002576 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002577 HInstruction* z;
2578
2579 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002580 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002581 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002582 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002583 }
2584
2585 block->ReplaceAndRemoveInstructionWith(instruction, z);
2586 RecordSimplification();
2587 return true;
2588}
2589
Lena Djokicbc5460b2017-07-20 16:07:36 +02002590void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2591 if (TryCombineVecMultiplyAccumulate(instruction)) {
2592 RecordSimplification();
2593 }
2594}
2595
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002596} // namespace art