blob: e13c8eafaf13f8e771983dc38b9660c0b3403040 [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 Marko5868ada2020-05-12 11:50:34 +010021#include "class_root-inl.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010022#include "data_type-inl.h"
Vladimir Marko9d31daa2022-04-14 10:48:44 +010023#include "driver/compiler_options.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080024#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025#include "intrinsics.h"
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +000026#include "intrinsics_utils.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027#include "mirror/class-inl.h"
Artem Serove91a9542021-10-25 16:23:27 +010028#include "optimizing/data_type.h"
Alex Light3a73ffb2021-01-25 14:11:05 +000029#include "optimizing/nodes.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070031#include "sharpening.h"
Vladimir Marko552a1342017-10-31 10:56:47 +000032#include "string_builder_append.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000033
VladimĂ­r Marko434d9682022-11-04 14:04:17 +000034namespace art HIDDEN {
Nicolas Geoffray3c049742014-09-24 18:10:46 +010035
Artem Serovcced8ba2017-07-19 18:18:09 +010036// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
37// is replaced with its copy if it is clonable.
38static constexpr bool kTestInstructionClonerExhaustively = false;
39
Vladimir Marko30759fa2023-04-05 09:43:21 +020040class InstructionSimplifierVisitor final : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000041 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 InstructionSimplifierVisitor(HGraph* graph,
43 CodeGenerator* codegen,
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010044 OptimizingCompilerStats* stats,
45 bool be_loop_friendly)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010046 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000047 codegen_(codegen),
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010048 stats_(stats),
49 be_loop_friendly_(be_loop_friendly) {}
Alexandre Rames188d4312015-04-09 18:30:21 +010050
Aart Bik24773202018-04-26 10:28:51 -070051 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000052
53 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010054 void RecordSimplification() {
55 simplification_occurred_ = true;
56 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000057 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010058 }
59
Scott Wakeling40a04bf2015-12-11 09:50:36 +000060 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
61 bool TryReplaceWithRotate(HBinaryOperation* instruction);
62 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
63 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
64 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
65
Alexandre Rames188d4312015-04-09 18:30:21 +010066 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000067 // `op` should be either HOr or HAnd.
68 // De Morgan's laws:
69 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
70 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010071 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
72 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020073 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010074 void TryToReuseDiv(HRem* rem);
Anton Kirilove14dc862016-05-13 17:56:15 +010075
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000076 void VisitShift(HBinaryOperation* shift);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010077 void VisitEqual(HEqual* equal) override;
78 void VisitNotEqual(HNotEqual* equal) override;
79 void VisitBooleanNot(HBooleanNot* bool_not) override;
80 void VisitInstanceFieldSet(HInstanceFieldSet* equal) override;
81 void VisitStaticFieldSet(HStaticFieldSet* equal) override;
82 void VisitArraySet(HArraySet* equal) override;
83 void VisitTypeConversion(HTypeConversion* instruction) override;
84 void VisitNullCheck(HNullCheck* instruction) override;
85 void VisitArrayLength(HArrayLength* instruction) override;
86 void VisitCheckCast(HCheckCast* instruction) override;
87 void VisitAbs(HAbs* instruction) override;
88 void VisitAdd(HAdd* instruction) override;
89 void VisitAnd(HAnd* instruction) override;
90 void VisitCondition(HCondition* instruction) override;
91 void VisitGreaterThan(HGreaterThan* condition) override;
92 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) override;
93 void VisitLessThan(HLessThan* condition) override;
94 void VisitLessThanOrEqual(HLessThanOrEqual* condition) override;
95 void VisitBelow(HBelow* condition) override;
96 void VisitBelowOrEqual(HBelowOrEqual* condition) override;
97 void VisitAbove(HAbove* condition) override;
98 void VisitAboveOrEqual(HAboveOrEqual* condition) override;
99 void VisitDiv(HDiv* instruction) override;
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100100 void VisitRem(HRem* instruction) override;
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100101 void VisitMul(HMul* instruction) override;
102 void VisitNeg(HNeg* instruction) override;
103 void VisitNot(HNot* instruction) override;
104 void VisitOr(HOr* instruction) override;
105 void VisitShl(HShl* instruction) override;
106 void VisitShr(HShr* instruction) override;
107 void VisitSub(HSub* instruction) override;
108 void VisitUShr(HUShr* instruction) override;
109 void VisitXor(HXor* instruction) override;
110 void VisitSelect(HSelect* select) override;
111 void VisitIf(HIf* instruction) override;
112 void VisitInstanceOf(HInstanceOf* instruction) override;
113 void VisitInvoke(HInvoke* invoke) override;
114 void VisitDeoptimize(HDeoptimize* deoptimize) override;
115 void VisitVecMul(HVecMul* instruction) override;
Alex Light3a73ffb2021-01-25 14:11:05 +0000116 void VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet* instruction) override;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100117 void SimplifySystemArrayCopy(HInvoke* invoke);
118 void SimplifyStringEquals(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800119 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100120 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Marko5f846072020-04-09 13:20:11 +0100121 void SimplifyStringLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000122 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800123 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800124 void SimplifyReturnThis(HInvoke* invoke);
125 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +0000126 void SimplifyVarHandleIntrinsic(HInvoke* invoke);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100127
Vladimir Marko9d31daa2022-04-14 10:48:44 +0100128 bool CanUseKnownBootImageVarHandle(HInvoke* invoke);
Ulya Trafimovich3676b362021-09-02 16:13:51 +0100129 static bool CanEnsureNotNullAt(HInstruction* input, HInstruction* at);
130
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000131 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000132 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100133 bool simplification_occurred_ = false;
134 int simplifications_at_current_position_ = 0;
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100135 // Prohibit optimizations which can affect HInductionVarAnalysis/HLoopOptimization
136 // and prevent loop optimizations:
137 // true - avoid such optimizations.
138 // false - allow such optimizations.
139 // Checked by the following optimizations:
140 // - TryToReuseDiv: simplification of Div+Rem into Div+Mul+Sub.
141 bool be_loop_friendly_;
Aart Bik2767f4b2016-10-28 15:03:53 -0700142 // We ensure we do not loop infinitely. The value should not be too high, since that
143 // would allow looping around the same basic block too many times. The value should
144 // not be too low either, however, since we want to allow revisiting a basic block
145 // with many statements and simplifications at least once.
146 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000147};
148
Aart Bik24773202018-04-26 10:28:51 -0700149bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100150 if (kTestInstructionClonerExhaustively) {
151 CloneAndReplaceInstructionVisitor visitor(graph_);
152 visitor.VisitReversePostOrder();
153 }
154
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100155 bool be_loop_friendly = (use_all_optimizations_ == false);
156
157 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_, be_loop_friendly);
Aart Bik24773202018-04-26 10:28:51 -0700158 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100159}
160
Aart Bik24773202018-04-26 10:28:51 -0700161bool InstructionSimplifierVisitor::Run() {
162 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100163 // Iterate in reverse post order to open up more simplifications to users
164 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100165 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100166 // The simplification of an instruction to another instruction may yield
167 // possibilities for other simplifications. So although we perform a reverse
168 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100169 do {
170 simplification_occurred_ = false;
171 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700172 if (simplification_occurred_) {
173 didSimplify = true;
174 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100175 } while (simplification_occurred_ &&
176 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100177 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100178 }
Aart Bik24773202018-04-26 10:28:51 -0700179 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180}
181
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000182namespace {
183
184bool AreAllBitsSet(HConstant* constant) {
185 return Int64FromConstant(constant) == -1;
186}
187
188} // namespace
189
Alexandre Rames188d4312015-04-09 18:30:21 +0100190// Returns true if the code was simplified to use only one negation operation
191// after the binary operation instead of one on each of the inputs.
192bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
193 DCHECK(binop->IsAdd() || binop->IsSub());
194 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
Vladimir Markocde64972023-04-25 16:40:06 +0000195 HNeg* left_neg = binop->GetLeft()->AsNeg();
196 HNeg* right_neg = binop->GetRight()->AsNeg();
Alexandre Rames188d4312015-04-09 18:30:21 +0100197 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
198 !right_neg->HasOnlyOneNonEnvironmentUse()) {
199 return false;
200 }
201 // Replace code looking like
202 // NEG tmp1, a
203 // NEG tmp2, b
204 // ADD dst, tmp1, tmp2
205 // with
206 // ADD tmp, a, b
207 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600208 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
209 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
210 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100211 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600212 return false;
213 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100214 binop->ReplaceInput(left_neg->GetInput(), 0);
215 binop->ReplaceInput(right_neg->GetInput(), 1);
216 left_neg->GetBlock()->RemoveInstruction(left_neg);
217 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100218 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100219 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
220 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
221 RecordSimplification();
222 return true;
223}
224
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
226 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100227 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000228 HInstruction* left = op->GetLeft();
229 HInstruction* right = op->GetRight();
230
231 // We can apply De Morgan's laws if both inputs are Not's and are only used
232 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000233 if (((left->IsNot() && right->IsNot()) ||
234 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000235 left->HasOnlyOneNonEnvironmentUse() &&
236 right->HasOnlyOneNonEnvironmentUse()) {
237 // Replace code looking like
238 // NOT nota, a
239 // NOT notb, b
240 // AND dst, nota, notb (respectively OR)
241 // with
242 // OR or, a, b (respectively AND)
243 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000244 HInstruction* src_left = left->InputAt(0);
245 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000246 uint32_t dex_pc = op->GetDexPc();
247
248 // Remove the negations on the inputs.
249 left->ReplaceWith(src_left);
250 right->ReplaceWith(src_right);
251 left->GetBlock()->RemoveInstruction(left);
252 right->GetBlock()->RemoveInstruction(right);
253
254 // Replace the `HAnd` or `HOr`.
255 HBinaryOperation* hbin;
256 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100257 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000258 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100259 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000260 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000261 HInstruction* hnot;
262 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100263 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000264 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100265 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000266 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000267
268 op->GetBlock()->InsertInstructionBefore(hbin, op);
269 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
270
271 RecordSimplification();
272 return true;
273 }
274
275 return false;
276}
277
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100279 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200280 InstructionSet isa = codegen_->GetInstructionSet();
281 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000282 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100283 if (!(type == DataType::Type::kUint8 ||
284 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100285 type == DataType::Type::kUint16 ||
286 type == DataType::Type::kInt16 ||
287 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200288 return false;
289 }
290 break;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200291 default:
292 return false;
293 }
294
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100295 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Artem Serov8ba4de12019-12-04 21:10:23 +0000296 if (!mul->HasOnlyOneNonEnvironmentUse()) {
297 return false;
298 }
299 HInstruction* binop = mul->GetUses().front().GetUser();
300 if (!binop->IsVecAdd() && !binop->IsVecSub()) {
301 return false;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200302 }
303
Artem Serov8ba4de12019-12-04 21:10:23 +0000304 // Replace code looking like
305 // VECMUL tmp, x, y
306 // VECADD/SUB dst, acc, tmp
307 // with
308 // VECMULACC dst, acc, x, y
309 // Note that we do not want to (unconditionally) perform the merge when the
310 // multiplication has multiple uses and it can be merged in all of them.
311 // Multiple uses could happen on the same control-flow path, and we would
312 // then increase the amount of work. In the future we could try to evaluate
313 // whether all uses are on different control-flow paths (using dominance and
314 // reverse-dominance information) and only perform the merge when they are.
315 HInstruction* accumulator = nullptr;
Vladimir Markocde64972023-04-25 16:40:06 +0000316 HVecBinaryOperation* vec_binop = binop->AsVecBinaryOperation();
Artem Serov8ba4de12019-12-04 21:10:23 +0000317 HInstruction* binop_left = vec_binop->GetLeft();
318 HInstruction* binop_right = vec_binop->GetRight();
319 // This is always true since the `HVecMul` has only one use (which is checked above).
320 DCHECK_NE(binop_left, binop_right);
321 if (binop_right == mul) {
322 accumulator = binop_left;
323 } else {
324 DCHECK_EQ(binop_left, mul);
325 // Only addition is commutative.
326 if (!binop->IsVecAdd()) {
327 return false;
328 }
329 accumulator = binop_right;
330 }
331
332 DCHECK(accumulator != nullptr);
333 HInstruction::InstructionKind kind =
334 binop->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
335
336 bool predicated_simd = vec_binop->IsPredicated();
337 if (predicated_simd && !HVecOperation::HaveSamePredicate(vec_binop, mul)) {
338 return false;
339 }
340
341 HVecMultiplyAccumulate* mulacc =
342 new (allocator) HVecMultiplyAccumulate(allocator,
343 kind,
344 accumulator,
345 mul->GetLeft(),
346 mul->GetRight(),
347 vec_binop->GetPackedType(),
348 vec_binop->GetVectorLength(),
349 vec_binop->GetDexPc());
350
351
352
353 vec_binop->GetBlock()->ReplaceAndRemoveInstructionWith(vec_binop, mulacc);
354 if (predicated_simd) {
355 mulacc->SetGoverningPredicate(vec_binop->GetGoverningPredicate(),
356 vec_binop->GetPredicationKind());
357 }
358
359 DCHECK(!mul->HasUses());
360 mul->GetBlock()->RemoveInstruction(mul);
361 return true;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200362}
363
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000364void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
365 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100366 HInstruction* shift_amount = instruction->GetRight();
367 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000368
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100369 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100370 ? kMaxLongShiftDistance
371 : kMaxIntShiftDistance;
372
373 if (shift_amount->IsConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +0000374 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700375 int64_t masked_cst = cst & implicit_mask;
376 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400377 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100378 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400379 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100380 // value
381 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400382 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100383 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100384 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700385 } else if (masked_cst != cst) {
386 // Replace code looking like
387 // SHL dst, value, cst
388 // where cst exceeds maximum distance with the equivalent
389 // SHL dst, value, cst & implicit_mask
390 // (as defined by shift semantics). This ensures other
391 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100392 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Andreas Gampe3db70682018-12-26 15:12:03 -0800393 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index= */ 1);
Aart Bik50e20d52017-05-05 14:07:29 -0700394 RecordSimplification();
395 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100396 }
397 }
398
399 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100400 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
401 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100402 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100403 // AND adjusted_shift, shift, <superset of implicit mask>
404 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
405 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
406 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100407 // with
408 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100409 if (shift_amount->IsAnd() ||
410 shift_amount->IsOr() ||
411 shift_amount->IsXor() ||
412 shift_amount->IsAdd() ||
413 shift_amount->IsSub()) {
414 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
Vladimir Markocde64972023-04-25 16:40:06 +0000415 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
Vladimir Marko7033d492017-09-28 16:32:24 +0100416 HConstant* mask = bin_op->GetConstantRight();
417 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
418 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100419 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100420 return;
421 }
422 } else if (shift_amount->IsTypeConversion()) {
423 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
424 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
425 // Non-integral and 64-bit source types require an explicit type conversion.
426 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
Vladimir Markocde64972023-04-25 16:40:06 +0000427 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
Vladimir Marko7033d492017-09-28 16:32:24 +0100428 RecordSimplification();
429 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400430 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000431 }
432}
433
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000434static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
435 return (sub->GetRight() == other &&
436 sub->GetLeft()->IsConstant() &&
Vladimir Markocde64972023-04-25 16:40:06 +0000437 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000438}
439
440bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
441 HUShr* ushr,
442 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000443 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100444 HRor* ror =
445 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000446 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
447 if (!ushr->HasUses()) {
448 ushr->GetBlock()->RemoveInstruction(ushr);
449 }
450 if (!ushr->GetRight()->HasUses()) {
451 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
452 }
453 if (!shl->HasUses()) {
454 shl->GetBlock()->RemoveInstruction(shl);
455 }
456 if (!shl->GetRight()->HasUses()) {
457 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
458 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100459 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000460 return true;
461}
462
463// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
464bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000465 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
466 HInstruction* left = op->GetLeft();
467 HInstruction* right = op->GetRight();
468 // If we have an UShr and a Shl (in either order).
469 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
Vladimir Markocde64972023-04-25 16:40:06 +0000470 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
471 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100472 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000473 if (ushr->GetType() == shl->GetType() &&
474 ushr->GetLeft() == shl->GetLeft()) {
475 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
476 // Shift distances are both constant, try replacing with Ror if they
477 // add up to the register size.
478 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
479 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
480 // Shift distances are potentially of the form x and (reg_size - x).
481 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
482 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
483 // Shift distances are potentially of the form d and -d.
484 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
485 }
486 }
487 }
488 return false;
489}
490
491// Try replacing code looking like (x >>> #rdist OP x << #ldist):
492// UShr dst, x, #rdist
493// Shl tmp, x, #ldist
494// OP dst, dst, tmp
495// or like (x >>> #rdist OP x << #-ldist):
496// UShr dst, x, #rdist
497// Shl tmp, x, #-ldist
498// OP dst, dst, tmp
499// with
500// Ror dst, x, #rdist
501bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
502 HUShr* ushr,
503 HShl* shl) {
504 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100505 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Vladimir Markocde64972023-04-25 16:40:06 +0000506 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
507 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000508 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
509 ReplaceRotateWithRor(op, ushr, shl);
510 return true;
511 }
512 return false;
513}
514
515// Replace code looking like (x >>> -d OP x << d):
516// Neg neg, d
517// UShr dst, x, neg
518// Shl tmp, x, d
519// OP dst, dst, tmp
520// with
521// Neg neg, d
522// Ror dst, x, neg
523// *** OR ***
524// Replace code looking like (x >>> d OP x << -d):
525// UShr dst, x, d
526// Neg neg, d
527// Shl tmp, x, neg
528// OP dst, dst, tmp
529// with
530// Ror dst, x, d
531bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
532 HUShr* ushr,
533 HShl* shl) {
534 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
535 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
536 bool neg_is_left = shl->GetRight()->IsNeg();
Vladimir Markocde64972023-04-25 16:40:06 +0000537 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000538 // And the shift distance being negated is the distance being shifted the other way.
539 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
540 ReplaceRotateWithRor(op, ushr, shl);
541 }
542 return false;
543}
544
545// Try replacing code looking like (x >>> d OP x << (#bits - d)):
546// UShr dst, x, d
547// Sub ld, #bits, d
548// Shl tmp, x, ld
549// OP dst, dst, tmp
550// with
551// Ror dst, x, d
552// *** OR ***
553// Replace code looking like (x >>> (#bits - d) OP x << d):
554// Sub rd, #bits, d
555// UShr dst, x, rd
556// Shl tmp, x, d
557// OP dst, dst, tmp
558// with
559// Neg neg, d
560// Ror dst, x, neg
561bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
562 HUShr* ushr,
563 HShl* shl) {
564 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
565 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100566 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000567 HInstruction* shl_shift = shl->GetRight();
568 HInstruction* ushr_shift = ushr->GetRight();
Vladimir Markocde64972023-04-25 16:40:06 +0000569 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
570 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000571 return ReplaceRotateWithRor(op, ushr, shl);
572 }
573 return false;
574}
575
Calin Juravle10e244f2015-01-26 18:54:32 +0000576void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
577 HInstruction* obj = null_check->InputAt(0);
578 if (!obj->CanBeNull()) {
579 null_check->ReplaceWith(obj);
580 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000581 if (stats_ != nullptr) {
582 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
583 }
584 }
585}
586
Ulya Trafimovich3676b362021-09-02 16:13:51 +0100587bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) {
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100588 if (!input->CanBeNull()) {
589 return true;
590 }
591
Vladimir Marko46817b82016-03-29 12:21:58 +0100592 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
593 HInstruction* user = use.GetUser();
594 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100595 return true;
596 }
597 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100598
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100599 return false;
600}
601
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100602// Returns whether doing a type test between the class of `object` against `klass` has
603// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000604static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
605 HInstruction* object,
606 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000607 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
608 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
609 ScopedObjectAccess soa(Thread::Current());
610 if (!obj_rti.IsValid()) {
611 // We run the simplifier before the reference type propagation so type info might not be
612 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100613 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000614 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100615
Calin Juravle98893e12015-10-02 21:05:03 +0100616 if (!class_rti.IsValid()) {
617 // Happens when the loaded class is unresolved.
Alex Lightbb550e42021-04-21 17:04:13 -0700618 if (obj_rti.IsExact()) {
619 // outcome == 'true' && obj_rti is valid implies that class_rti is valid.
620 // Since that's a contradiction we must not pass this check.
621 *outcome = false;
622 return true;
623 } else {
624 // We aren't able to say anything in particular since we don't know the
625 // exact type of the object.
626 return false;
627 }
Calin Juravle98893e12015-10-02 21:05:03 +0100628 }
629 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000630 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100631 *outcome = true;
632 return true;
633 } else if (obj_rti.IsExact()) {
634 // The test failed at compile time so will also fail at runtime.
635 *outcome = false;
636 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100637 } else if (!class_rti.IsInterface()
638 && !obj_rti.IsInterface()
639 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100640 // Different type hierarchy. The test will fail.
641 *outcome = false;
642 return true;
643 }
644 return false;
645}
646
647void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
648 HInstruction* object = check_cast->InputAt(0);
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100649 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100650 check_cast->ClearMustDoNullCheck();
651 }
652
653 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000654 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700655 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100656 return;
657 }
658
Alex Lightbb550e42021-04-21 17:04:13 -0700659 // Minor correctness check.
660 DCHECK(check_cast->GetTargetClass()->StrictlyDominates(check_cast))
661 << "Illegal graph!\n"
662 << check_cast->DumpWithArgs();
663
Roland Levillain05e34f42018-05-24 13:19:05 +0000664 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
665 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000666 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000667 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100668 if (outcome) {
669 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700670 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000671 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
672 HLoadClass* load_class = check_cast->GetTargetClass();
Alex Lightbb550e42021-04-21 17:04:13 -0700673 if (!load_class->HasUses() && !load_class->NeedsAccessCheck()) {
Vladimir Marko175e7862018-03-27 09:03:13 +0000674 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
Alex Lightbb550e42021-04-21 17:04:13 -0700675 // However, here we know that it cannot because the checkcast was successful, hence
Vladimir Marko175e7862018-03-27 09:03:13 +0000676 // the class was already loaded.
677 load_class->GetBlock()->RemoveInstruction(load_class);
678 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700679 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100680 } else {
Alex Lightbb550e42021-04-21 17:04:13 -0700681 // TODO Don't do anything for exceptional cases for now. Ideally we should
682 // remove all instructions and blocks this instruction dominates and
683 // replace it with a manual throw.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100684 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000685 }
686}
687
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100688void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100689 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100690
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100691 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100692 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100693 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100694 instruction->ClearMustDoNullCheck();
695 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100696
697 HGraph* graph = GetGraph();
698 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000699 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100700 instruction->ReplaceWith(graph->GetIntConstant(0));
701 instruction->GetBlock()->RemoveInstruction(instruction);
702 RecordSimplification();
703 return;
704 }
705
Alex Lightbb550e42021-04-21 17:04:13 -0700706 // Minor correctness check.
707 DCHECK(instruction->GetTargetClass()->StrictlyDominates(instruction))
708 << "Illegal graph!\n"
709 << instruction->DumpWithArgs();
710
Roland Levillain05e34f42018-05-24 13:19:05 +0000711 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
712 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000713 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000714 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000715 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100716 if (outcome && can_be_null) {
717 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100718 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100719 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
720 instruction->ReplaceWith(test);
721 } else {
722 // We've statically determined the result of the instanceof.
723 instruction->ReplaceWith(graph->GetIntConstant(outcome));
724 }
725 RecordSimplification();
726 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000727 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
728 HLoadClass* load_class = instruction->GetTargetClass();
Alex Lightbb550e42021-04-21 17:04:13 -0700729 if (!load_class->HasUses() && !load_class->NeedsAccessCheck()) {
730 // We cannot rely on DCE to remove the class because the `HLoadClass`
731 // thinks it can throw. However, here we know that it cannot because the
732 // instanceof check was successful and we don't need to check the
733 // access, hence the class was already loaded.
Vladimir Marko175e7862018-03-27 09:03:13 +0000734 load_class->GetBlock()->RemoveInstruction(load_class);
735 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700736 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100737 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100738}
739
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100740void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100741 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100742 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100743 instruction->ClearValueCanBeNull();
744 }
745}
746
747void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100748 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100749 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100750 instruction->ClearValueCanBeNull();
751 }
752}
753
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100754static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600755 HInstruction *lhs = cond->InputAt(0);
756 HInstruction *rhs = cond->InputAt(1);
757 switch (cond->GetKind()) {
758 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100759 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600760 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100761 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600762 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100763 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600764 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100765 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600766 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100767 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600768 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100769 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600770 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100771 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600772 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100773 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600774 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100775 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600776 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100777 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600778 default:
779 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800780 UNREACHABLE();
Anton Shaminbdd79352016-02-15 12:48:36 +0600781 }
Anton Shaminbdd79352016-02-15 12:48:36 +0600782}
783
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000784void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100785 HInstruction* input_const = equal->GetConstantRight();
786 if (input_const != nullptr) {
787 HInstruction* input_value = equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100788 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100790 // We are comparing the boolean to a constant which is of type int and can
791 // be any constant.
Vladimir Markocde64972023-04-25 16:40:06 +0000792 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100793 // Replace (bool_value == true) with bool_value
794 equal->ReplaceWith(input_value);
795 block->RemoveInstruction(equal);
796 RecordSimplification();
Vladimir Markocde64972023-04-25 16:40:06 +0000797 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700798 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500799 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
800 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100802 } else {
803 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
804 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
805 block->RemoveInstruction(equal);
806 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100807 }
Mark Mendellc4701932015-04-10 13:18:51 -0400808 } else {
809 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100810 }
Mark Mendellc4701932015-04-10 13:18:51 -0400811 } else {
812 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100813 }
814}
815
David Brazdil0d13fee2015-04-17 14:52:19 +0100816void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
817 HInstruction* input_const = not_equal->GetConstantRight();
818 if (input_const != nullptr) {
819 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100820 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100821 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100822 // We are comparing the boolean to a constant which is of type int and can
823 // be any constant.
Vladimir Markocde64972023-04-25 16:40:06 +0000824 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700825 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500826 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
827 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100828 RecordSimplification();
Vladimir Markocde64972023-04-25 16:40:06 +0000829 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100830 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100831 not_equal->ReplaceWith(input_value);
832 block->RemoveInstruction(not_equal);
833 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100834 } else {
835 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
836 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
837 block->RemoveInstruction(not_equal);
838 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100839 }
Mark Mendellc4701932015-04-10 13:18:51 -0400840 } else {
841 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100842 }
Mark Mendellc4701932015-04-10 13:18:51 -0400843 } else {
844 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100845 }
846}
847
848void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000849 HInstruction* input = bool_not->InputAt(0);
850 HInstruction* replace_with = nullptr;
851
852 if (input->IsIntConstant()) {
853 // Replace !(true/false) with false/true.
Vladimir Markocde64972023-04-25 16:40:06 +0000854 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000855 replace_with = GetGraph()->GetIntConstant(0);
856 } else {
Vladimir Markocde64972023-04-25 16:40:06 +0000857 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000858 replace_with = GetGraph()->GetIntConstant(1);
859 }
860 } else if (input->IsBooleanNot()) {
861 // Replace (!(!bool_value)) with bool_value.
862 replace_with = input->InputAt(0);
863 } else if (input->IsCondition() &&
864 // Don't change FP compares. The definition of compares involving
865 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100866 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000867 // Replace condition with its opposite.
Vladimir Markocde64972023-04-25 16:40:06 +0000868 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000869 }
870
871 if (replace_with != nullptr) {
872 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100873 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000874 RecordSimplification();
875 }
876}
877
Aart Bik4f7dd342017-09-12 13:12:57 -0700878// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100879static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
880 HInstruction* x,
881 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700882 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800883 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700884 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800885 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
886 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700887}
888
Aart Bik142b9132018-03-14 15:12:59 -0700889// Constructs a new MIN/MAX(x, y) node in the HIR.
890static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
891 HInstruction* x,
892 HInstruction* y,
893 HInstruction* cursor,
894 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700895 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700896 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
897 HBinaryOperation* minmax = nullptr;
898 if (is_min) {
899 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
900 } else {
901 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
902 }
903 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
904 return minmax;
905}
906
Aart Bik4f7dd342017-09-12 13:12:57 -0700907// Returns true if operands a and b consists of widening type conversions
908// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100909static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700910 if (a->IsTypeConversion() && a->GetType() == to_type) {
911 a = a->InputAt(0);
912 }
913 if (b->IsTypeConversion() && b->GetType() == to_type) {
914 b = b->InputAt(0);
915 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100916 DataType::Type type1 = a->GetType();
917 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100918 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
919 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
920 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
921 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
922 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100923 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700924}
925
Aart Bik1d746de2018-03-28 16:30:02 -0700926// Returns an acceptable substitution for "a" on the select
927// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
928static HInstruction* AllowInMinMax(IfCondition cmp,
929 HInstruction* a,
930 HInstruction* b,
931 HInstruction* c) {
932 int64_t value = 0;
933 if (IsInt64AndGet(b, /*out*/ &value) &&
934 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
935 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
Vladimir Markocde64972023-04-25 16:40:06 +0000936 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
937 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
Aart Bik1d746de2018-03-28 16:30:02 -0700938 int64_t other_value = Int64FromConstant(other);
939 bool is_max = (cmp == kCondLT || cmp == kCondLE);
940 // Allow the max for a < 100 ? max(a, -100) : ..
941 // or the min for a > -100 ? min(a, 100) : ..
942 if (is_max ? (value >= other_value) : (value <= other_value)) {
943 return c;
944 }
945 }
946 }
947 return nullptr;
948}
949
Alex Light3a73ffb2021-01-25 14:11:05 +0000950// TODO This should really be done by LSE itself since there is significantly
951// more information available there.
952void InstructionSimplifierVisitor::VisitPredicatedInstanceFieldGet(
953 HPredicatedInstanceFieldGet* pred_get) {
954 HInstruction* target = pred_get->GetTarget();
955 HInstruction* default_val = pred_get->GetDefaultValue();
Alex Lightba320162021-04-22 15:15:13 -0700956 if (target->IsNullConstant()) {
957 pred_get->ReplaceWith(default_val);
958 pred_get->GetBlock()->RemoveInstruction(pred_get);
959 RecordSimplification();
Alex Light3a73ffb2021-01-25 14:11:05 +0000960 return;
Alex Lightba320162021-04-22 15:15:13 -0700961 } else if (!target->CanBeNull()) {
Alex Light74328052021-03-29 18:11:23 -0700962 HInstruction* replace_with = new (GetGraph()->GetAllocator())
963 HInstanceFieldGet(pred_get->GetTarget(),
964 pred_get->GetFieldInfo().GetField(),
965 pred_get->GetFieldType(),
966 pred_get->GetFieldOffset(),
967 pred_get->IsVolatile(),
968 pred_get->GetFieldInfo().GetFieldIndex(),
969 pred_get->GetFieldInfo().GetDeclaringClassDefIndex(),
970 pred_get->GetFieldInfo().GetDexFile(),
971 pred_get->GetDexPc());
972 if (pred_get->GetType() == DataType::Type::kReference) {
Santiago Aboy Solanese05bc3e2023-02-20 14:26:23 +0000973 replace_with->SetReferenceTypeInfoIfValid(pred_get->GetReferenceTypeInfo());
Alex Light74328052021-03-29 18:11:23 -0700974 }
975 pred_get->GetBlock()->InsertInstructionBefore(replace_with, pred_get);
976 pred_get->ReplaceWith(replace_with);
977 pred_get->GetBlock()->RemoveInstruction(pred_get);
978 RecordSimplification();
Alex Lightba320162021-04-22 15:15:13 -0700979 return;
980 }
981 if (!target->IsPhi() || !default_val->IsPhi() || default_val->GetBlock() != target->GetBlock()) {
982 // The iget has already been reduced. We know the target or the phi
983 // selection will differ between the target and default.
984 return;
985 }
986 DCHECK_EQ(default_val->InputCount(), target->InputCount());
987 // In the same block both phis only one non-null we can remove the phi from default_val.
988 HInstruction* single_value = nullptr;
989 auto inputs = target->GetInputs();
990 for (auto [input, idx] : ZipCount(MakeIterationRange(inputs))) {
991 if (input->CanBeNull()) {
992 if (single_value == nullptr) {
993 single_value = default_val->InputAt(idx);
994 } else if (single_value != default_val->InputAt(idx) &&
995 !single_value->Equals(default_val->InputAt(idx))) {
996 // Multiple values are associated with potential nulls, can't combine.
997 return;
998 }
999 }
1000 }
1001 DCHECK(single_value != nullptr) << "All target values are non-null but the phi as a whole still"
1002 << " can be null? This should not be possible." << std::endl
1003 << pred_get->DumpWithArgs();
1004 if (single_value->StrictlyDominates(pred_get)) {
Alex Light3a73ffb2021-01-25 14:11:05 +00001005 // Combine all the maybe null values into one.
1006 pred_get->ReplaceInput(single_value, 0);
Alex Light74328052021-03-29 18:11:23 -07001007 RecordSimplification();
Alex Light3a73ffb2021-01-25 14:11:05 +00001008 }
1009}
1010
David Brazdil74eb1b22015-12-14 11:44:01 +00001011void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
1012 HInstruction* replace_with = nullptr;
1013 HInstruction* condition = select->GetCondition();
1014 HInstruction* true_value = select->GetTrueValue();
1015 HInstruction* false_value = select->GetFalseValue();
1016
1017 if (condition->IsBooleanNot()) {
1018 // Change ((!cond) ? x : y) to (cond ? y : x).
1019 condition = condition->InputAt(0);
1020 std::swap(true_value, false_value);
1021 select->ReplaceInput(false_value, 0);
1022 select->ReplaceInput(true_value, 1);
1023 select->ReplaceInput(condition, 2);
1024 RecordSimplification();
1025 }
1026
1027 if (true_value == false_value) {
1028 // Replace (cond ? x : x) with (x).
1029 replace_with = true_value;
1030 } else if (condition->IsIntConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001031 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001032 // Replace (true ? x : y) with (x).
1033 replace_with = true_value;
1034 } else {
1035 // Replace (false ? x : y) with (y).
Vladimir Markocde64972023-04-25 16:40:06 +00001036 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +00001037 replace_with = false_value;
1038 }
1039 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001040 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001041 // Replace (cond ? true : false) with (cond).
1042 replace_with = condition;
Vladimir Markocde64972023-04-25 16:40:06 +00001043 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001044 // Replace (cond ? false : true) with (!cond).
1045 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
1046 }
Aart Bik4f7dd342017-09-12 13:12:57 -07001047 } else if (condition->IsCondition()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001048 IfCondition cmp = condition->AsCondition()->GetCondition();
Aart Bik4f7dd342017-09-12 13:12:57 -07001049 HInstruction* a = condition->InputAt(0);
1050 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001051 DataType::Type t_type = true_value->GetType();
1052 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -07001053 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -07001054 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
1055 // type will be int or long, like the condition). Replacements are general,
1056 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -07001057 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001058 // Allow a < 100 ? max(a, -100) : ..
1059 // or a > -100 ? min(a, 100) : ..
1060 // to use min/max instead of a to detect nested min/max expressions.
1061 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
1062 if (new_a != nullptr) {
1063 a = new_a;
1064 }
Aart Bik142b9132018-03-14 15:12:59 -07001065 // Try to replace typical integral MIN/MAX/ABS constructs.
1066 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
1067 ((a == true_value && b == false_value) ||
1068 (b == true_value && a == false_value))) {
1069 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
1070 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
1071 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
1072 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -07001073 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
1074 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
1075 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
1076 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1077 HInstruction* not_negated = negLeft ? false_value : true_value;
1078 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1079 // Found a < 0 ? -a : a
1080 // or a > 0 ? a : -a
1081 // which can be replaced by ABS(a).
1082 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001083 }
1084 } else if (true_value->IsSub() && false_value->IsSub()) {
1085 HInstruction* true_sub1 = true_value->InputAt(0);
1086 HInstruction* true_sub2 = true_value->InputAt(1);
1087 HInstruction* false_sub1 = false_value->InputAt(0);
1088 HInstruction* false_sub2 = false_value->InputAt(1);
1089 if ((((cmp == kCondGT || cmp == kCondGE) &&
1090 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1091 ((cmp == kCondLT || cmp == kCondLE) &&
1092 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1093 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001094 // Found a > b ? a - b : b - a
1095 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001096 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001097 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001098 }
1099 }
1100 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001101 }
1102
1103 if (replace_with != nullptr) {
1104 select->ReplaceWith(replace_with);
1105 select->GetBlock()->RemoveInstruction(select);
1106 RecordSimplification();
1107 }
1108}
1109
1110void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1111 HInstruction* condition = instruction->InputAt(0);
1112 if (condition->IsBooleanNot()) {
1113 // Swap successors if input is negated.
1114 instruction->ReplaceInput(condition->InputAt(0), 0);
1115 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001116 RecordSimplification();
1117 }
1118}
1119
Santiago Aboy Solanesc63bdde2023-03-31 16:04:22 +01001120// TODO(solanes): This optimization should be in ConstantFolding since we are folding to a constant.
1121// However, we get code size regressions when we do that since we sometimes have a NullCheck between
1122// HArrayLength and IsNewArray, and said NullCheck is eliminated in InstructionSimplifier. If we run
1123// ConstantFolding and InstructionSimplifier in lockstep this wouldn't be an issue.
Mingyao Yang0304e182015-01-30 16:41:29 -08001124void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1125 HInstruction* input = instruction->InputAt(0);
1126 // If the array is a NewArray with constant size, replace the array length
1127 // with the constant instruction. This helps the bounds check elimination phase.
1128 if (input->IsNewArray()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001129 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001130 if (input->IsIntConstant()) {
1131 instruction->ReplaceWith(input);
1132 }
1133 }
1134}
1135
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001136void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001137 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001138 if (value->GetType() != DataType::Type::kReference) {
1139 return;
1140 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001141
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001142 if (CanEnsureNotNullAt(value, instruction)) {
1143 instruction->ClearValueCanBeNull();
1144 }
1145
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001146 if (value->IsArrayGet()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001147 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001148 // If the code is just swapping elements in the array, no need for a type check.
Santiago Aboy Solanes13c3ce12022-12-05 12:05:43 +00001149 instruction->ClearTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001150 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001151 }
1152 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001153
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001154 if (value->IsNullConstant()) {
Santiago Aboy Solanes13c3ce12022-12-05 12:05:43 +00001155 instruction->ClearTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001156 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001157 }
1158
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001159 ScopedObjectAccess soa(Thread::Current());
1160 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1161 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1162 if (!array_rti.IsValid()) {
1163 return;
1164 }
1165
1166 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
Santiago Aboy Solanes13c3ce12022-12-05 12:05:43 +00001167 instruction->ClearTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001168 return;
1169 }
1170
1171 if (array_rti.IsObjectArray()) {
1172 if (array_rti.IsExact()) {
Santiago Aboy Solanes13c3ce12022-12-05 12:05:43 +00001173 instruction->ClearTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001174 return;
1175 }
1176 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001177 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001178}
1179
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001180static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001181 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1182 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1183 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001184 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001185 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001186 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1187 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001188 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001189 return DataType::Size(result_type) > DataType::Size(input_type) &&
1190 result_type != DataType::Type::kUint16 &&
1191 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001192}
1193
Artem Serove91a9542021-10-25 16:23:27 +01001194static bool CanRemoveRedundantAnd(HConstant* and_right,
1195 HConstant* shr_right,
1196 DataType::Type result_type) {
1197 int64_t and_cst = Int64FromConstant(and_right);
1198 int64_t shr_cst = Int64FromConstant(shr_right);
1199
1200 // In the following sequence A is the input value, D is the result:
1201 // B := A & x
1202 // C := B >> r
1203 // D := TypeConv(n-bit type) C
1204
1205 // The value of D is entirely dependent on the bits [n-1:0] of C, which in turn are dependent
1206 // on bits [r+n-1:r] of B.
1207 // Therefore, if the AND does not change bits [r+n-1:r] of A then it will not affect D.
1208 // This can be checked by ensuring that bits [r+n-1:r] of the AND Constant are 1.
1209
1210 // For example: return (byte) ((value & 0xff00) >> 8)
1211 // return (byte) ((value & 0xff000000) >> 31)
1212
1213 // The mask sets bits [r+n-1:r] to 1, and all others to 0.
1214 int64_t mask = DataType::MaxValueOfIntegralType(DataType::ToUnsigned(result_type)) << shr_cst;
1215
1216 // If the result of a bitwise AND between the mask and the AND constant is the original mask, then
1217 // the AND does not change bits [r+n-1:r], meaning that it is redundant and can be removed.
1218 return ((and_cst & mask) == mask);
1219}
1220
Vladimir Marko61b92282017-10-11 13:23:17 +01001221static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1222 if (maybe_get->IsInstanceFieldGet()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001223 maybe_get->AsInstanceFieldGet()->SetType(new_type);
Vladimir Marko61b92282017-10-11 13:23:17 +01001224 return true;
Alex Light3a73ffb2021-01-25 14:11:05 +00001225 } else if (maybe_get->IsPredicatedInstanceFieldGet()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001226 maybe_get->AsPredicatedInstanceFieldGet()->SetType(new_type);
Alex Light3a73ffb2021-01-25 14:11:05 +00001227 return true;
Vladimir Marko61b92282017-10-11 13:23:17 +01001228 } else if (maybe_get->IsStaticFieldGet()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001229 maybe_get->AsStaticFieldGet()->SetType(new_type);
Vladimir Marko61b92282017-10-11 13:23:17 +01001230 return true;
Vladimir Markocde64972023-04-25 16:40:06 +00001231 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1232 maybe_get->AsArrayGet()->SetType(new_type);
Vladimir Marko61b92282017-10-11 13:23:17 +01001233 return true;
1234 } else {
1235 return false;
1236 }
1237}
1238
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001239// The type conversion is only used for storing into a field/element of the
1240// same/narrower size.
1241static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1242 if (type_conversion->HasEnvironmentUses()) {
1243 return false;
1244 }
1245 DataType::Type input_type = type_conversion->GetInputType();
1246 DataType::Type result_type = type_conversion->GetResultType();
1247 if (!DataType::IsIntegralType(input_type) ||
1248 !DataType::IsIntegralType(result_type) ||
1249 input_type == DataType::Type::kInt64 ||
1250 result_type == DataType::Type::kInt64) {
1251 // Type conversion is needed if non-integer types are involved, or 64-bit
1252 // types are involved, which may use different number of registers.
1253 return false;
1254 }
1255 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1256 // Type conversion is not necessary when storing to a field/element of the
1257 // same/smaller size.
1258 } else {
1259 // We do not handle this case here.
1260 return false;
1261 }
1262
1263 // Check if the converted value is only used for storing into heap.
1264 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1265 HInstruction* instruction = use.GetUser();
1266 if (instruction->IsInstanceFieldSet() &&
Vladimir Markocde64972023-04-25 16:40:06 +00001267 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1268 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001269 continue;
1270 }
1271 if (instruction->IsStaticFieldSet() &&
Vladimir Markocde64972023-04-25 16:40:06 +00001272 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1273 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001274 continue;
1275 }
1276 if (instruction->IsArraySet() &&
Vladimir Markocde64972023-04-25 16:40:06 +00001277 instruction->AsArraySet()->GetComponentType() == result_type &&
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001278 // not index use.
Vladimir Markocde64972023-04-25 16:40:06 +00001279 instruction->AsArraySet()->GetIndex() != type_conversion) {
1280 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001281 continue;
1282 }
1283 // The use is not as a store value, or the field/element type is not the
1284 // same as the result_type, keep the type conversion.
1285 return false;
1286 }
1287 // Codegen automatically handles the type conversion during the store.
1288 return true;
1289}
1290
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001291void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001292 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001293 DataType::Type input_type = input->GetType();
1294 DataType::Type result_type = instruction->GetResultType();
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001295 if (instruction->IsImplicitConversion()) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001296 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001297 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001298 RecordSimplification();
1299 return;
1300 }
1301
1302 if (input->IsTypeConversion()) {
Vladimir Markocde64972023-04-25 16:40:06 +00001303 HTypeConversion* input_conversion = input->AsTypeConversion();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001304 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001305 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001306
1307 // When the first conversion is lossless, a direct conversion from the original type
1308 // to the final type yields the same result, even for a lossy second conversion, for
1309 // example float->double->int or int->double->float.
1310 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1311
1312 // For integral conversions, see if the first conversion loses only bits that the second
1313 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1314 // conversion yields the same result, for example long->int->short or int->char->short.
1315 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001316 DataType::IsIntegralType(input_type) &&
1317 DataType::IsIntegralType(original_type) &&
1318 DataType::IsIntegralType(result_type) &&
1319 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001320
1321 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1322 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001323 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001324 instruction->ReplaceWith(original_input);
1325 instruction->GetBlock()->RemoveInstruction(instruction);
1326 if (!input_conversion->HasUses()) {
1327 // Don't wait for DCE.
1328 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1329 }
1330 RecordSimplification();
1331 return;
1332 }
1333 // Otherwise simplify only if the first conversion has no other use.
1334 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1335 input_conversion->ReplaceWith(original_input);
1336 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1337 RecordSimplification();
1338 return;
1339 }
1340 }
Artem Serove91a9542021-10-25 16:23:27 +01001341 } else if (input->IsShr() && DataType::IsIntegralType(result_type) &&
1342 // Optimization only applies to lossy Type Conversions.
1343 !IsTypeConversionLossless(input_type, result_type)) {
1344 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Markocde64972023-04-25 16:40:06 +00001345 HShr* shr_op = input->AsShr();
Artem Serove91a9542021-10-25 16:23:27 +01001346 HConstant* shr_right = shr_op->GetConstantRight();
1347 HInstruction* shr_left = shr_op->GetLeastConstantLeft();
1348 if (shr_right != nullptr && shr_left->IsAnd()) {
1349 // Optimization needs AND -> SHR -> TypeConversion pattern.
Vladimir Markocde64972023-04-25 16:40:06 +00001350 HAnd* and_op = shr_left->AsAnd();
Artem Serove91a9542021-10-25 16:23:27 +01001351 HConstant* and_right = and_op->GetConstantRight();
1352 HInstruction* and_left = and_op->GetLeastConstantLeft();
1353 if (and_right != nullptr &&
1354 !DataType::IsUnsignedType(and_left->GetType()) &&
1355 !DataType::IsUnsignedType(result_type) &&
1356 !DataType::IsUnsignedType(and_right->GetType()) &&
1357 (DataType::Size(and_left->GetType()) < 8) &&
1358 (DataType::Size(result_type) == 1)) {
1359 // TODO: Support Unsigned Types.
1360 // TODO: Support Long Types.
1361 // TODO: Support result types other than byte.
1362 if (and_op->HasOnlyOneNonEnvironmentUse() &&
1363 CanRemoveRedundantAnd(and_right, shr_right, result_type)) {
1364 and_op->ReplaceWith(and_left);
1365 and_op->GetBlock()->RemoveInstruction(and_op);
1366 RecordSimplification();
1367 return;
1368 }
1369 }
1370 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001371 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1372 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Markocde64972023-04-25 16:40:06 +00001373 HAnd* input_and = input->AsAnd();
Vladimir Marko8428bd32016-02-12 16:53:57 +00001374 HConstant* constant = input_and->GetConstantRight();
1375 if (constant != nullptr) {
1376 int64_t value = Int64FromConstant(constant);
1377 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1378 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001379 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001380 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001381 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001382 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001383 instruction->ReplaceWith(original_input);
1384 instruction->GetBlock()->RemoveInstruction(instruction);
1385 RecordSimplification();
1386 return;
1387 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1388 input_and->ReplaceWith(original_input);
1389 input_and->GetBlock()->RemoveInstruction(input_and);
1390 RecordSimplification();
1391 return;
1392 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001393 }
1394 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001395 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1396 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1397 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1398 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1399 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1400 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1401 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1402 instruction->ReplaceWith(input);
1403 instruction->GetBlock()->RemoveInstruction(instruction);
1404 RecordSimplification();
1405 return;
1406 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001407 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001408
1409 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1410 instruction->ReplaceWith(input);
1411 instruction->GetBlock()->RemoveInstruction(instruction);
1412 RecordSimplification();
1413 return;
1414 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001415}
1416
Aart Bikc6eec4b2018-03-29 17:22:00 -07001417void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1418 HInstruction* input = instruction->GetInput();
1419 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1420 // Zero extension from narrow to wide can never set sign bit in the wider
1421 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1422 instruction->ReplaceWith(input);
1423 instruction->GetBlock()->RemoveInstruction(instruction);
1424 RecordSimplification();
1425 }
1426}
1427
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001428void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1429 HConstant* input_cst = instruction->GetConstantRight();
1430 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001432 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001433 // Replace code looking like
1434 // ADD dst, src, 0
1435 // with
1436 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001437 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1438 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1439 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001440 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001441 instruction->ReplaceWith(input_other);
1442 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001443 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001444 return;
1445 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001446 }
1447
1448 HInstruction* left = instruction->GetLeft();
1449 HInstruction* right = instruction->GetRight();
1450 bool left_is_neg = left->IsNeg();
1451 bool right_is_neg = right->IsNeg();
1452
1453 if (left_is_neg && right_is_neg) {
1454 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1455 return;
1456 }
1457 }
1458
Vladimir Markod6ce8df2023-04-27 12:09:54 +00001459 if (left_is_neg != right_is_neg) {
1460 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1461 if (neg->HasOnlyOneNonEnvironmentUse()) {
1462 // Replace code looking like
1463 // NEG tmp, b
1464 // ADD dst, a, tmp
1465 // with
1466 // SUB dst, a, b
1467 // We do not perform the optimization if the input negation has environment
1468 // uses or multiple non-environment uses as it could lead to worse code. In
1469 // particular, we do not want the live range of `b` to be extended if we are
1470 // not sure the initial 'NEG' instruction can be removed.
1471 HInstruction* other = left_is_neg ? right : left;
1472 HSub* sub =
1473 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
1474 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1475 RecordSimplification();
1476 neg->GetBlock()->RemoveInstruction(neg);
1477 return;
1478 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001479 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001480
Anton Kirilove14dc862016-05-13 17:56:15 +01001481 if (TryReplaceWithRotate(instruction)) {
1482 return;
1483 }
1484
1485 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1486 // so no need to return.
1487 TryHandleAssociativeAndCommutativeOperation(instruction);
1488
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001489 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001490 TrySubtractionChainSimplification(instruction)) {
1491 return;
1492 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001493
1494 if (integral_type) {
1495 // Replace code patterns looking like
1496 // SUB dst1, x, y SUB dst1, x, y
1497 // ADD dst2, dst1, y ADD dst2, y, dst1
1498 // with
1499 // SUB dst1, x, y
1500 // ADD instruction is not needed in this case, we may use
1501 // one of inputs of SUB instead.
1502 if (left->IsSub() && left->InputAt(1) == right) {
1503 instruction->ReplaceWith(left->InputAt(0));
1504 RecordSimplification();
1505 instruction->GetBlock()->RemoveInstruction(instruction);
1506 return;
1507 } else if (right->IsSub() && right->InputAt(1) == left) {
1508 instruction->ReplaceWith(right->InputAt(0));
1509 RecordSimplification();
1510 instruction->GetBlock()->RemoveInstruction(instruction);
1511 return;
1512 }
1513 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001514}
1515
1516void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001517 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001518 HConstant* input_cst = instruction->GetConstantRight();
1519 HInstruction* input_other = instruction->GetLeastConstantLeft();
1520
Vladimir Marko452c1b62015-09-25 14:44:17 +01001521 if (input_cst != nullptr) {
1522 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001523 if (value == -1 ||
1524 // Similar cases under zero extension.
1525 (DataType::IsUnsignedType(input_other->GetType()) &&
1526 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001527 // Replace code looking like
1528 // AND dst, src, 0xFFF...FF
1529 // with
1530 // src
1531 instruction->ReplaceWith(input_other);
1532 instruction->GetBlock()->RemoveInstruction(instruction);
1533 RecordSimplification();
1534 return;
1535 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001536 if (input_other->IsTypeConversion() &&
1537 input_other->GetType() == DataType::Type::kInt64 &&
1538 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1539 IsInt<32>(value) &&
1540 input_other->HasOnlyOneNonEnvironmentUse()) {
1541 // The AND can be reordered before the TypeConversion. Replace
1542 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1543 // TypeConversion<Int64> tmp, src
1544 // AND dst, tmp, cst
1545 // with
1546 // IntConstant cst, <32-bit-constant>
1547 // AND tmp, src, cst
1548 // TypeConversion<Int64> dst, tmp
1549 // This helps 32-bit targets and does not hurt 64-bit targets.
1550 // This also simplifies detection of other patterns, such as Uint8 loads.
1551 HInstruction* new_and_input = input_other->InputAt(0);
1552 // Implicit conversion Int64->Int64 would have been removed previously.
1553 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1554 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1555 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001556 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001557 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1558 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001559 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001560 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1561 input_other->GetBlock()->RemoveInstruction(input_other);
1562 RecordSimplification();
1563 // Try to process the new And now, do not wait for the next round of simplifications.
1564 instruction = new_and;
1565 input_other = new_and_input;
1566 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001567 // Eliminate And from UShr+And if the And-mask contains all the bits that
1568 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1569 // precisely clears the shifted-in sign bits.
1570 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001571 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Markocde64972023-04-25 16:40:06 +00001572 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
Vladimir Marko452c1b62015-09-25 14:44:17 +01001573 size_t num_tail_bits_set = CTZ(value + 1);
1574 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1575 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1576 instruction->ReplaceWith(input_other);
1577 instruction->GetBlock()->RemoveInstruction(instruction);
1578 RecordSimplification();
1579 return;
1580 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1581 input_other->HasOnlyOneNonEnvironmentUse()) {
1582 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1583 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001584 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001585 input_other->InputAt(0),
1586 input_other->InputAt(1),
1587 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001588 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1589 input_other->GetBlock()->RemoveInstruction(input_other);
1590 RecordSimplification();
1591 return;
1592 }
1593 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001594 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1595 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1596 // or array Get with only a single use, short-circuit the subsequent simplification
1597 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1598 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1599 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1600 if (input_other->GetType() == find_type &&
1601 input_other->HasOnlyOneNonEnvironmentUse() &&
1602 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1603 instruction->ReplaceWith(input_other);
1604 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001605 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1606 instruction->ReplaceWith(input_other);
1607 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001608 } else {
1609 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1610 new_type, input_other, instruction->GetDexPc());
1611 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1612 }
1613 RecordSimplification();
1614 return;
1615 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001616 }
1617
1618 // We assume that GVN has run before, so we only perform a pointer comparison.
1619 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001620 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001621 if (instruction->GetLeft() == instruction->GetRight()) {
1622 // Replace code looking like
1623 // AND dst, src, src
1624 // with
1625 // src
1626 instruction->ReplaceWith(instruction->GetLeft());
1627 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001628 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001629 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001630 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001631
Anton Kirilove14dc862016-05-13 17:56:15 +01001632 if (TryDeMorganNegationFactoring(instruction)) {
1633 return;
1634 }
1635
1636 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1637 // so no need to return.
1638 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001639}
1640
Mark Mendellc4701932015-04-10 13:18:51 -04001641void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1642 VisitCondition(condition);
1643}
1644
1645void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1646 VisitCondition(condition);
1647}
1648
1649void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1650 VisitCondition(condition);
1651}
1652
1653void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1654 VisitCondition(condition);
1655}
1656
Anton Shaminbdd79352016-02-15 12:48:36 +06001657void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1658 VisitCondition(condition);
1659}
1660
1661void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1662 VisitCondition(condition);
1663}
1664
1665void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1666 VisitCondition(condition);
1667}
1668
1669void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1670 VisitCondition(condition);
1671}
Aart Bike9f37602015-10-09 11:15:55 -07001672
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001673// Recognize the following pattern:
1674// obj.getClass() ==/!= Foo.class
1675// And replace it with a constant value if the type of `obj` is statically known.
1676static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1677 HInstruction* input_one = condition->InputAt(0);
1678 HInstruction* input_two = condition->InputAt(1);
1679 HLoadClass* load_class = input_one->IsLoadClass()
Vladimir Markocde64972023-04-25 16:40:06 +00001680 ? input_one->AsLoadClass()
Vladimir Marko79dc2172023-04-05 10:33:07 +00001681 : input_two->AsLoadClassOrNull();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001682 if (load_class == nullptr) {
1683 return false;
1684 }
1685
1686 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1687 if (!class_rti.IsValid()) {
1688 // Unresolved class.
1689 return false;
1690 }
1691
1692 HInstanceFieldGet* field_get = (load_class == input_one)
Vladimir Marko79dc2172023-04-05 10:33:07 +00001693 ? input_two->AsInstanceFieldGetOrNull()
1694 : input_one->AsInstanceFieldGetOrNull();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001695 if (field_get == nullptr) {
1696 return false;
1697 }
1698
1699 HInstruction* receiver = field_get->InputAt(0);
1700 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1701 if (!receiver_type.IsExact()) {
1702 return false;
1703 }
1704
1705 {
1706 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001707 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001708 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1709 if (field_get->GetFieldInfo().GetField() != field) {
1710 return false;
1711 }
1712
1713 // We can replace the compare.
1714 int value = 0;
1715 if (receiver_type.IsEqual(class_rti)) {
1716 value = condition->IsEqual() ? 1 : 0;
1717 } else {
1718 value = condition->IsNotEqual() ? 1 : 0;
1719 }
1720 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1721 return true;
1722 }
1723}
1724
Mark Mendellc4701932015-04-10 13:18:51 -04001725void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001726 if (condition->IsEqual() || condition->IsNotEqual()) {
1727 if (RecognizeAndSimplifyClassCheck(condition)) {
1728 return;
1729 }
1730 }
1731
Anton Shaminbdd79352016-02-15 12:48:36 +06001732 // Reverse condition if left is constant. Our code generators prefer constant
1733 // on the right hand side.
1734 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1735 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001736 HCondition* replacement =
1737 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001738 // If it is a fp we must set the opposite bias.
1739 if (replacement != nullptr) {
1740 if (condition->IsLtBias()) {
1741 replacement->SetBias(ComparisonBias::kGtBias);
1742 } else if (condition->IsGtBias()) {
1743 replacement->SetBias(ComparisonBias::kLtBias);
1744 }
1745 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1746 RecordSimplification();
1747
1748 condition = replacement;
1749 }
1750 }
Mark Mendellc4701932015-04-10 13:18:51 -04001751
Mark Mendellc4701932015-04-10 13:18:51 -04001752 HInstruction* left = condition->GetLeft();
1753 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001754
1755 // Try to fold an HCompare into this HCondition.
1756
Mark Mendellc4701932015-04-10 13:18:51 -04001757 // We can only replace an HCondition which compares a Compare to 0.
1758 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1759 // condition with a long, float or double comparison as input.
Vladimir Markocde64972023-04-25 16:40:06 +00001760 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
Mark Mendellc4701932015-04-10 13:18:51 -04001761 // Conversion is not possible.
1762 return;
1763 }
1764
1765 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001766 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001767 // Someone else also wants the result of the compare.
1768 return;
1769 }
1770
Vladimir Marko46817b82016-03-29 12:21:58 +01001771 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001772 // There is a reference to the compare result in an environment. Do we really need it?
1773 if (GetGraph()->IsDebuggable()) {
1774 return;
1775 }
1776
1777 // We have to ensure that there are no deopt points in the sequence.
1778 if (left->HasAnyEnvironmentUseBefore(condition)) {
1779 return;
1780 }
1781 }
1782
1783 // Clean up any environment uses from the HCompare, if any.
1784 left->RemoveEnvironmentUsers();
1785
1786 // We have decided to fold the HCompare into the HCondition. Transfer the information.
Vladimir Markocde64972023-04-25 16:40:06 +00001787 condition->SetBias(left->AsCompare()->GetBias());
Mark Mendellc4701932015-04-10 13:18:51 -04001788
1789 // Replace the operands of the HCondition.
1790 condition->ReplaceInput(left->InputAt(0), 0);
1791 condition->ReplaceInput(left->InputAt(1), 1);
1792
1793 // Remove the HCompare.
1794 left->GetBlock()->RemoveInstruction(left);
1795
1796 RecordSimplification();
1797}
1798
Andreas Gampe9186ced2016-12-12 14:28:21 -08001799// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1800static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1801 // True, if the most significant bits of divisor are 0.
1802 return ((divisor & 0x7fffff) == 0);
1803}
1804
1805// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1806static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1807 // True, if the most significant bits of divisor are 0.
1808 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1809}
1810
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001811void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1812 HConstant* input_cst = instruction->GetConstantRight();
1813 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001814 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001815
1816 if ((input_cst != nullptr) && input_cst->IsOne()) {
1817 // Replace code looking like
1818 // DIV dst, src, 1
1819 // with
1820 // src
1821 instruction->ReplaceWith(input_other);
1822 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001823 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001824 return;
1825 }
1826
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001827 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001828 // Replace code looking like
1829 // DIV dst, src, -1
1830 // with
1831 // NEG dst, src
1832 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001833 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001834 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001835 return;
1836 }
1837
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001838 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001839 // Try replacing code looking like
1840 // DIV dst, src, constant
1841 // with
1842 // MUL dst, src, 1 / constant
1843 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001844 if (type == DataType::Type::kFloat64) {
Vladimir Markocde64972023-04-25 16:40:06 +00001845 double value = input_cst->AsDoubleConstant()->GetValue();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001846 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1847 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1848 }
1849 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001850 DCHECK_EQ(type, DataType::Type::kFloat32);
Vladimir Markocde64972023-04-25 16:40:06 +00001851 float value = input_cst->AsFloatConstant()->GetValue();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001852 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1853 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1854 }
1855 }
1856
1857 if (reciprocal != nullptr) {
1858 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001859 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001860 RecordSimplification();
1861 return;
1862 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001863 }
1864}
1865
Evgeny Astigeevich6587d912020-06-12 10:51:43 +01001866
1867// Search HDiv having the specified dividend and divisor which is in the specified basic block.
1868// Return nullptr if nothing has been found.
Santiago Aboy Solanes66a1abb2023-01-09 20:58:58 +00001869static HDiv* FindDivWithInputsInBasicBlock(HInstruction* dividend,
1870 HInstruction* divisor,
1871 HBasicBlock* basic_block) {
Evgeny Astigeevich6587d912020-06-12 10:51:43 +01001872 for (const HUseListNode<HInstruction*>& use : dividend->GetUses()) {
1873 HInstruction* user = use.GetUser();
Santiago Aboy Solanes66a1abb2023-01-09 20:58:58 +00001874 if (user->GetBlock() == basic_block &&
1875 user->IsDiv() &&
1876 user->InputAt(0) == dividend &&
1877 user->InputAt(1) == divisor) {
Vladimir Markocde64972023-04-25 16:40:06 +00001878 return user->AsDiv();
Evgeny Astigeevich6587d912020-06-12 10:51:43 +01001879 }
1880 }
1881 return nullptr;
1882}
1883
1884// If there is Div with the same inputs as Rem and in the same basic block, it can be reused.
1885// Rem is replaced with Mul+Sub which use the found Div.
1886void InstructionSimplifierVisitor::TryToReuseDiv(HRem* rem) {
1887 // As the optimization replaces Rem with Mul+Sub they prevent some loop optimizations
1888 // if the Rem is in a loop.
1889 // Check if it is allowed to optimize such Rems.
1890 if (rem->IsInLoop() && be_loop_friendly_) {
1891 return;
1892 }
1893 DataType::Type type = rem->GetResultType();
1894 if (!DataType::IsIntOrLongType(type)) {
1895 return;
1896 }
1897
1898 HBasicBlock* basic_block = rem->GetBlock();
1899 HInstruction* dividend = rem->GetLeft();
1900 HInstruction* divisor = rem->GetRight();
1901
1902 if (divisor->IsConstant()) {
1903 HConstant* input_cst = rem->GetConstantRight();
1904 DCHECK(input_cst->IsIntConstant() || input_cst->IsLongConstant());
1905 int64_t cst_value = Int64FromConstant(input_cst);
1906 if (cst_value == std::numeric_limits<int64_t>::min() || IsPowerOfTwo(std::abs(cst_value))) {
1907 // Such cases are usually handled in the code generator because they don't need Div at all.
1908 return;
1909 }
1910 }
1911
Santiago Aboy Solanes66a1abb2023-01-09 20:58:58 +00001912 HDiv* quotient = FindDivWithInputsInBasicBlock(dividend, divisor, basic_block);
Evgeny Astigeevich6587d912020-06-12 10:51:43 +01001913 if (quotient == nullptr) {
1914 return;
1915 }
1916 if (!quotient->StrictlyDominates(rem)) {
1917 quotient->MoveBefore(rem);
1918 }
1919
1920 ArenaAllocator* allocator = GetGraph()->GetAllocator();
1921 HInstruction* mul = new (allocator) HMul(type, quotient, divisor);
1922 basic_block->InsertInstructionBefore(mul, rem);
1923 HInstruction* sub = new (allocator) HSub(type, dividend, mul);
1924 basic_block->InsertInstructionBefore(sub, rem);
1925 rem->ReplaceWith(sub);
1926 basic_block->RemoveInstruction(rem);
1927 RecordSimplification();
1928}
1929
1930void InstructionSimplifierVisitor::VisitRem(HRem* rem) {
1931 TryToReuseDiv(rem);
1932}
1933
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001934void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1935 HConstant* input_cst = instruction->GetConstantRight();
1936 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001937 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001938 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001939 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001940
1941 if (input_cst == nullptr) {
1942 return;
1943 }
1944
1945 if (input_cst->IsOne()) {
1946 // Replace code looking like
1947 // MUL dst, src, 1
1948 // with
1949 // src
1950 instruction->ReplaceWith(input_other);
1951 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001952 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001953 return;
1954 }
1955
1956 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001957 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001958 // Replace code looking like
1959 // MUL dst, src, -1
1960 // with
1961 // NEG dst, src
1962 HNeg* neg = new (allocator) HNeg(type, input_other);
1963 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001964 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001965 return;
1966 }
1967
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001968 if (DataType::IsFloatingPointType(type) &&
Vladimir Markocde64972023-04-25 16:40:06 +00001969 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1970 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001971 // Replace code looking like
1972 // FP_MUL dst, src, 2.0
1973 // with
1974 // FP_ADD dst, src, src
1975 // The 'int' and 'long' cases are handled below.
1976 block->ReplaceAndRemoveInstructionWith(instruction,
1977 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001978 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001979 return;
1980 }
1981
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001982 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001983 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001984 // Even though constant propagation also takes care of the zero case, other
1985 // optimizations can lead to having a zero multiplication.
1986 if (factor == 0) {
1987 // Replace code looking like
1988 // MUL dst, src, 0
1989 // with
1990 // 0
1991 instruction->ReplaceWith(input_cst);
1992 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001993 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001994 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001995 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001996 // Replace code looking like
1997 // MUL dst, src, pow_of_2
1998 // with
1999 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00002000 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00002001 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002002 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01002003 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01002004 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00002005 } else if (IsPowerOfTwo(factor - 1)) {
2006 // Transform code looking like
2007 // MUL dst, src, (2^n + 1)
2008 // into
2009 // SHL tmp, src, n
2010 // ADD dst, src, tmp
2011 HShl* shl = new (allocator) HShl(type,
2012 input_other,
2013 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
2014 HAdd* add = new (allocator) HAdd(type, input_other, shl);
2015
2016 block->InsertInstructionBefore(shl, instruction);
2017 block->ReplaceAndRemoveInstructionWith(instruction, add);
2018 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01002019 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00002020 } else if (IsPowerOfTwo(factor + 1)) {
2021 // Transform code looking like
2022 // MUL dst, src, (2^n - 1)
2023 // into
2024 // SHL tmp, src, n
2025 // SUB dst, tmp, src
2026 HShl* shl = new (allocator) HShl(type,
2027 input_other,
2028 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
2029 HSub* sub = new (allocator) HSub(type, shl, input_other);
2030
2031 block->InsertInstructionBefore(shl, instruction);
2032 block->ReplaceAndRemoveInstructionWith(instruction, sub);
2033 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01002034 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002035 }
2036 }
Anton Kirilove14dc862016-05-13 17:56:15 +01002037
2038 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2039 // so no need to return.
2040 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002041}
2042
Alexandre Rames188d4312015-04-09 18:30:21 +01002043void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
2044 HInstruction* input = instruction->GetInput();
2045 if (input->IsNeg()) {
2046 // Replace code looking like
2047 // NEG tmp, src
2048 // NEG dst, tmp
2049 // with
2050 // src
Vladimir Markocde64972023-04-25 16:40:06 +00002051 HNeg* previous_neg = input->AsNeg();
Alexandre Rames188d4312015-04-09 18:30:21 +01002052 instruction->ReplaceWith(previous_neg->GetInput());
2053 instruction->GetBlock()->RemoveInstruction(instruction);
2054 // We perform the optimization even if the input negation has environment
2055 // uses since it allows removing the current instruction. But we only delete
2056 // the input negation only if it is does not have any uses left.
2057 if (!previous_neg->HasUses()) {
2058 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
2059 }
2060 RecordSimplification();
2061 return;
2062 }
2063
Serguei Katkov339dfc22015-04-20 12:29:32 +06002064 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002065 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01002066 // Replace code looking like
2067 // SUB tmp, a, b
2068 // NEG dst, tmp
2069 // with
2070 // SUB dst, b, a
2071 // We do not perform the optimization if the input subtraction has
2072 // environment uses or multiple non-environment uses as it could lead to
2073 // worse code. In particular, we do not want the live ranges of `a` and `b`
2074 // to be extended if we are not sure the initial 'SUB' instruction can be
2075 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06002076 // We do not perform optimization for fp because we could lose the sign of zero.
Vladimir Markocde64972023-04-25 16:40:06 +00002077 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002078 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
2079 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01002080 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
2081 if (!sub->HasUses()) {
2082 sub->GetBlock()->RemoveInstruction(sub);
2083 }
2084 RecordSimplification();
2085 }
2086}
2087
2088void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
2089 HInstruction* input = instruction->GetInput();
2090 if (input->IsNot()) {
2091 // Replace code looking like
2092 // NOT tmp, src
2093 // NOT dst, tmp
2094 // with
2095 // src
2096 // We perform the optimization even if the input negation has environment
2097 // uses since it allows removing the current instruction. But we only delete
2098 // the input negation only if it is does not have any uses left.
Vladimir Markocde64972023-04-25 16:40:06 +00002099 HNot* previous_not = input->AsNot();
Alexandre Rames188d4312015-04-09 18:30:21 +01002100 instruction->ReplaceWith(previous_not->GetInput());
2101 instruction->GetBlock()->RemoveInstruction(instruction);
2102 if (!previous_not->HasUses()) {
2103 previous_not->GetBlock()->RemoveInstruction(previous_not);
2104 }
2105 RecordSimplification();
2106 }
2107}
2108
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002109void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
2110 HConstant* input_cst = instruction->GetConstantRight();
2111 HInstruction* input_other = instruction->GetLeastConstantLeft();
2112
Roland Levillain1a653882016-03-18 18:05:57 +00002113 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002114 // Replace code looking like
2115 // OR dst, src, 0
2116 // with
2117 // src
2118 instruction->ReplaceWith(input_other);
2119 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002120 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002121 return;
2122 }
2123
2124 // We assume that GVN has run before, so we only perform a pointer comparison.
2125 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01002126 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002127 if (instruction->GetLeft() == instruction->GetRight()) {
2128 // Replace code looking like
2129 // OR dst, src, src
2130 // with
2131 // src
2132 instruction->ReplaceWith(instruction->GetLeft());
2133 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002134 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002135 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002136 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002137
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002138 if (TryDeMorganNegationFactoring(instruction)) return;
2139
Anton Kirilove14dc862016-05-13 17:56:15 +01002140 if (TryReplaceWithRotate(instruction)) {
2141 return;
2142 }
2143
2144 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2145 // so no need to return.
2146 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002147}
2148
2149void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
2150 VisitShift(instruction);
2151}
2152
2153void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
2154 VisitShift(instruction);
2155}
2156
2157void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
2158 HConstant* input_cst = instruction->GetConstantRight();
2159 HInstruction* input_other = instruction->GetLeastConstantLeft();
2160
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002161 DataType::Type type = instruction->GetType();
2162 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06002163 return;
2164 }
2165
Roland Levillain1a653882016-03-18 18:05:57 +00002166 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002167 // Replace code looking like
2168 // SUB dst, src, 0
2169 // with
2170 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06002171 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
2172 // `x` is `-0.0`, the former expression yields `0.0`, while the later
2173 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002174 instruction->ReplaceWith(input_other);
2175 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002176 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002177 return;
2178 }
2179
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002180 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002181 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002182
Alexandre Rames188d4312015-04-09 18:30:21 +01002183 HInstruction* left = instruction->GetLeft();
2184 HInstruction* right = instruction->GetRight();
2185 if (left->IsConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +00002186 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002187 // Replace code looking like
2188 // SUB dst, 0, src
2189 // with
2190 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01002191 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002192 // `x` is `0.0`, the former expression yields `0.0`, while the later
2193 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01002194 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002195 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01002196 RecordSimplification();
2197 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002198 }
2199 }
Alexandre Rames188d4312015-04-09 18:30:21 +01002200
2201 if (left->IsNeg() && right->IsNeg()) {
2202 if (TryMoveNegOnInputsAfterBinop(instruction)) {
2203 return;
2204 }
2205 }
2206
2207 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
2208 // Replace code looking like
2209 // NEG tmp, b
2210 // SUB dst, a, tmp
2211 // with
2212 // ADD dst, a, b
Vladimir Markocde64972023-04-25 16:40:06 +00002213 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002214 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2215 RecordSimplification();
2216 right->GetBlock()->RemoveInstruction(right);
2217 return;
2218 }
2219
2220 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2221 // Replace code looking like
2222 // NEG tmp, a
2223 // SUB dst, tmp, b
2224 // with
2225 // ADD tmp, a, b
2226 // NEG dst, tmp
2227 // The second version is not intrinsically better, but enables more
2228 // transformations.
Vladimir Markocde64972023-04-25 16:40:06 +00002229 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002230 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002231 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002232 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2233 instruction->ReplaceWith(neg);
2234 instruction->GetBlock()->RemoveInstruction(instruction);
2235 RecordSimplification();
2236 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002237 return;
2238 }
2239
2240 if (TrySubtractionChainSimplification(instruction)) {
2241 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002242 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002243
2244 if (left->IsAdd()) {
2245 // Replace code patterns looking like
2246 // ADD dst1, x, y ADD dst1, x, y
2247 // SUB dst2, dst1, y SUB dst2, dst1, x
2248 // with
2249 // ADD dst1, x, y
2250 // SUB instruction is not needed in this case, we may use
2251 // one of inputs of ADD instead.
2252 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002253 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002254 if (left->InputAt(1) == right) {
2255 instruction->ReplaceWith(left->InputAt(0));
2256 RecordSimplification();
2257 instruction->GetBlock()->RemoveInstruction(instruction);
2258 return;
2259 } else if (left->InputAt(0) == right) {
2260 instruction->ReplaceWith(left->InputAt(1));
2261 RecordSimplification();
2262 instruction->GetBlock()->RemoveInstruction(instruction);
2263 return;
2264 }
2265 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002266}
2267
2268void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2269 VisitShift(instruction);
2270}
2271
2272void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2273 HConstant* input_cst = instruction->GetConstantRight();
2274 HInstruction* input_other = instruction->GetLeastConstantLeft();
2275
Roland Levillain1a653882016-03-18 18:05:57 +00002276 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002277 // Replace code looking like
2278 // XOR dst, src, 0
2279 // with
2280 // src
2281 instruction->ReplaceWith(input_other);
2282 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002283 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002284 return;
2285 }
2286
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002287 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002288 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002289 // Replace code looking like
2290 // XOR dst, src, 1
2291 // with
2292 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002293 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002294 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2295 RecordSimplification();
2296 return;
2297 }
2298
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002299 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2300 // Replace code looking like
2301 // XOR dst, src, 0xFFF...FF
2302 // with
2303 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002304 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002305 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002306 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002307 return;
2308 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002309
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002310 HInstruction* left = instruction->GetLeft();
2311 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002312 if (((left->IsNot() && right->IsNot()) ||
2313 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002314 left->HasOnlyOneNonEnvironmentUse() &&
2315 right->HasOnlyOneNonEnvironmentUse()) {
2316 // Replace code looking like
2317 // NOT nota, a
2318 // NOT notb, b
2319 // XOR dst, nota, notb
2320 // with
2321 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002322 instruction->ReplaceInput(left->InputAt(0), 0);
2323 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002324 left->GetBlock()->RemoveInstruction(left);
2325 right->GetBlock()->RemoveInstruction(right);
2326 RecordSimplification();
2327 return;
2328 }
2329
Anton Kirilove14dc862016-05-13 17:56:15 +01002330 if (TryReplaceWithRotate(instruction)) {
2331 return;
2332 }
2333
2334 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2335 // so no need to return.
2336 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002337}
2338
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002339void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2340 HInstruction* argument = instruction->InputAt(1);
2341 HInstruction* receiver = instruction->InputAt(0);
2342 if (receiver == argument) {
2343 // Because String.equals is an instance call, the receiver is
2344 // a null check if we don't know it's null. The argument however, will
2345 // be the actual object. So we cannot end up in a situation where both
2346 // are equal but could be null.
2347 DCHECK(CanEnsureNotNullAt(argument, instruction));
2348 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2349 instruction->GetBlock()->RemoveInstruction(instruction);
2350 } else {
2351 StringEqualsOptimizations optimizations(instruction);
2352 if (CanEnsureNotNullAt(argument, instruction)) {
2353 optimizations.SetArgumentNotNull();
2354 }
2355 ScopedObjectAccess soa(Thread::Current());
2356 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2357 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2358 optimizations.SetArgumentIsString();
2359 }
2360 }
2361}
2362
2363static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2364 if (potential_length->IsArrayLength()) {
2365 return potential_length->InputAt(0) == potential_array;
2366 }
2367
2368 if (potential_array->IsNewArray()) {
Vladimir Markocde64972023-04-25 16:40:06 +00002369 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002370 }
2371
2372 return false;
2373}
2374
2375void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2376 HInstruction* source = instruction->InputAt(0);
2377 HInstruction* destination = instruction->InputAt(2);
2378 HInstruction* count = instruction->InputAt(4);
2379 SystemArrayCopyOptimizations optimizations(instruction);
2380 if (CanEnsureNotNullAt(source, instruction)) {
2381 optimizations.SetSourceIsNotNull();
2382 }
2383 if (CanEnsureNotNullAt(destination, instruction)) {
2384 optimizations.SetDestinationIsNotNull();
2385 }
2386 if (destination == source) {
2387 optimizations.SetDestinationIsSource();
2388 }
2389
2390 if (IsArrayLengthOf(count, source)) {
2391 optimizations.SetCountIsSourceLength();
2392 }
2393
2394 if (IsArrayLengthOf(count, destination)) {
2395 optimizations.SetCountIsDestinationLength();
2396 }
2397
2398 {
2399 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002400 DataType::Type source_component_type = DataType::Type::kVoid;
2401 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002402 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2403 if (destination_rti.IsValid()) {
2404 if (destination_rti.IsObjectArray()) {
2405 if (destination_rti.IsExact()) {
2406 optimizations.SetDoesNotNeedTypeCheck();
2407 }
2408 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002409 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002410 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002411 destination_component_type = DataTypeFromPrimitive(
2412 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002413 optimizations.SetDestinationIsPrimitiveArray();
2414 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2415 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002416 }
2417 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002418 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2419 if (source_rti.IsValid()) {
2420 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2421 optimizations.SetDoesNotNeedTypeCheck();
2422 }
2423 if (source_rti.IsPrimitiveArrayClass()) {
2424 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002425 source_component_type = DataTypeFromPrimitive(
2426 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002427 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2428 optimizations.SetSourceIsNonPrimitiveArray();
2429 }
2430 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002431 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002432 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002433 (source_component_type == destination_component_type)) {
2434 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2435 PointerSize image_size = class_linker->GetImagePointerSize();
Vladimir Markocde64972023-04-25 16:40:06 +00002436 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
Vladimir Markod93e3742018-07-18 10:58:13 +01002437 ObjPtr<mirror::Class> system = invoke->GetResolvedMethod()->GetDeclaringClass();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002438 ArtMethod* method = nullptr;
2439 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002440 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002441 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002442 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002443 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002444 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002445 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002446 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002447 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002448 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002449 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002450 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002451 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002452 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002453 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002454 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002455 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002456 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002457 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002458 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002459 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002460 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002461 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002462 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002463 break;
2464 default:
2465 LOG(FATAL) << "Unreachable";
2466 }
2467 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002468 DCHECK(method->IsStatic());
2469 DCHECK(method->GetDeclaringClass() == system);
Mythri Alled60aff52023-04-26 12:56:36 +00002470 invoke->SetResolvedMethod(method, !codegen_->GetGraph()->IsDebuggable());
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002471 // Sharpen the new invoke. Note that we do not update the dex method index of
2472 // the invoke, as we would need to look it up in the current dex file, and it
2473 // is unlikely that it exists. The most usual situation for such typed
2474 // arraycopy methods is a direct pointer to the boot image.
Nicolas Geoffrayd5a86952021-01-19 10:35:54 +00002475 invoke->SetDispatchInfo(HSharpening::SharpenLoadMethod(
2476 method,
2477 /* has_method_id= */ true,
2478 /* for_interface_call= */ false,
2479 codegen_));
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002480 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002481 }
2482}
2483
Aart Bik2a6aad92016-02-25 11:32:32 -08002484void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2485 DCHECK(invoke->IsInvokeStaticOrDirect());
2486 uint32_t dex_pc = invoke->GetDexPc();
2487 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002488 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002489 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2490 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002491 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002492 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2493 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00002494 kNeedsEnvironment,
Aart Bik2a6aad92016-02-25 11:32:32 -08002495 kNoSideEffects,
2496 kNoThrow);
2497 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002498 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002499 nan = GetGraph()->GetIntConstant(0x7fc00000);
2500 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00002501 kNeedsEnvironment,
Aart Bik2a6aad92016-02-25 11:32:32 -08002502 kNoSideEffects,
2503 kNoThrow);
2504 }
2505 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002506 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002507 condition->SetBias(ComparisonBias::kLtBias);
2508 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2509 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002510 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002511 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2512 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2513}
2514
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002515void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2516 HInstruction* str = invoke->InputAt(0);
2517 HInstruction* index = invoke->InputAt(1);
2518 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002519 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002520 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2521 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Andreas Gampe3db70682018-12-26 15:12:03 -08002522 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002523 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002524 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Andreas Gampe3db70682018-12-26 15:12:03 -08002525 index, length, dex_pc, /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002526 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002527 HArrayGet* array_get = new (allocator) HArrayGet(str,
2528 bounds_check,
2529 DataType::Type::kUint16,
2530 SideEffects::None(), // Strings are immutable.
2531 dex_pc,
Andreas Gampe3db70682018-12-26 15:12:03 -08002532 /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002533 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2534 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2535 GetGraph()->SetHasBoundsChecks(true);
2536}
2537
Vladimir Marko5f846072020-04-09 13:20:11 +01002538void InstructionSimplifierVisitor::SimplifyStringLength(HInvoke* invoke) {
Vladimir Markodce016e2016-04-28 13:10:02 +01002539 HInstruction* str = invoke->InputAt(0);
2540 uint32_t dex_pc = invoke->GetDexPc();
2541 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2542 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002543 HArrayLength* length =
Andreas Gampe3db70682018-12-26 15:12:03 -08002544 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko5f846072020-04-09 13:20:11 +01002545 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, length);
Vladimir Markodce016e2016-04-28 13:10:02 +01002546}
2547
Vladimir Marko6fa44042018-03-19 18:42:49 +00002548void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2549 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2550 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2551 if (invoke->InputAt(0)->IsLoadString()) {
Vladimir Markocde64972023-04-25 16:40:06 +00002552 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
Vladimir Marko6fa44042018-03-19 18:42:49 +00002553 const DexFile& dex_file = load_string->GetDexFile();
2554 uint32_t utf16_length;
2555 const char* data =
2556 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2557 if (utf16_length == 0) {
2558 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2559 invoke->GetBlock()->RemoveInstruction(invoke);
2560 RecordSimplification();
2561 return;
2562 }
2563 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2564 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2565 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2566 uint32_t c = GetUtf16FromUtf8(&data);
2567 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2568 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2569 uint32_t dex_pc = invoke->GetDexPc();
2570 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2571 HEqual* equal =
2572 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2573 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2574 HSelect* result = new (allocator) HSelect(equal,
2575 GetGraph()->GetIntConstant(0),
2576 GetGraph()->GetIntConstant(-1),
2577 dex_pc);
2578 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2579 RecordSimplification();
2580 return;
2581 }
2582 }
2583}
2584
Aart Bikff7d89c2016-11-07 08:49:28 -08002585// This method should only be used on intrinsics whose sole way of throwing an
2586// exception is raising a NPE when the nth argument is null. If that argument
2587// is provably non-null, we can clear the flag.
2588void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2589 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002590 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002591 invoke->SetCanThrow(false);
2592 }
2593}
2594
Aart Bik71bf7b42016-11-16 10:17:46 -08002595// Methods that return "this" can replace the returned value with the receiver.
2596void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2597 if (invoke->HasUses()) {
2598 HInstruction* receiver = invoke->InputAt(0);
2599 invoke->ReplaceWith(receiver);
2600 RecordSimplification();
2601 }
2602}
2603
2604// Helper method for StringBuffer escape analysis.
2605static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2606 if (user->IsInvokeStaticOrDirect()) {
2607 // Any constructor on StringBuffer is okay.
Vladimir Markocde64972023-04-25 16:40:06 +00002608 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2609 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002610 user->InputAt(0) == reference;
2611 } else if (user->IsInvokeVirtual()) {
Vladimir Markocde64972023-04-25 16:40:06 +00002612 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
Aart Bik71bf7b42016-11-16 10:17:46 -08002613 case Intrinsics::kStringBufferLength:
2614 case Intrinsics::kStringBufferToString:
2615 DCHECK_EQ(user->InputAt(0), reference);
2616 return true;
2617 case Intrinsics::kStringBufferAppend:
2618 // Returns "this", so only okay if no further uses.
2619 DCHECK_EQ(user->InputAt(0), reference);
2620 DCHECK_NE(user->InputAt(1), reference);
2621 return !user->HasUses();
2622 default:
2623 break;
2624 }
2625 }
2626 return false;
2627}
2628
Vladimir Marko552a1342017-10-31 10:56:47 +00002629static bool TryReplaceStringBuilderAppend(HInvoke* invoke) {
2630 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringBuilderToString);
2631 if (invoke->CanThrowIntoCatchBlock()) {
2632 return false;
2633 }
2634
2635 HBasicBlock* block = invoke->GetBlock();
2636 HInstruction* sb = invoke->InputAt(0);
2637
2638 // We support only a new StringBuilder, otherwise we cannot ensure that
2639 // the StringBuilder data does not need to be populated for other users.
2640 if (!sb->IsNewInstance()) {
2641 return false;
2642 }
2643
2644 // For now, we support only single-block recognition.
2645 // (Ternary operators feeding the append could be implemented.)
2646 for (const HUseListNode<HInstruction*>& use : sb->GetUses()) {
2647 if (use.GetUser()->GetBlock() != block) {
2648 return false;
2649 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002650 // The append pattern uses the StringBuilder only as the first argument.
2651 if (use.GetIndex() != 0u) {
2652 return false;
2653 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002654 }
2655
2656 // Collect args and check for unexpected uses.
2657 // We expect one call to a constructor with no arguments, one constructor fence (unless
2658 // eliminated), some number of append calls and one call to StringBuilder.toString().
2659 bool seen_constructor = false;
2660 bool seen_constructor_fence = false;
2661 bool seen_to_string = false;
2662 uint32_t format = 0u;
2663 uint32_t num_args = 0u;
Vladimir Marko41de4502019-05-21 10:00:15 +01002664 bool has_fp_args = false;
Vladimir Marko552a1342017-10-31 10:56:47 +00002665 HInstruction* args[StringBuilderAppend::kMaxArgs]; // Added in reverse order.
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002666 for (HBackwardInstructionIterator iter(block->GetInstructions()); !iter.Done(); iter.Advance()) {
2667 HInstruction* user = iter.Current();
2668 // Instructions of interest apply to `sb`, skip those that do not involve `sb`.
2669 if (user->InputCount() == 0u || user->InputAt(0u) != sb) {
2670 continue;
Vladimir Marko552a1342017-10-31 10:56:47 +00002671 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002672 // We visit the uses in reverse order, so the StringBuilder.toString() must come first.
Vladimir Marko552a1342017-10-31 10:56:47 +00002673 if (!seen_to_string) {
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002674 if (user == invoke) {
Vladimir Marko552a1342017-10-31 10:56:47 +00002675 seen_to_string = true;
2676 continue;
2677 } else {
2678 return false;
2679 }
2680 }
2681 // Then we should see the arguments.
2682 if (user->IsInvokeVirtual()) {
Vladimir Markocde64972023-04-25 16:40:06 +00002683 HInvokeVirtual* as_invoke_virtual = user->AsInvokeVirtual();
Vladimir Marko552a1342017-10-31 10:56:47 +00002684 DCHECK(!seen_constructor);
2685 DCHECK(!seen_constructor_fence);
2686 StringBuilderAppend::Argument arg;
2687 switch (as_invoke_virtual->GetIntrinsic()) {
2688 case Intrinsics::kStringBuilderAppendObject:
2689 // TODO: Unimplemented, needs to call String.valueOf().
2690 return false;
2691 case Intrinsics::kStringBuilderAppendString:
2692 arg = StringBuilderAppend::Argument::kString;
2693 break;
2694 case Intrinsics::kStringBuilderAppendCharArray:
2695 // TODO: Unimplemented, StringBuilder.append(char[]) can throw NPE and we would
2696 // not have the correct stack trace for it.
2697 return false;
2698 case Intrinsics::kStringBuilderAppendBoolean:
2699 arg = StringBuilderAppend::Argument::kBoolean;
2700 break;
2701 case Intrinsics::kStringBuilderAppendChar:
2702 arg = StringBuilderAppend::Argument::kChar;
2703 break;
2704 case Intrinsics::kStringBuilderAppendInt:
2705 arg = StringBuilderAppend::Argument::kInt;
2706 break;
2707 case Intrinsics::kStringBuilderAppendLong:
2708 arg = StringBuilderAppend::Argument::kLong;
2709 break;
Vladimir Marko41de4502019-05-21 10:00:15 +01002710 case Intrinsics::kStringBuilderAppendFloat:
2711 arg = StringBuilderAppend::Argument::kFloat;
2712 has_fp_args = true;
2713 break;
2714 case Intrinsics::kStringBuilderAppendDouble:
2715 arg = StringBuilderAppend::Argument::kDouble;
2716 has_fp_args = true;
2717 break;
Vladimir Marko552a1342017-10-31 10:56:47 +00002718 case Intrinsics::kStringBuilderAppendCharSequence: {
Vladimir Markocde64972023-04-25 16:40:06 +00002719 ReferenceTypeInfo rti = user->AsInvokeVirtual()->InputAt(1)->GetReferenceTypeInfo();
Vladimir Marko552a1342017-10-31 10:56:47 +00002720 if (!rti.IsValid()) {
2721 return false;
2722 }
2723 ScopedObjectAccess soa(Thread::Current());
2724 Handle<mirror::Class> input_type = rti.GetTypeHandle();
2725 DCHECK(input_type != nullptr);
2726 if (input_type.Get() == GetClassRoot<mirror::String>()) {
2727 arg = StringBuilderAppend::Argument::kString;
2728 } else {
2729 // TODO: Check and implement for StringBuilder. We could find the StringBuilder's
2730 // internal char[] inconsistent with the length, or the string compression
2731 // of the result could be compromised with a concurrent modification, and
2732 // we would need to throw appropriate exceptions.
2733 return false;
2734 }
2735 break;
2736 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002737 default: {
2738 return false;
2739 }
2740 }
2741 // Uses of the append return value should have been replaced with the first input.
2742 DCHECK(!as_invoke_virtual->HasUses());
2743 DCHECK(!as_invoke_virtual->HasEnvironmentUses());
2744 if (num_args == StringBuilderAppend::kMaxArgs) {
2745 return false;
2746 }
2747 format = (format << StringBuilderAppend::kBitsPerArg) | static_cast<uint32_t>(arg);
2748 args[num_args] = as_invoke_virtual->InputAt(1u);
2749 ++num_args;
Victor Chang16a0d412022-10-07 11:49:43 +01002750 } else if (user->IsInvokeStaticOrDirect() &&
Vladimir Markocde64972023-04-25 16:40:06 +00002751 user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2752 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
2753 user->AsInvokeStaticOrDirect()->GetNumberOfArguments() == 1u) {
Victor Chang16a0d412022-10-07 11:49:43 +01002754 // After arguments, we should see the constructor.
2755 // We accept only the constructor with no extra arguments.
2756 DCHECK(!seen_constructor);
Vladimir Marko552a1342017-10-31 10:56:47 +00002757 DCHECK(!seen_constructor_fence);
2758 seen_constructor = true;
2759 } else if (user->IsConstructorFence()) {
2760 // The last use we see is the constructor fence.
2761 DCHECK(seen_constructor);
2762 DCHECK(!seen_constructor_fence);
2763 seen_constructor_fence = true;
2764 } else {
2765 return false;
2766 }
2767 }
2768
2769 if (num_args == 0u) {
2770 return false;
2771 }
2772
2773 // Check environment uses.
2774 for (const HUseListNode<HEnvironment*>& use : sb->GetEnvUses()) {
2775 HInstruction* holder = use.GetUser()->GetHolder();
2776 if (holder->GetBlock() != block) {
2777 return false;
2778 }
2779 // Accept only calls on the StringBuilder (which shall all be removed).
2780 // TODO: Carve-out for const-string? Or rely on environment pruning (to be implemented)?
2781 if (holder->InputCount() == 0 || holder->InputAt(0) != sb) {
2782 return false;
2783 }
2784 }
2785
2786 // Create replacement instruction.
2787 HIntConstant* fmt = block->GetGraph()->GetIntConstant(static_cast<int32_t>(format));
2788 ArenaAllocator* allocator = block->GetGraph()->GetAllocator();
Vladimir Marko41de4502019-05-21 10:00:15 +01002789 HStringBuilderAppend* append = new (allocator) HStringBuilderAppend(
2790 fmt, num_args, has_fp_args, allocator, invoke->GetDexPc());
Santiago Aboy Solanese05bc3e2023-02-20 14:26:23 +00002791 append->SetReferenceTypeInfoIfValid(invoke->GetReferenceTypeInfo());
Vladimir Marko552a1342017-10-31 10:56:47 +00002792 for (size_t i = 0; i != num_args; ++i) {
2793 append->SetArgumentAt(i, args[num_args - 1u - i]);
2794 }
2795 block->InsertInstructionBefore(append, invoke);
Vladimir Markob1fe5e12020-03-10 14:30:49 +00002796 DCHECK(!invoke->CanBeNull());
2797 DCHECK(!append->CanBeNull());
Vladimir Marko552a1342017-10-31 10:56:47 +00002798 invoke->ReplaceWith(append);
2799 // Copy environment, except for the StringBuilder uses.
Vladimir Marko56f13322019-11-15 14:07:19 +00002800 for (HEnvironment* env = invoke->GetEnvironment(); env != nullptr; env = env->GetParent()) {
2801 for (size_t i = 0, size = env->Size(); i != size; ++i) {
2802 if (env->GetInstructionAt(i) == sb) {
2803 env->RemoveAsUserOfInput(i);
2804 env->SetRawEnvAt(i, /*instruction=*/ nullptr);
2805 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002806 }
2807 }
2808 append->CopyEnvironmentFrom(invoke->GetEnvironment());
2809 // Remove the old instruction.
2810 block->RemoveInstruction(invoke);
2811 // Remove the StringBuilder's uses and StringBuilder.
2812 while (sb->HasNonEnvironmentUses()) {
2813 block->RemoveInstruction(sb->GetUses().front().GetUser());
2814 }
2815 DCHECK(!sb->HasEnvironmentUses());
2816 block->RemoveInstruction(sb);
2817 return true;
2818}
2819
Aart Bik71bf7b42016-11-16 10:17:46 -08002820// Certain allocation intrinsics are not removed by dead code elimination
2821// because of potentially throwing an OOM exception or other side effects.
2822// This method removes such intrinsics when special circumstances allow.
2823void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2824 if (!invoke->HasUses()) {
2825 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2826 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2827 // call does not escape since only thread-local synchronization may be removed.
2828 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2829 HInstruction* receiver = invoke->InputAt(0);
2830 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2831 invoke->GetBlock()->RemoveInstruction(invoke);
2832 RecordSimplification();
2833 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002834 } else if (invoke->GetIntrinsic() == Intrinsics::kStringBuilderToString &&
2835 TryReplaceStringBuilderAppend(invoke)) {
2836 RecordSimplification();
Aart Bik71bf7b42016-11-16 10:17:46 -08002837 }
2838}
2839
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002840void InstructionSimplifierVisitor::SimplifyVarHandleIntrinsic(HInvoke* invoke) {
2841 DCHECK(invoke->IsInvokePolymorphic());
2842 VarHandleOptimizations optimizations(invoke);
2843
2844 if (optimizations.GetDoNotIntrinsify()) {
2845 // Preceding static checks disabled intrinsic, so no need to analyze further.
2846 return;
2847 }
2848
2849 size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002850 if (expected_coordinates_count != 0u) {
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002851 HInstruction* object = invoke->InputAt(1);
Ulya Trafimovich3676b362021-09-02 16:13:51 +01002852 // The following has been ensured by static checks in the instruction builder.
2853 DCHECK(object->GetType() == DataType::Type::kReference);
2854 // Re-check for null constant, as this might have changed after the inliner.
2855 if (object->IsNullConstant()) {
2856 optimizations.SetDoNotIntrinsify();
2857 return;
2858 }
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002859 // Test whether we can avoid the null check on the object.
2860 if (CanEnsureNotNullAt(object, invoke)) {
2861 optimizations.SetSkipObjectNullCheck();
2862 }
2863 }
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002864
2865 if (CanUseKnownBootImageVarHandle(invoke)) {
2866 optimizations.SetUseKnownBootImageVarHandle();
2867 }
2868}
2869
2870bool InstructionSimplifierVisitor::CanUseKnownBootImageVarHandle(HInvoke* invoke) {
2871 // If the `VarHandle` comes from a static final field of an initialized class in
2872 // the boot image, we can do the checks at compile time. We do this optimization only
2873 // for AOT and only for field handles when we can avoid all checks. This avoids the
2874 // possibility of the code concurrently messing with the `VarHandle` using reflection,
2875 // we simply perform the operation with the `VarHandle` as seen at compile time.
2876 // TODO: Extend this to arrays to support the `AtomicIntegerArray` class.
2877 const CompilerOptions& compiler_options = codegen_->GetCompilerOptions();
2878 if (!compiler_options.IsAotCompiler()) {
2879 return false;
2880 }
2881 size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
2882 if (expected_coordinates_count == 2u) {
2883 return false;
2884 }
2885 HInstruction* var_handle_instruction = invoke->InputAt(0);
2886 if (var_handle_instruction->IsNullCheck()) {
2887 var_handle_instruction = var_handle_instruction->InputAt(0);
2888 }
2889 if (!var_handle_instruction->IsStaticFieldGet()) {
2890 return false;
2891 }
Vladimir Markocde64972023-04-25 16:40:06 +00002892 ArtField* field = var_handle_instruction->AsStaticFieldGet()->GetFieldInfo().GetField();
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002893 DCHECK(field->IsStatic());
2894 if (!field->IsFinal()) {
2895 return false;
2896 }
2897 ScopedObjectAccess soa(Thread::Current());
2898 ObjPtr<mirror::Class> declaring_class = field->GetDeclaringClass();
2899 if (!declaring_class->IsVisiblyInitialized()) {
2900 // During AOT compilation, dex2oat ensures that initialized classes are visibly initialized.
2901 DCHECK(!declaring_class->IsInitialized());
2902 return false;
2903 }
Vladimir Markoc05a32a2022-04-29 09:34:04 +01002904 HInstruction* load_class = var_handle_instruction->InputAt(0);
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002905 if (kIsDebugBuild) {
2906 bool is_in_boot_image = false;
2907 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(declaring_class)) {
2908 is_in_boot_image = true;
2909 } else if (compiler_options.IsBootImage() || compiler_options.IsBootImageExtension()) {
2910 std::string storage;
2911 const char* descriptor = declaring_class->GetDescriptor(&storage);
2912 is_in_boot_image = compiler_options.IsImageClass(descriptor);
2913 }
Vladimir Marko1fbfa9b2022-04-28 15:46:40 +01002914 CHECK_EQ(is_in_boot_image,
Vladimir Markocde64972023-04-25 16:40:06 +00002915 load_class->IsLoadClass() && load_class->AsLoadClass()->IsInBootImage());
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002916 }
Vladimir Markocde64972023-04-25 16:40:06 +00002917 if (!load_class->IsLoadClass() || !load_class->AsLoadClass()->IsInBootImage()) {
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002918 return false;
2919 }
2920
2921 // Get the `VarHandle` object and check its class.
2922 ObjPtr<mirror::Class> expected_var_handle_class;
2923 switch (expected_coordinates_count) {
2924 case 0:
2925 expected_var_handle_class = GetClassRoot<mirror::StaticFieldVarHandle>();
2926 break;
2927 default:
2928 DCHECK_EQ(expected_coordinates_count, 1u);
2929 expected_var_handle_class = GetClassRoot<mirror::FieldVarHandle>();
2930 break;
2931 }
2932 ObjPtr<mirror::Object> var_handle_object = field->GetObject(declaring_class);
2933 if (var_handle_object == nullptr || var_handle_object->GetClass() != expected_var_handle_class) {
2934 return false;
2935 }
2936 ObjPtr<mirror::VarHandle> var_handle = ObjPtr<mirror::VarHandle>::DownCast(var_handle_object);
2937
2938 // Check access mode.
2939 mirror::VarHandle::AccessMode access_mode =
2940 mirror::VarHandle::GetAccessModeByIntrinsic(invoke->GetIntrinsic());
2941 if (!var_handle->IsAccessModeSupported(access_mode)) {
2942 return false;
2943 }
2944
2945 // Check argument types.
2946 ObjPtr<mirror::Class> var_type = var_handle->GetVarType();
2947 mirror::VarHandle::AccessModeTemplate access_mode_template =
2948 mirror::VarHandle::GetAccessModeTemplate(access_mode);
2949 // Note: The data type of input arguments does not need to match the type from shorty
2950 // due to implicit conversions or avoiding unnecessary conversions before narrow stores.
2951 DataType::Type type = (access_mode_template == mirror::VarHandle::AccessModeTemplate::kGet)
2952 ? invoke->GetType()
2953 : GetDataTypeFromShorty(invoke, invoke->GetNumberOfArguments() - 1u);
2954 if (type != DataTypeFromPrimitive(var_type->GetPrimitiveType())) {
2955 return false;
2956 }
2957 if (type == DataType::Type::kReference) {
2958 uint32_t arguments_start = /* VarHandle object */ 1u + expected_coordinates_count;
2959 uint32_t number_of_arguments = invoke->GetNumberOfArguments();
2960 for (size_t arg_index = arguments_start; arg_index != number_of_arguments; ++arg_index) {
2961 HInstruction* arg = invoke->InputAt(arg_index);
2962 DCHECK_EQ(arg->GetType(), DataType::Type::kReference);
2963 if (!arg->IsNullConstant()) {
2964 ReferenceTypeInfo arg_type_info = arg->GetReferenceTypeInfo();
2965 if (!arg_type_info.IsValid() ||
2966 !var_type->IsAssignableFrom(arg_type_info.GetTypeHandle().Get())) {
2967 return false;
2968 }
2969 }
2970 }
2971 }
2972
2973 // Check the first coordinate.
2974 if (expected_coordinates_count != 0u) {
2975 ObjPtr<mirror::Class> coordinate0_type = var_handle->GetCoordinateType0();
2976 DCHECK(coordinate0_type != nullptr);
2977 ReferenceTypeInfo object_type_info = invoke->InputAt(1)->GetReferenceTypeInfo();
2978 if (!object_type_info.IsValid() ||
2979 !coordinate0_type->IsAssignableFrom(object_type_info.GetTypeHandle().Get())) {
2980 return false;
2981 }
2982 }
2983
2984 // All required checks passed.
2985 return true;
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002986}
2987
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002988void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002989 switch (instruction->GetIntrinsic()) {
2990 case Intrinsics::kStringEquals:
2991 SimplifyStringEquals(instruction);
2992 break;
2993 case Intrinsics::kSystemArrayCopy:
2994 SimplifySystemArrayCopy(instruction);
2995 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002996 case Intrinsics::kFloatFloatToIntBits:
2997 case Intrinsics::kDoubleDoubleToLongBits:
2998 SimplifyFP2Int(instruction);
2999 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01003000 case Intrinsics::kStringCharAt:
Vladimir Marko5f846072020-04-09 13:20:11 +01003001 // Instruction builder creates intermediate representation directly
3002 // but the inliner can sharpen CharSequence.charAt() to String.charAt().
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01003003 SimplifyStringCharAt(instruction);
3004 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01003005 case Intrinsics::kStringLength:
Vladimir Marko5f846072020-04-09 13:20:11 +01003006 // Instruction builder creates intermediate representation directly
3007 // but the inliner can sharpen CharSequence.length() to String.length().
3008 SimplifyStringLength(instruction);
Vladimir Markodce016e2016-04-28 13:10:02 +01003009 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00003010 case Intrinsics::kStringIndexOf:
3011 case Intrinsics::kStringIndexOfAfter:
3012 SimplifyStringIndexOf(instruction);
3013 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08003014 case Intrinsics::kStringStringIndexOf:
3015 case Intrinsics::kStringStringIndexOfAfter:
3016 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
3017 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08003018 case Intrinsics::kStringBufferAppend:
Vladimir Markod4561172017-10-30 17:48:25 +00003019 case Intrinsics::kStringBuilderAppendObject:
3020 case Intrinsics::kStringBuilderAppendString:
3021 case Intrinsics::kStringBuilderAppendCharSequence:
3022 case Intrinsics::kStringBuilderAppendCharArray:
3023 case Intrinsics::kStringBuilderAppendBoolean:
3024 case Intrinsics::kStringBuilderAppendChar:
3025 case Intrinsics::kStringBuilderAppendInt:
3026 case Intrinsics::kStringBuilderAppendLong:
3027 case Intrinsics::kStringBuilderAppendFloat:
3028 case Intrinsics::kStringBuilderAppendDouble:
Aart Bik71bf7b42016-11-16 10:17:46 -08003029 SimplifyReturnThis(instruction);
3030 break;
3031 case Intrinsics::kStringBufferToString:
3032 case Intrinsics::kStringBuilderToString:
3033 SimplifyAllocationIntrinsic(instruction);
3034 break;
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00003035 case Intrinsics::kVarHandleCompareAndExchange:
3036 case Intrinsics::kVarHandleCompareAndExchangeAcquire:
3037 case Intrinsics::kVarHandleCompareAndExchangeRelease:
3038 case Intrinsics::kVarHandleCompareAndSet:
3039 case Intrinsics::kVarHandleGet:
3040 case Intrinsics::kVarHandleGetAcquire:
3041 case Intrinsics::kVarHandleGetAndAdd:
3042 case Intrinsics::kVarHandleGetAndAddAcquire:
3043 case Intrinsics::kVarHandleGetAndAddRelease:
3044 case Intrinsics::kVarHandleGetAndBitwiseAnd:
3045 case Intrinsics::kVarHandleGetAndBitwiseAndAcquire:
3046 case Intrinsics::kVarHandleGetAndBitwiseAndRelease:
3047 case Intrinsics::kVarHandleGetAndBitwiseOr:
3048 case Intrinsics::kVarHandleGetAndBitwiseOrAcquire:
3049 case Intrinsics::kVarHandleGetAndBitwiseOrRelease:
3050 case Intrinsics::kVarHandleGetAndBitwiseXor:
3051 case Intrinsics::kVarHandleGetAndBitwiseXorAcquire:
3052 case Intrinsics::kVarHandleGetAndBitwiseXorRelease:
3053 case Intrinsics::kVarHandleGetAndSet:
3054 case Intrinsics::kVarHandleGetAndSetAcquire:
3055 case Intrinsics::kVarHandleGetAndSetRelease:
3056 case Intrinsics::kVarHandleGetOpaque:
3057 case Intrinsics::kVarHandleGetVolatile:
3058 case Intrinsics::kVarHandleSet:
3059 case Intrinsics::kVarHandleSetOpaque:
3060 case Intrinsics::kVarHandleSetRelease:
3061 case Intrinsics::kVarHandleSetVolatile:
3062 case Intrinsics::kVarHandleWeakCompareAndSet:
3063 case Intrinsics::kVarHandleWeakCompareAndSetAcquire:
3064 case Intrinsics::kVarHandleWeakCompareAndSetPlain:
3065 case Intrinsics::kVarHandleWeakCompareAndSetRelease:
3066 SimplifyVarHandleIntrinsic(instruction);
3067 break;
Vladimir Marko5f846072020-04-09 13:20:11 +01003068 case Intrinsics::kIntegerRotateRight:
3069 case Intrinsics::kLongRotateRight:
3070 case Intrinsics::kIntegerRotateLeft:
3071 case Intrinsics::kLongRotateLeft:
3072 case Intrinsics::kIntegerCompare:
3073 case Intrinsics::kLongCompare:
3074 case Intrinsics::kIntegerSignum:
3075 case Intrinsics::kLongSignum:
3076 case Intrinsics::kFloatIsNaN:
3077 case Intrinsics::kDoubleIsNaN:
3078 case Intrinsics::kStringIsEmpty:
Aart Bik11932592016-03-08 12:42:25 -08003079 case Intrinsics::kUnsafeLoadFence:
Aart Bik11932592016-03-08 12:42:25 -08003080 case Intrinsics::kUnsafeStoreFence:
Aart Bik11932592016-03-08 12:42:25 -08003081 case Intrinsics::kUnsafeFullFence:
Sorin Basca2f01e8e2021-06-18 06:44:07 +00003082 case Intrinsics::kJdkUnsafeLoadFence:
3083 case Intrinsics::kJdkUnsafeStoreFence:
3084 case Intrinsics::kJdkUnsafeFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003085 case Intrinsics::kVarHandleFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003086 case Intrinsics::kVarHandleAcquireFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003087 case Intrinsics::kVarHandleReleaseFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003088 case Intrinsics::kVarHandleLoadLoadFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003089 case Intrinsics::kVarHandleStoreStoreFence:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003090 case Intrinsics::kMathMinIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003091 case Intrinsics::kMathMinLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003092 case Intrinsics::kMathMinFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003093 case Intrinsics::kMathMinDoubleDouble:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003094 case Intrinsics::kMathMaxIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003095 case Intrinsics::kMathMaxLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003096 case Intrinsics::kMathMaxFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003097 case Intrinsics::kMathMaxDoubleDouble:
Aart Bik3dad3412018-02-28 12:01:46 -08003098 case Intrinsics::kMathAbsInt:
Aart Bik3dad3412018-02-28 12:01:46 -08003099 case Intrinsics::kMathAbsLong:
Aart Bik3dad3412018-02-28 12:01:46 -08003100 case Intrinsics::kMathAbsFloat:
Aart Bik3dad3412018-02-28 12:01:46 -08003101 case Intrinsics::kMathAbsDouble:
Vladimir Marko5f846072020-04-09 13:20:11 +01003102 // These are replaced by intermediate representation in the instruction builder.
3103 LOG(FATAL) << "Unexpected " << static_cast<Intrinsics>(instruction->GetIntrinsic());
3104 UNREACHABLE();
Aart Bik2a6aad92016-02-25 11:32:32 -08003105 default:
3106 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003107 }
3108}
3109
Aart Bikbb245d12015-10-19 11:05:03 -07003110void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
3111 HInstruction* cond = deoptimize->InputAt(0);
3112 if (cond->IsConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +00003113 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07003114 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00003115 if (deoptimize->GuardsAnInput()) {
3116 deoptimize->ReplaceWith(deoptimize->GuardedInput());
3117 }
Aart Bikbb245d12015-10-19 11:05:03 -07003118 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
3119 } else {
3120 // Always deopt.
3121 }
3122 }
3123}
3124
Anton Kirilove14dc862016-05-13 17:56:15 +01003125// Replace code looking like
3126// OP y, x, const1
3127// OP z, y, const2
3128// with
3129// OP z, x, const3
3130// where OP is both an associative and a commutative operation.
3131bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
3132 HBinaryOperation* instruction) {
3133 DCHECK(instruction->IsCommutative());
3134
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003135 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003136 return false;
3137 }
3138
3139 HInstruction* left = instruction->GetLeft();
3140 HInstruction* right = instruction->GetRight();
3141 // Variable names as described above.
3142 HConstant* const2;
3143 HBinaryOperation* y;
3144
Vladimir Marko0dcccd82018-05-04 13:32:25 +01003145 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Vladimir Markocde64972023-04-25 16:40:06 +00003146 const2 = right->AsConstant();
3147 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01003148 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Vladimir Markocde64972023-04-25 16:40:06 +00003149 const2 = left->AsConstant();
3150 y = right->AsBinaryOperation();
Anton Kirilove14dc862016-05-13 17:56:15 +01003151 } else {
3152 // The node does not match the pattern.
3153 return false;
3154 }
3155
3156 // If `y` has more than one use, we do not perform the optimization
3157 // because it might increase code size (e.g. if the new constant is
3158 // no longer encodable as an immediate operand in the target ISA).
3159 if (!y->HasOnlyOneNonEnvironmentUse()) {
3160 return false;
3161 }
3162
3163 // GetConstantRight() can return both left and right constants
3164 // for commutative operations.
3165 HConstant* const1 = y->GetConstantRight();
3166 if (const1 == nullptr) {
3167 return false;
3168 }
3169
3170 instruction->ReplaceInput(const1, 0);
3171 instruction->ReplaceInput(const2, 1);
3172 HConstant* const3 = instruction->TryStaticEvaluation();
3173 DCHECK(const3 != nullptr);
3174 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
3175 instruction->ReplaceInput(const3, 1);
3176 RecordSimplification();
3177 return true;
3178}
3179
3180static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
Vladimir Markocde64972023-04-25 16:40:06 +00003181 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
Anton Kirilove14dc862016-05-13 17:56:15 +01003182}
3183
3184// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003185static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003186 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003187 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003188 return HAdd::Compute<int32_t>(x, y);
3189 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003190 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01003191 return HAdd::Compute<int64_t>(x, y);
3192 }
3193}
3194
3195// Helper function that handles the child classes of HConstant
3196// and returns an integer with the appropriate sign.
3197static int64_t GetValue(HConstant* constant, bool is_negated) {
3198 int64_t ret = Int64FromConstant(constant);
3199 return is_negated ? -ret : ret;
3200}
3201
3202// Replace code looking like
3203// OP1 y, x, const1
3204// OP2 z, y, const2
3205// with
3206// OP3 z, x, const3
3207// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
3208bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
3209 HBinaryOperation* instruction) {
3210 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
3211
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003212 DataType::Type type = instruction->GetType();
3213 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003214 return false;
3215 }
3216
3217 HInstruction* left = instruction->GetLeft();
3218 HInstruction* right = instruction->GetRight();
3219 // Variable names as described above.
Vladimir Markocde64972023-04-25 16:40:06 +00003220 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstantOrNull();
Anton Kirilove14dc862016-05-13 17:56:15 +01003221 if (const2 == nullptr) {
3222 return false;
3223 }
3224
3225 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
Vladimir Markocde64972023-04-25 16:40:06 +00003226 ? left->AsBinaryOperation()
Anton Kirilove14dc862016-05-13 17:56:15 +01003227 : AsAddOrSub(right);
3228 // If y has more than one use, we do not perform the optimization because
3229 // it might increase code size (e.g. if the new constant is no longer
3230 // encodable as an immediate operand in the target ISA).
3231 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
3232 return false;
3233 }
3234
3235 left = y->GetLeft();
Vladimir Markocde64972023-04-25 16:40:06 +00003236 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstantOrNull();
Anton Kirilove14dc862016-05-13 17:56:15 +01003237 if (const1 == nullptr) {
3238 return false;
3239 }
3240
3241 HInstruction* x = (const1 == left) ? y->GetRight() : left;
3242 // If both inputs are constants, let the constant folding pass deal with it.
3243 if (x->IsConstant()) {
3244 return false;
3245 }
3246
3247 bool is_const2_negated = (const2 == right) && instruction->IsSub();
3248 int64_t const2_val = GetValue(const2, is_const2_negated);
3249 bool is_y_negated = (y == right) && instruction->IsSub();
3250 right = y->GetRight();
3251 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
3252 int64_t const1_val = GetValue(const1, is_const1_negated);
3253 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
3254 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
3255 HBasicBlock* block = instruction->GetBlock();
3256 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003257 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01003258 HInstruction* z;
3259
3260 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003261 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01003262 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003263 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01003264 }
3265
3266 block->ReplaceAndRemoveInstructionWith(instruction, z);
3267 RecordSimplification();
3268 return true;
3269}
3270
Lena Djokicbc5460b2017-07-20 16:07:36 +02003271void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
3272 if (TryCombineVecMultiplyAccumulate(instruction)) {
3273 RecordSimplification();
3274 }
3275}
3276
Nicolas Geoffray3c049742014-09-24 18:10:46 +01003277} // namespace art