1 //===- StraightLineStrengthReduce.cpp - -----------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements straight-line strength reduction (SLSR). Unlike loop
10 // strength reduction, this algorithm is designed to reduce arithmetic
11 // redundancy in straight-line code instead of loops. It has proven to be
12 // effective in simplifying arithmetic statements derived from an unrolled loop.
13 // It can also simplify the logic of SeparateConstOffsetFromGEP.
15 // There are many optimizations we can perform in the domain of SLSR. This file
16 // for now contains only an initial step. Specifically, we look for strength
17 // reduction candidates in the following forms:
20 // Form 2: (B + i) * S
23 // where S is an integer variable, and i is a constant integer. If we found two
24 // candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
25 // in a simpler way with respect to S1. For example,
28 // S2: Y = B + i' * S => X + (i' - i) * S
30 // S1: X = (B + i) * S
31 // S2: Y = (B + i') * S => X + (i' - i) * S
34 // S2: Y = &B[i' * S] => &X[(i' - i) * S]
36 // Note: (i' - i) * S is folded to the extent possible.
38 // This rewriting is in general a good idea. The code patterns we focus on
39 // usually come from loop unrolling, so (i' - i) * S is likely the same
40 // across iterations and can be reused. When that happens, the optimized form
41 // takes only one add starting from the second iteration.
43 // When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
44 // multiple bases, we choose to rewrite S2 with respect to its "immediate"
45 // basis, the basis that is the closest ancestor in the dominator tree.
49 // - Floating point arithmetics when fast math is enabled.
51 // - SLSR may decrease ILP at the architecture level. Targets that are very
52 // sensitive to ILP may want to disable it. Having SLSR to consider ILP is
53 // left as future work.
55 // - When (i' - i) is constant but i and i' are not, we could still perform
58 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
59 #include "llvm/ADT/APInt.h"
60 #include "llvm/ADT/DepthFirstIterator.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/TargetTransformInfo.h"
64 #include "llvm/Analysis/ValueTracking.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/GetElementPtrTypeIterator.h"
70 #include "llvm/IR/IRBuilder.h"
71 #include "llvm/IR/Instruction.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/Module.h"
74 #include "llvm/IR/Operator.h"
75 #include "llvm/IR/PatternMatch.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/Local.h"
91 using namespace PatternMatch
;
93 static const unsigned UnknownAddressSpace
=
94 std::numeric_limits
<unsigned>::max();
98 class StraightLineStrengthReduceLegacyPass
: public FunctionPass
{
99 const DataLayout
*DL
= nullptr;
104 StraightLineStrengthReduceLegacyPass() : FunctionPass(ID
) {
105 initializeStraightLineStrengthReduceLegacyPassPass(
106 *PassRegistry::getPassRegistry());
109 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
110 AU
.addRequired
<DominatorTreeWrapperPass
>();
111 AU
.addRequired
<ScalarEvolutionWrapperPass
>();
112 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
113 // We do not modify the shape of the CFG.
114 AU
.setPreservesCFG();
117 bool doInitialization(Module
&M
) override
{
118 DL
= &M
.getDataLayout();
122 bool runOnFunction(Function
&F
) override
;
125 class StraightLineStrengthReduce
{
127 StraightLineStrengthReduce(const DataLayout
*DL
, DominatorTree
*DT
,
128 ScalarEvolution
*SE
, TargetTransformInfo
*TTI
)
129 : DL(DL
), DT(DT
), SE(SE
), TTI(TTI
) {}
131 // SLSR candidate. Such a candidate must be in one of the forms described in
132 // the header comments.
135 Invalid
, // reserved for the default constructor
138 GEP
, // &B[..][i * S][..]
141 Candidate() = default;
142 Candidate(Kind CT
, const SCEV
*B
, ConstantInt
*Idx
, Value
*S
,
144 : CandidateKind(CT
), Base(B
), Index(Idx
), Stride(S
), Ins(I
) {}
146 Kind CandidateKind
= Invalid
;
148 const SCEV
*Base
= nullptr;
150 // Note that Index and Stride of a GEP candidate do not necessarily have the
151 // same integer type. In that case, during rewriting, Stride will be
152 // sign-extended or truncated to Index's type.
153 ConstantInt
*Index
= nullptr;
155 Value
*Stride
= nullptr;
157 // The instruction this candidate corresponds to. It helps us to rewrite a
158 // candidate with respect to its immediate basis. Note that one instruction
159 // can correspond to multiple candidates depending on how you associate the
160 // expression. For instance,
166 // <Base: a, Index: 1, Stride: b + 2>
170 // <Base: b, Index: 2, Stride: a + 1>
171 Instruction
*Ins
= nullptr;
173 // Points to the immediate basis of this candidate, or nullptr if we cannot
174 // find any basis for this candidate.
175 Candidate
*Basis
= nullptr;
178 bool runOnFunction(Function
&F
);
181 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
182 // share the same base and stride.
183 bool isBasisFor(const Candidate
&Basis
, const Candidate
&C
);
185 // Returns whether the candidate can be folded into an addressing mode.
186 bool isFoldable(const Candidate
&C
, TargetTransformInfo
*TTI
,
187 const DataLayout
*DL
);
189 // Returns true if C is already in a simplest form and not worth being
191 bool isSimplestForm(const Candidate
&C
);
193 // Checks whether I is in a candidate form. If so, adds all the matching forms
194 // to Candidates, and tries to find the immediate basis for each of them.
195 void allocateCandidatesAndFindBasis(Instruction
*I
);
197 // Allocate candidates and find bases for Add instructions.
198 void allocateCandidatesAndFindBasisForAdd(Instruction
*I
);
200 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
202 void allocateCandidatesAndFindBasisForAdd(Value
*LHS
, Value
*RHS
,
204 // Allocate candidates and find bases for Mul instructions.
205 void allocateCandidatesAndFindBasisForMul(Instruction
*I
);
207 // Splits LHS into Base + Index and, if succeeds, calls
208 // allocateCandidatesAndFindBasis.
209 void allocateCandidatesAndFindBasisForMul(Value
*LHS
, Value
*RHS
,
212 // Allocate candidates and find bases for GetElementPtr instructions.
213 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst
*GEP
);
215 // A helper function that scales Idx with ElementSize before invoking
216 // allocateCandidatesAndFindBasis.
217 void allocateCandidatesAndFindBasisForGEP(const SCEV
*B
, ConstantInt
*Idx
,
218 Value
*S
, uint64_t ElementSize
,
221 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
223 void allocateCandidatesAndFindBasis(Candidate::Kind CT
, const SCEV
*B
,
224 ConstantInt
*Idx
, Value
*S
,
227 // Rewrites candidate C with respect to Basis.
228 void rewriteCandidateWithBasis(const Candidate
&C
, const Candidate
&Basis
);
230 // A helper function that factors ArrayIdx to a product of a stride and a
231 // constant index, and invokes allocateCandidatesAndFindBasis with the
233 void factorArrayIndex(Value
*ArrayIdx
, const SCEV
*Base
, uint64_t ElementSize
,
234 GetElementPtrInst
*GEP
);
236 // Emit code that computes the "bump" from Basis to C.
237 static Value
*emitBump(const Candidate
&Basis
, const Candidate
&C
,
238 IRBuilder
<> &Builder
, const DataLayout
*DL
);
240 const DataLayout
*DL
= nullptr;
241 DominatorTree
*DT
= nullptr;
243 TargetTransformInfo
*TTI
= nullptr;
244 std::list
<Candidate
> Candidates
;
246 // Temporarily holds all instructions that are unlinked (but not deleted) by
247 // rewriteCandidateWithBasis. These instructions will be actually removed
248 // after all rewriting finishes.
249 std::vector
<Instruction
*> UnlinkedInstructions
;
252 } // end anonymous namespace
254 char StraightLineStrengthReduceLegacyPass::ID
= 0;
256 INITIALIZE_PASS_BEGIN(StraightLineStrengthReduceLegacyPass
, "slsr",
257 "Straight line strength reduction", false, false)
258 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
259 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass
)
260 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
261 INITIALIZE_PASS_END(StraightLineStrengthReduceLegacyPass
, "slsr",
262 "Straight line strength reduction", false, false)
264 FunctionPass
*llvm::createStraightLineStrengthReducePass() {
265 return new StraightLineStrengthReduceLegacyPass();
268 bool StraightLineStrengthReduce::isBasisFor(const Candidate
&Basis
,
269 const Candidate
&C
) {
270 return (Basis
.Ins
!= C
.Ins
&& // skip the same instruction
271 // They must have the same type too. Basis.Base == C.Base doesn't
272 // guarantee their types are the same (PR23975).
273 Basis
.Ins
->getType() == C
.Ins
->getType() &&
274 // Basis must dominate C in order to rewrite C with respect to Basis.
275 DT
->dominates(Basis
.Ins
->getParent(), C
.Ins
->getParent()) &&
276 // They share the same base, stride, and candidate kind.
277 Basis
.Base
== C
.Base
&& Basis
.Stride
== C
.Stride
&&
278 Basis
.CandidateKind
== C
.CandidateKind
);
281 static bool isGEPFoldable(GetElementPtrInst
*GEP
,
282 const TargetTransformInfo
*TTI
) {
283 SmallVector
<const Value
*, 4> Indices(GEP
->indices());
284 return TTI
->getGEPCost(GEP
->getSourceElementType(), GEP
->getPointerOperand(),
285 Indices
) == TargetTransformInfo::TCC_Free
;
288 // Returns whether (Base + Index * Stride) can be folded to an addressing mode.
289 static bool isAddFoldable(const SCEV
*Base
, ConstantInt
*Index
, Value
*Stride
,
290 TargetTransformInfo
*TTI
) {
291 // Index->getSExtValue() may crash if Index is wider than 64-bit.
292 return Index
->getBitWidth() <= 64 &&
293 TTI
->isLegalAddressingMode(Base
->getType(), nullptr, 0, true,
294 Index
->getSExtValue(), UnknownAddressSpace
);
297 bool StraightLineStrengthReduce::isFoldable(const Candidate
&C
,
298 TargetTransformInfo
*TTI
,
299 const DataLayout
*DL
) {
300 if (C
.CandidateKind
== Candidate::Add
)
301 return isAddFoldable(C
.Base
, C
.Index
, C
.Stride
, TTI
);
302 if (C
.CandidateKind
== Candidate::GEP
)
303 return isGEPFoldable(cast
<GetElementPtrInst
>(C
.Ins
), TTI
);
307 // Returns true if GEP has zero or one non-zero index.
308 static bool hasOnlyOneNonZeroIndex(GetElementPtrInst
*GEP
) {
309 unsigned NumNonZeroIndices
= 0;
310 for (Use
&Idx
: GEP
->indices()) {
311 ConstantInt
*ConstIdx
= dyn_cast
<ConstantInt
>(Idx
);
312 if (ConstIdx
== nullptr || !ConstIdx
->isZero())
315 return NumNonZeroIndices
<= 1;
318 bool StraightLineStrengthReduce::isSimplestForm(const Candidate
&C
) {
319 if (C
.CandidateKind
== Candidate::Add
) {
320 // B + 1 * S or B + (-1) * S
321 return C
.Index
->isOne() || C
.Index
->isMinusOne();
323 if (C
.CandidateKind
== Candidate::Mul
) {
325 return C
.Index
->isZero();
327 if (C
.CandidateKind
== Candidate::GEP
) {
328 // (char*)B + S or (char*)B - S
329 return ((C
.Index
->isOne() || C
.Index
->isMinusOne()) &&
330 hasOnlyOneNonZeroIndex(cast
<GetElementPtrInst
>(C
.Ins
)));
335 // TODO: We currently implement an algorithm whose time complexity is linear in
336 // the number of existing candidates. However, we could do better by using
337 // ScopedHashTable. Specifically, while traversing the dominator tree, we could
338 // maintain all the candidates that dominate the basic block being traversed in
339 // a ScopedHashTable. This hash table is indexed by the base and the stride of
340 // a candidate. Therefore, finding the immediate basis of a candidate boils down
341 // to one hash-table look up.
342 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
343 Candidate::Kind CT
, const SCEV
*B
, ConstantInt
*Idx
, Value
*S
,
345 Candidate
C(CT
, B
, Idx
, S
, I
);
346 // SLSR can complicate an instruction in two cases:
348 // 1. If we can fold I into an addressing mode, computing I is likely free or
349 // takes only one instruction.
351 // 2. I is already in a simplest form. For example, when
354 // rewriting Y to X - 7 * S is probably a bad idea.
356 // In the above cases, we still add I to the candidate list so that I can be
357 // the basis of other candidates, but we leave I's basis blank so that I
358 // won't be rewritten.
359 if (!isFoldable(C
, TTI
, DL
) && !isSimplestForm(C
)) {
360 // Try to compute the immediate basis of C.
361 unsigned NumIterations
= 0;
362 // Limit the scan radius to avoid running in quadratice time.
363 static const unsigned MaxNumIterations
= 50;
364 for (auto Basis
= Candidates
.rbegin();
365 Basis
!= Candidates
.rend() && NumIterations
< MaxNumIterations
;
366 ++Basis
, ++NumIterations
) {
367 if (isBasisFor(*Basis
, C
)) {
373 // Regardless of whether we find a basis for C, we need to push C to the
374 // candidate list so that it can be the basis of other candidates.
375 Candidates
.push_back(C
);
378 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
380 switch (I
->getOpcode()) {
381 case Instruction::Add
:
382 allocateCandidatesAndFindBasisForAdd(I
);
384 case Instruction::Mul
:
385 allocateCandidatesAndFindBasisForMul(I
);
387 case Instruction::GetElementPtr
:
388 allocateCandidatesAndFindBasisForGEP(cast
<GetElementPtrInst
>(I
));
393 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
395 // Try matching B + i * S.
396 if (!isa
<IntegerType
>(I
->getType()))
399 assert(I
->getNumOperands() == 2 && "isn't I an add?");
400 Value
*LHS
= I
->getOperand(0), *RHS
= I
->getOperand(1);
401 allocateCandidatesAndFindBasisForAdd(LHS
, RHS
, I
);
403 allocateCandidatesAndFindBasisForAdd(RHS
, LHS
, I
);
406 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
407 Value
*LHS
, Value
*RHS
, Instruction
*I
) {
409 ConstantInt
*Idx
= nullptr;
410 if (match(RHS
, m_Mul(m_Value(S
), m_ConstantInt(Idx
)))) {
411 // I = LHS + RHS = LHS + Idx * S
412 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), Idx
, S
, I
);
413 } else if (match(RHS
, m_Shl(m_Value(S
), m_ConstantInt(Idx
)))) {
414 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
415 APInt
One(Idx
->getBitWidth(), 1);
416 Idx
= ConstantInt::get(Idx
->getContext(), One
<< Idx
->getValue());
417 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), Idx
, S
, I
);
419 // At least, I = LHS + 1 * RHS
420 ConstantInt
*One
= ConstantInt::get(cast
<IntegerType
>(I
->getType()), 1);
421 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), One
, RHS
,
426 // Returns true if A matches B + C where C is constant.
427 static bool matchesAdd(Value
*A
, Value
*&B
, ConstantInt
*&C
) {
428 return (match(A
, m_Add(m_Value(B
), m_ConstantInt(C
))) ||
429 match(A
, m_Add(m_ConstantInt(C
), m_Value(B
))));
432 // Returns true if A matches B | C where C is constant.
433 static bool matchesOr(Value
*A
, Value
*&B
, ConstantInt
*&C
) {
434 return (match(A
, m_Or(m_Value(B
), m_ConstantInt(C
))) ||
435 match(A
, m_Or(m_ConstantInt(C
), m_Value(B
))));
438 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
439 Value
*LHS
, Value
*RHS
, Instruction
*I
) {
441 ConstantInt
*Idx
= nullptr;
442 if (matchesAdd(LHS
, B
, Idx
)) {
443 // If LHS is in the form of "Base + Index", then I is in the form of
444 // "(Base + Index) * RHS".
445 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(B
), Idx
, RHS
, I
);
446 } else if (matchesOr(LHS
, B
, Idx
) && haveNoCommonBitsSet(B
, Idx
, *DL
)) {
447 // If LHS is in the form of "Base | Index" and Base and Index have no common
449 // Base | Index = Base + Index
450 // and I is thus in the form of "(Base + Index) * RHS".
451 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(B
), Idx
, RHS
, I
);
453 // Otherwise, at least try the form (LHS + 0) * RHS.
454 ConstantInt
*Zero
= ConstantInt::get(cast
<IntegerType
>(I
->getType()), 0);
455 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(LHS
), Zero
, RHS
,
460 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
462 // Try matching (B + i) * S.
463 // TODO: we could extend SLSR to float and vector types.
464 if (!isa
<IntegerType
>(I
->getType()))
467 assert(I
->getNumOperands() == 2 && "isn't I a mul?");
468 Value
*LHS
= I
->getOperand(0), *RHS
= I
->getOperand(1);
469 allocateCandidatesAndFindBasisForMul(LHS
, RHS
, I
);
471 // Symmetrically, try to split RHS to Base + Index.
472 allocateCandidatesAndFindBasisForMul(RHS
, LHS
, I
);
476 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
477 const SCEV
*B
, ConstantInt
*Idx
, Value
*S
, uint64_t ElementSize
,
479 // I = B + sext(Idx *nsw S) * ElementSize
480 // = B + (sext(Idx) * sext(S)) * ElementSize
481 // = B + (sext(Idx) * ElementSize) * sext(S)
482 // Casting to IntegerType is safe because we skipped vector GEPs.
483 IntegerType
*PtrIdxTy
= cast
<IntegerType
>(DL
->getIndexType(I
->getType()));
484 ConstantInt
*ScaledIdx
= ConstantInt::get(
485 PtrIdxTy
, Idx
->getSExtValue() * (int64_t)ElementSize
, true);
486 allocateCandidatesAndFindBasis(Candidate::GEP
, B
, ScaledIdx
, S
, I
);
489 void StraightLineStrengthReduce::factorArrayIndex(Value
*ArrayIdx
,
491 uint64_t ElementSize
,
492 GetElementPtrInst
*GEP
) {
493 // At least, ArrayIdx = ArrayIdx *nsw 1.
494 allocateCandidatesAndFindBasisForGEP(
495 Base
, ConstantInt::get(cast
<IntegerType
>(ArrayIdx
->getType()), 1),
496 ArrayIdx
, ElementSize
, GEP
);
497 Value
*LHS
= nullptr;
498 ConstantInt
*RHS
= nullptr;
499 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
500 // itself. This would allow us to handle the shl case for free. However,
501 // matching SCEVs has two issues:
503 // 1. this would complicate rewriting because the rewriting procedure
504 // would have to translate SCEVs back to IR instructions. This translation
505 // is difficult when LHS is further evaluated to a composite SCEV.
507 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
508 // to strip nsw/nuw flags which are critical for SLSR to trace into
509 // sext'ed multiplication.
510 if (match(ArrayIdx
, m_NSWMul(m_Value(LHS
), m_ConstantInt(RHS
)))) {
511 // SLSR is currently unsafe if i * S may overflow.
512 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
513 allocateCandidatesAndFindBasisForGEP(Base
, RHS
, LHS
, ElementSize
, GEP
);
514 } else if (match(ArrayIdx
, m_NSWShl(m_Value(LHS
), m_ConstantInt(RHS
)))) {
515 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
516 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
517 APInt
One(RHS
->getBitWidth(), 1);
518 ConstantInt
*PowerOf2
=
519 ConstantInt::get(RHS
->getContext(), One
<< RHS
->getValue());
520 allocateCandidatesAndFindBasisForGEP(Base
, PowerOf2
, LHS
, ElementSize
, GEP
);
524 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
525 GetElementPtrInst
*GEP
) {
526 // TODO: handle vector GEPs
527 if (GEP
->getType()->isVectorTy())
530 SmallVector
<const SCEV
*, 4> IndexExprs
;
531 for (Use
&Idx
: GEP
->indices())
532 IndexExprs
.push_back(SE
->getSCEV(Idx
));
534 gep_type_iterator GTI
= gep_type_begin(GEP
);
535 for (unsigned I
= 1, E
= GEP
->getNumOperands(); I
!= E
; ++I
, ++GTI
) {
539 const SCEV
*OrigIndexExpr
= IndexExprs
[I
- 1];
540 IndexExprs
[I
- 1] = SE
->getZero(OrigIndexExpr
->getType());
542 // The base of this candidate is GEP's base plus the offsets of all
543 // indices except this current one.
544 const SCEV
*BaseExpr
= SE
->getGEPExpr(cast
<GEPOperator
>(GEP
), IndexExprs
);
545 Value
*ArrayIdx
= GEP
->getOperand(I
);
546 uint64_t ElementSize
= GTI
.getSequentialElementStride(*DL
);
547 if (ArrayIdx
->getType()->getIntegerBitWidth() <=
548 DL
->getIndexSizeInBits(GEP
->getAddressSpace())) {
549 // Skip factoring if ArrayIdx is wider than the index size, because
550 // ArrayIdx is implicitly truncated to the index size.
551 factorArrayIndex(ArrayIdx
, BaseExpr
, ElementSize
, GEP
);
553 // When ArrayIdx is the sext of a value, we try to factor that value as
554 // well. Handling this case is important because array indices are
555 // typically sign-extended to the pointer index size.
556 Value
*TruncatedArrayIdx
= nullptr;
557 if (match(ArrayIdx
, m_SExt(m_Value(TruncatedArrayIdx
))) &&
558 TruncatedArrayIdx
->getType()->getIntegerBitWidth() <=
559 DL
->getIndexSizeInBits(GEP
->getAddressSpace())) {
560 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
561 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
562 factorArrayIndex(TruncatedArrayIdx
, BaseExpr
, ElementSize
, GEP
);
565 IndexExprs
[I
- 1] = OrigIndexExpr
;
569 // A helper function that unifies the bitwidth of A and B.
570 static void unifyBitWidth(APInt
&A
, APInt
&B
) {
571 if (A
.getBitWidth() < B
.getBitWidth())
572 A
= A
.sext(B
.getBitWidth());
573 else if (A
.getBitWidth() > B
.getBitWidth())
574 B
= B
.sext(A
.getBitWidth());
577 Value
*StraightLineStrengthReduce::emitBump(const Candidate
&Basis
,
579 IRBuilder
<> &Builder
,
580 const DataLayout
*DL
) {
581 APInt Idx
= C
.Index
->getValue(), BasisIdx
= Basis
.Index
->getValue();
582 unifyBitWidth(Idx
, BasisIdx
);
583 APInt IndexOffset
= Idx
- BasisIdx
;
585 // Compute Bump = C - Basis = (i' - i) * S.
586 // Common case 1: if (i' - i) is 1, Bump = S.
587 if (IndexOffset
== 1)
589 // Common case 2: if (i' - i) is -1, Bump = -S.
590 if (IndexOffset
.isAllOnes())
591 return Builder
.CreateNeg(C
.Stride
);
593 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
594 // have different bit widths.
595 IntegerType
*DeltaType
=
596 IntegerType::get(Basis
.Ins
->getContext(), IndexOffset
.getBitWidth());
597 Value
*ExtendedStride
= Builder
.CreateSExtOrTrunc(C
.Stride
, DeltaType
);
598 if (IndexOffset
.isPowerOf2()) {
599 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
600 ConstantInt
*Exponent
= ConstantInt::get(DeltaType
, IndexOffset
.logBase2());
601 return Builder
.CreateShl(ExtendedStride
, Exponent
);
603 if (IndexOffset
.isNegatedPowerOf2()) {
604 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
605 ConstantInt
*Exponent
=
606 ConstantInt::get(DeltaType
, (-IndexOffset
).logBase2());
607 return Builder
.CreateNeg(Builder
.CreateShl(ExtendedStride
, Exponent
));
609 Constant
*Delta
= ConstantInt::get(DeltaType
, IndexOffset
);
610 return Builder
.CreateMul(ExtendedStride
, Delta
);
613 void StraightLineStrengthReduce::rewriteCandidateWithBasis(
614 const Candidate
&C
, const Candidate
&Basis
) {
615 assert(C
.CandidateKind
== Basis
.CandidateKind
&& C
.Base
== Basis
.Base
&&
616 C
.Stride
== Basis
.Stride
);
617 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
618 // basis of a candidate cannot be unlinked before the candidate.
619 assert(Basis
.Ins
->getParent() != nullptr && "the basis is unlinked");
621 // An instruction can correspond to multiple candidates. Therefore, instead of
622 // simply deleting an instruction when we rewrite it, we mark its parent as
623 // nullptr (i.e. unlink it) so that we can skip the candidates whose
624 // instruction is already rewritten.
625 if (!C
.Ins
->getParent())
628 IRBuilder
<> Builder(C
.Ins
);
629 Value
*Bump
= emitBump(Basis
, C
, Builder
, DL
);
630 Value
*Reduced
= nullptr; // equivalent to but weaker than C.Ins
631 switch (C
.CandidateKind
) {
633 case Candidate::Mul
: {
636 if (match(Bump
, m_Neg(m_Value(NegBump
)))) {
637 // If Bump is a neg instruction, emit C = Basis - (-Bump).
638 Reduced
= Builder
.CreateSub(Basis
.Ins
, NegBump
);
639 // We only use the negative argument of Bump, and Bump itself may be
641 RecursivelyDeleteTriviallyDeadInstructions(Bump
);
643 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
644 // usually unsound, e.g.,
646 // X = (-2 +nsw 1) *nsw INT_MAX
647 // Y = (-2 +nsw 3) *nsw INT_MAX
649 // Y = X + 2 * INT_MAX
651 // Neither + and * in the resultant expression are nsw.
652 Reduced
= Builder
.CreateAdd(Basis
.Ins
, Bump
);
656 case Candidate::GEP
: {
657 bool InBounds
= cast
<GetElementPtrInst
>(C
.Ins
)->isInBounds();
658 // C = (char *)Basis + Bump
659 Reduced
= Builder
.CreatePtrAdd(Basis
.Ins
, Bump
, "", InBounds
);
663 llvm_unreachable("C.CandidateKind is invalid");
665 Reduced
->takeName(C
.Ins
);
666 C
.Ins
->replaceAllUsesWith(Reduced
);
667 // Unlink C.Ins so that we can skip other candidates also corresponding to
668 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
669 C
.Ins
->removeFromParent();
670 UnlinkedInstructions
.push_back(C
.Ins
);
673 bool StraightLineStrengthReduceLegacyPass::runOnFunction(Function
&F
) {
677 auto *TTI
= &getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
678 auto *DT
= &getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
679 auto *SE
= &getAnalysis
<ScalarEvolutionWrapperPass
>().getSE();
680 return StraightLineStrengthReduce(DL
, DT
, SE
, TTI
).runOnFunction(F
);
683 bool StraightLineStrengthReduce::runOnFunction(Function
&F
) {
684 // Traverse the dominator tree in the depth-first order. This order makes sure
685 // all bases of a candidate are in Candidates when we process it.
686 for (const auto Node
: depth_first(DT
))
687 for (auto &I
: *(Node
->getBlock()))
688 allocateCandidatesAndFindBasis(&I
);
690 // Rewrite candidates in the reverse depth-first order. This order makes sure
691 // a candidate being rewritten is not a basis for any other candidate.
692 while (!Candidates
.empty()) {
693 const Candidate
&C
= Candidates
.back();
694 if (C
.Basis
!= nullptr) {
695 rewriteCandidateWithBasis(C
, *C
.Basis
);
697 Candidates
.pop_back();
700 // Delete all unlink instructions.
701 for (auto *UnlinkedInst
: UnlinkedInstructions
) {
702 for (unsigned I
= 0, E
= UnlinkedInst
->getNumOperands(); I
!= E
; ++I
) {
703 Value
*Op
= UnlinkedInst
->getOperand(I
);
704 UnlinkedInst
->setOperand(I
, nullptr);
705 RecursivelyDeleteTriviallyDeadInstructions(Op
);
707 UnlinkedInst
->deleteValue();
709 bool Ret
= !UnlinkedInstructions
.empty();
710 UnlinkedInstructions
.clear();
717 StraightLineStrengthReducePass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
718 const DataLayout
*DL
= &F
.getParent()->getDataLayout();
719 auto *DT
= &AM
.getResult
<DominatorTreeAnalysis
>(F
);
720 auto *SE
= &AM
.getResult
<ScalarEvolutionAnalysis
>(F
);
721 auto *TTI
= &AM
.getResult
<TargetIRAnalysis
>(F
);
723 if (!StraightLineStrengthReduce(DL
, DT
, SE
, TTI
).runOnFunction(F
))
724 return PreservedAnalyses::all();
726 PreservedAnalyses PA
;
727 PA
.preserveSet
<CFGAnalyses
>();
728 PA
.preserve
<DominatorTreeAnalysis
>();
729 PA
.preserve
<ScalarEvolutionAnalysis
>();
730 PA
.preserve
<TargetIRAnalysis
>();