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/ADT/APInt.h"
59 #include "llvm/ADT/DepthFirstIterator.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/TargetTransformInfo.h"
63 #include "llvm/Transforms/Utils/Local.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/InstrTypes.h"
72 #include "llvm/IR/Instruction.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/Module.h"
75 #include "llvm/IR/Operator.h"
76 #include "llvm/IR/PatternMatch.h"
77 #include "llvm/IR/Type.h"
78 #include "llvm/IR/Value.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Transforms/Scalar.h"
90 using namespace PatternMatch
;
92 static const unsigned UnknownAddressSpace
=
93 std::numeric_limits
<unsigned>::max();
97 class StraightLineStrengthReduce
: public FunctionPass
{
99 // SLSR candidate. Such a candidate must be in one of the forms described in
100 // the header comments.
103 Invalid
, // reserved for the default constructor
106 GEP
, // &B[..][i * S][..]
109 Candidate() = default;
110 Candidate(Kind CT
, const SCEV
*B
, ConstantInt
*Idx
, Value
*S
,
112 : CandidateKind(CT
), Base(B
), Index(Idx
), Stride(S
), Ins(I
) {}
114 Kind CandidateKind
= Invalid
;
116 const SCEV
*Base
= nullptr;
118 // Note that Index and Stride of a GEP candidate do not necessarily have the
119 // same integer type. In that case, during rewriting, Stride will be
120 // sign-extended or truncated to Index's type.
121 ConstantInt
*Index
= nullptr;
123 Value
*Stride
= nullptr;
125 // The instruction this candidate corresponds to. It helps us to rewrite a
126 // candidate with respect to its immediate basis. Note that one instruction
127 // can correspond to multiple candidates depending on how you associate the
128 // expression. For instance,
134 // <Base: a, Index: 1, Stride: b + 2>
138 // <Base: b, Index: 2, Stride: a + 1>
139 Instruction
*Ins
= nullptr;
141 // Points to the immediate basis of this candidate, or nullptr if we cannot
142 // find any basis for this candidate.
143 Candidate
*Basis
= nullptr;
148 StraightLineStrengthReduce() : FunctionPass(ID
) {
149 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
152 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
153 AU
.addRequired
<DominatorTreeWrapperPass
>();
154 AU
.addRequired
<ScalarEvolutionWrapperPass
>();
155 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
156 // We do not modify the shape of the CFG.
157 AU
.setPreservesCFG();
160 bool doInitialization(Module
&M
) override
{
161 DL
= &M
.getDataLayout();
165 bool runOnFunction(Function
&F
) override
;
168 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
169 // share the same base and stride.
170 bool isBasisFor(const Candidate
&Basis
, const Candidate
&C
);
172 // Returns whether the candidate can be folded into an addressing mode.
173 bool isFoldable(const Candidate
&C
, TargetTransformInfo
*TTI
,
174 const DataLayout
*DL
);
176 // Returns true if C is already in a simplest form and not worth being
178 bool isSimplestForm(const Candidate
&C
);
180 // Checks whether I is in a candidate form. If so, adds all the matching forms
181 // to Candidates, and tries to find the immediate basis for each of them.
182 void allocateCandidatesAndFindBasis(Instruction
*I
);
184 // Allocate candidates and find bases for Add instructions.
185 void allocateCandidatesAndFindBasisForAdd(Instruction
*I
);
187 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
189 void allocateCandidatesAndFindBasisForAdd(Value
*LHS
, Value
*RHS
,
191 // Allocate candidates and find bases for Mul instructions.
192 void allocateCandidatesAndFindBasisForMul(Instruction
*I
);
194 // Splits LHS into Base + Index and, if succeeds, calls
195 // allocateCandidatesAndFindBasis.
196 void allocateCandidatesAndFindBasisForMul(Value
*LHS
, Value
*RHS
,
199 // Allocate candidates and find bases for GetElementPtr instructions.
200 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst
*GEP
);
202 // A helper function that scales Idx with ElementSize before invoking
203 // allocateCandidatesAndFindBasis.
204 void allocateCandidatesAndFindBasisForGEP(const SCEV
*B
, ConstantInt
*Idx
,
205 Value
*S
, uint64_t ElementSize
,
208 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
210 void allocateCandidatesAndFindBasis(Candidate::Kind CT
, const SCEV
*B
,
211 ConstantInt
*Idx
, Value
*S
,
214 // Rewrites candidate C with respect to Basis.
215 void rewriteCandidateWithBasis(const Candidate
&C
, const Candidate
&Basis
);
217 // A helper function that factors ArrayIdx to a product of a stride and a
218 // constant index, and invokes allocateCandidatesAndFindBasis with the
220 void factorArrayIndex(Value
*ArrayIdx
, const SCEV
*Base
, uint64_t ElementSize
,
221 GetElementPtrInst
*GEP
);
223 // Emit code that computes the "bump" from Basis to C. If the candidate is a
224 // GEP and the bump is not divisible by the element size of the GEP, this
225 // function sets the BumpWithUglyGEP flag to notify its caller to bump the
226 // basis using an ugly GEP.
227 static Value
*emitBump(const Candidate
&Basis
, const Candidate
&C
,
228 IRBuilder
<> &Builder
, const DataLayout
*DL
,
229 bool &BumpWithUglyGEP
);
231 const DataLayout
*DL
= nullptr;
232 DominatorTree
*DT
= nullptr;
234 TargetTransformInfo
*TTI
= nullptr;
235 std::list
<Candidate
> Candidates
;
237 // Temporarily holds all instructions that are unlinked (but not deleted) by
238 // rewriteCandidateWithBasis. These instructions will be actually removed
239 // after all rewriting finishes.
240 std::vector
<Instruction
*> UnlinkedInstructions
;
243 } // end anonymous namespace
245 char StraightLineStrengthReduce::ID
= 0;
247 INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce
, "slsr",
248 "Straight line strength reduction", false, false)
249 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
250 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass
)
251 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
252 INITIALIZE_PASS_END(StraightLineStrengthReduce
, "slsr",
253 "Straight line strength reduction", false, false)
255 FunctionPass
*llvm::createStraightLineStrengthReducePass() {
256 return new StraightLineStrengthReduce();
259 bool StraightLineStrengthReduce::isBasisFor(const Candidate
&Basis
,
260 const Candidate
&C
) {
261 return (Basis
.Ins
!= C
.Ins
&& // skip the same instruction
262 // They must have the same type too. Basis.Base == C.Base doesn't
263 // guarantee their types are the same (PR23975).
264 Basis
.Ins
->getType() == C
.Ins
->getType() &&
265 // Basis must dominate C in order to rewrite C with respect to Basis.
266 DT
->dominates(Basis
.Ins
->getParent(), C
.Ins
->getParent()) &&
267 // They share the same base, stride, and candidate kind.
268 Basis
.Base
== C
.Base
&& Basis
.Stride
== C
.Stride
&&
269 Basis
.CandidateKind
== C
.CandidateKind
);
272 static bool isGEPFoldable(GetElementPtrInst
*GEP
,
273 const TargetTransformInfo
*TTI
) {
274 SmallVector
<const Value
*, 4> Indices
;
275 for (auto I
= GEP
->idx_begin(); I
!= GEP
->idx_end(); ++I
)
276 Indices
.push_back(*I
);
277 return TTI
->getGEPCost(GEP
->getSourceElementType(), GEP
->getPointerOperand(),
278 Indices
) == TargetTransformInfo::TCC_Free
;
281 // Returns whether (Base + Index * Stride) can be folded to an addressing mode.
282 static bool isAddFoldable(const SCEV
*Base
, ConstantInt
*Index
, Value
*Stride
,
283 TargetTransformInfo
*TTI
) {
284 // Index->getSExtValue() may crash if Index is wider than 64-bit.
285 return Index
->getBitWidth() <= 64 &&
286 TTI
->isLegalAddressingMode(Base
->getType(), nullptr, 0, true,
287 Index
->getSExtValue(), UnknownAddressSpace
);
290 bool StraightLineStrengthReduce::isFoldable(const Candidate
&C
,
291 TargetTransformInfo
*TTI
,
292 const DataLayout
*DL
) {
293 if (C
.CandidateKind
== Candidate::Add
)
294 return isAddFoldable(C
.Base
, C
.Index
, C
.Stride
, TTI
);
295 if (C
.CandidateKind
== Candidate::GEP
)
296 return isGEPFoldable(cast
<GetElementPtrInst
>(C
.Ins
), TTI
);
300 // Returns true if GEP has zero or one non-zero index.
301 static bool hasOnlyOneNonZeroIndex(GetElementPtrInst
*GEP
) {
302 unsigned NumNonZeroIndices
= 0;
303 for (auto I
= GEP
->idx_begin(); I
!= GEP
->idx_end(); ++I
) {
304 ConstantInt
*ConstIdx
= dyn_cast
<ConstantInt
>(*I
);
305 if (ConstIdx
== nullptr || !ConstIdx
->isZero())
308 return NumNonZeroIndices
<= 1;
311 bool StraightLineStrengthReduce::isSimplestForm(const Candidate
&C
) {
312 if (C
.CandidateKind
== Candidate::Add
) {
313 // B + 1 * S or B + (-1) * S
314 return C
.Index
->isOne() || C
.Index
->isMinusOne();
316 if (C
.CandidateKind
== Candidate::Mul
) {
318 return C
.Index
->isZero();
320 if (C
.CandidateKind
== Candidate::GEP
) {
321 // (char*)B + S or (char*)B - S
322 return ((C
.Index
->isOne() || C
.Index
->isMinusOne()) &&
323 hasOnlyOneNonZeroIndex(cast
<GetElementPtrInst
>(C
.Ins
)));
328 // TODO: We currently implement an algorithm whose time complexity is linear in
329 // the number of existing candidates. However, we could do better by using
330 // ScopedHashTable. Specifically, while traversing the dominator tree, we could
331 // maintain all the candidates that dominate the basic block being traversed in
332 // a ScopedHashTable. This hash table is indexed by the base and the stride of
333 // a candidate. Therefore, finding the immediate basis of a candidate boils down
334 // to one hash-table look up.
335 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
336 Candidate::Kind CT
, const SCEV
*B
, ConstantInt
*Idx
, Value
*S
,
338 Candidate
C(CT
, B
, Idx
, S
, I
);
339 // SLSR can complicate an instruction in two cases:
341 // 1. If we can fold I into an addressing mode, computing I is likely free or
342 // takes only one instruction.
344 // 2. I is already in a simplest form. For example, when
347 // rewriting Y to X - 7 * S is probably a bad idea.
349 // In the above cases, we still add I to the candidate list so that I can be
350 // the basis of other candidates, but we leave I's basis blank so that I
351 // won't be rewritten.
352 if (!isFoldable(C
, TTI
, DL
) && !isSimplestForm(C
)) {
353 // Try to compute the immediate basis of C.
354 unsigned NumIterations
= 0;
355 // Limit the scan radius to avoid running in quadratice time.
356 static const unsigned MaxNumIterations
= 50;
357 for (auto Basis
= Candidates
.rbegin();
358 Basis
!= Candidates
.rend() && NumIterations
< MaxNumIterations
;
359 ++Basis
, ++NumIterations
) {
360 if (isBasisFor(*Basis
, C
)) {
366 // Regardless of whether we find a basis for C, we need to push C to the
367 // candidate list so that it can be the basis of other candidates.
368 Candidates
.push_back(C
);
371 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
373 switch (I
->getOpcode()) {
374 case Instruction::Add
:
375 allocateCandidatesAndFindBasisForAdd(I
);
377 case Instruction::Mul
:
378 allocateCandidatesAndFindBasisForMul(I
);
380 case Instruction::GetElementPtr
:
381 allocateCandidatesAndFindBasisForGEP(cast
<GetElementPtrInst
>(I
));
386 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
388 // Try matching B + i * S.
389 if (!isa
<IntegerType
>(I
->getType()))
392 assert(I
->getNumOperands() == 2 && "isn't I an add?");
393 Value
*LHS
= I
->getOperand(0), *RHS
= I
->getOperand(1);
394 allocateCandidatesAndFindBasisForAdd(LHS
, RHS
, I
);
396 allocateCandidatesAndFindBasisForAdd(RHS
, LHS
, I
);
399 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
400 Value
*LHS
, Value
*RHS
, Instruction
*I
) {
402 ConstantInt
*Idx
= nullptr;
403 if (match(RHS
, m_Mul(m_Value(S
), m_ConstantInt(Idx
)))) {
404 // I = LHS + RHS = LHS + Idx * S
405 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), Idx
, S
, I
);
406 } else if (match(RHS
, m_Shl(m_Value(S
), m_ConstantInt(Idx
)))) {
407 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
408 APInt
One(Idx
->getBitWidth(), 1);
409 Idx
= ConstantInt::get(Idx
->getContext(), One
<< Idx
->getValue());
410 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), Idx
, S
, I
);
412 // At least, I = LHS + 1 * RHS
413 ConstantInt
*One
= ConstantInt::get(cast
<IntegerType
>(I
->getType()), 1);
414 allocateCandidatesAndFindBasis(Candidate::Add
, SE
->getSCEV(LHS
), One
, RHS
,
419 // Returns true if A matches B + C where C is constant.
420 static bool matchesAdd(Value
*A
, Value
*&B
, ConstantInt
*&C
) {
421 return (match(A
, m_Add(m_Value(B
), m_ConstantInt(C
))) ||
422 match(A
, m_Add(m_ConstantInt(C
), m_Value(B
))));
425 // Returns true if A matches B | C where C is constant.
426 static bool matchesOr(Value
*A
, Value
*&B
, ConstantInt
*&C
) {
427 return (match(A
, m_Or(m_Value(B
), m_ConstantInt(C
))) ||
428 match(A
, m_Or(m_ConstantInt(C
), m_Value(B
))));
431 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
432 Value
*LHS
, Value
*RHS
, Instruction
*I
) {
434 ConstantInt
*Idx
= nullptr;
435 if (matchesAdd(LHS
, B
, Idx
)) {
436 // If LHS is in the form of "Base + Index", then I is in the form of
437 // "(Base + Index) * RHS".
438 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(B
), Idx
, RHS
, I
);
439 } else if (matchesOr(LHS
, B
, Idx
) && haveNoCommonBitsSet(B
, Idx
, *DL
)) {
440 // If LHS is in the form of "Base | Index" and Base and Index have no common
442 // Base | Index = Base + Index
443 // and I is thus in the form of "(Base + Index) * RHS".
444 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(B
), Idx
, RHS
, I
);
446 // Otherwise, at least try the form (LHS + 0) * RHS.
447 ConstantInt
*Zero
= ConstantInt::get(cast
<IntegerType
>(I
->getType()), 0);
448 allocateCandidatesAndFindBasis(Candidate::Mul
, SE
->getSCEV(LHS
), Zero
, RHS
,
453 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
455 // Try matching (B + i) * S.
456 // TODO: we could extend SLSR to float and vector types.
457 if (!isa
<IntegerType
>(I
->getType()))
460 assert(I
->getNumOperands() == 2 && "isn't I a mul?");
461 Value
*LHS
= I
->getOperand(0), *RHS
= I
->getOperand(1);
462 allocateCandidatesAndFindBasisForMul(LHS
, RHS
, I
);
464 // Symmetrically, try to split RHS to Base + Index.
465 allocateCandidatesAndFindBasisForMul(RHS
, LHS
, I
);
469 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
470 const SCEV
*B
, ConstantInt
*Idx
, Value
*S
, uint64_t ElementSize
,
472 // I = B + sext(Idx *nsw S) * ElementSize
473 // = B + (sext(Idx) * sext(S)) * ElementSize
474 // = B + (sext(Idx) * ElementSize) * sext(S)
475 // Casting to IntegerType is safe because we skipped vector GEPs.
476 IntegerType
*IntPtrTy
= cast
<IntegerType
>(DL
->getIntPtrType(I
->getType()));
477 ConstantInt
*ScaledIdx
= ConstantInt::get(
478 IntPtrTy
, Idx
->getSExtValue() * (int64_t)ElementSize
, true);
479 allocateCandidatesAndFindBasis(Candidate::GEP
, B
, ScaledIdx
, S
, I
);
482 void StraightLineStrengthReduce::factorArrayIndex(Value
*ArrayIdx
,
484 uint64_t ElementSize
,
485 GetElementPtrInst
*GEP
) {
486 // At least, ArrayIdx = ArrayIdx *nsw 1.
487 allocateCandidatesAndFindBasisForGEP(
488 Base
, ConstantInt::get(cast
<IntegerType
>(ArrayIdx
->getType()), 1),
489 ArrayIdx
, ElementSize
, GEP
);
490 Value
*LHS
= nullptr;
491 ConstantInt
*RHS
= nullptr;
492 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
493 // itself. This would allow us to handle the shl case for free. However,
494 // matching SCEVs has two issues:
496 // 1. this would complicate rewriting because the rewriting procedure
497 // would have to translate SCEVs back to IR instructions. This translation
498 // is difficult when LHS is further evaluated to a composite SCEV.
500 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
501 // to strip nsw/nuw flags which are critical for SLSR to trace into
502 // sext'ed multiplication.
503 if (match(ArrayIdx
, m_NSWMul(m_Value(LHS
), m_ConstantInt(RHS
)))) {
504 // SLSR is currently unsafe if i * S may overflow.
505 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
506 allocateCandidatesAndFindBasisForGEP(Base
, RHS
, LHS
, ElementSize
, GEP
);
507 } else if (match(ArrayIdx
, m_NSWShl(m_Value(LHS
), m_ConstantInt(RHS
)))) {
508 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
509 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
510 APInt
One(RHS
->getBitWidth(), 1);
511 ConstantInt
*PowerOf2
=
512 ConstantInt::get(RHS
->getContext(), One
<< RHS
->getValue());
513 allocateCandidatesAndFindBasisForGEP(Base
, PowerOf2
, LHS
, ElementSize
, GEP
);
517 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
518 GetElementPtrInst
*GEP
) {
519 // TODO: handle vector GEPs
520 if (GEP
->getType()->isVectorTy())
523 SmallVector
<const SCEV
*, 4> IndexExprs
;
524 for (auto I
= GEP
->idx_begin(); I
!= GEP
->idx_end(); ++I
)
525 IndexExprs
.push_back(SE
->getSCEV(*I
));
527 gep_type_iterator GTI
= gep_type_begin(GEP
);
528 for (unsigned I
= 1, E
= GEP
->getNumOperands(); I
!= E
; ++I
, ++GTI
) {
532 const SCEV
*OrigIndexExpr
= IndexExprs
[I
- 1];
533 IndexExprs
[I
- 1] = SE
->getZero(OrigIndexExpr
->getType());
535 // The base of this candidate is GEP's base plus the offsets of all
536 // indices except this current one.
537 const SCEV
*BaseExpr
= SE
->getGEPExpr(cast
<GEPOperator
>(GEP
), IndexExprs
);
538 Value
*ArrayIdx
= GEP
->getOperand(I
);
539 uint64_t ElementSize
= DL
->getTypeAllocSize(GTI
.getIndexedType());
540 if (ArrayIdx
->getType()->getIntegerBitWidth() <=
541 DL
->getPointerSizeInBits(GEP
->getAddressSpace())) {
542 // Skip factoring if ArrayIdx is wider than the pointer size, because
543 // ArrayIdx is implicitly truncated to the pointer size.
544 factorArrayIndex(ArrayIdx
, BaseExpr
, ElementSize
, GEP
);
546 // When ArrayIdx is the sext of a value, we try to factor that value as
547 // well. Handling this case is important because array indices are
548 // typically sign-extended to the pointer size.
549 Value
*TruncatedArrayIdx
= nullptr;
550 if (match(ArrayIdx
, m_SExt(m_Value(TruncatedArrayIdx
))) &&
551 TruncatedArrayIdx
->getType()->getIntegerBitWidth() <=
552 DL
->getPointerSizeInBits(GEP
->getAddressSpace())) {
553 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
554 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
555 factorArrayIndex(TruncatedArrayIdx
, BaseExpr
, ElementSize
, GEP
);
558 IndexExprs
[I
- 1] = OrigIndexExpr
;
562 // A helper function that unifies the bitwidth of A and B.
563 static void unifyBitWidth(APInt
&A
, APInt
&B
) {
564 if (A
.getBitWidth() < B
.getBitWidth())
565 A
= A
.sext(B
.getBitWidth());
566 else if (A
.getBitWidth() > B
.getBitWidth())
567 B
= B
.sext(A
.getBitWidth());
570 Value
*StraightLineStrengthReduce::emitBump(const Candidate
&Basis
,
572 IRBuilder
<> &Builder
,
573 const DataLayout
*DL
,
574 bool &BumpWithUglyGEP
) {
575 APInt Idx
= C
.Index
->getValue(), BasisIdx
= Basis
.Index
->getValue();
576 unifyBitWidth(Idx
, BasisIdx
);
577 APInt IndexOffset
= Idx
- BasisIdx
;
579 BumpWithUglyGEP
= false;
580 if (Basis
.CandidateKind
== Candidate::GEP
) {
582 IndexOffset
.getBitWidth(),
583 DL
->getTypeAllocSize(
584 cast
<GetElementPtrInst
>(Basis
.Ins
)->getResultElementType()));
586 APInt::sdivrem(IndexOffset
, ElementSize
, Q
, R
);
590 BumpWithUglyGEP
= true;
593 // Compute Bump = C - Basis = (i' - i) * S.
594 // Common case 1: if (i' - i) is 1, Bump = S.
595 if (IndexOffset
== 1)
597 // Common case 2: if (i' - i) is -1, Bump = -S.
598 if (IndexOffset
.isAllOnesValue())
599 return Builder
.CreateNeg(C
.Stride
);
601 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
602 // have different bit widths.
603 IntegerType
*DeltaType
=
604 IntegerType::get(Basis
.Ins
->getContext(), IndexOffset
.getBitWidth());
605 Value
*ExtendedStride
= Builder
.CreateSExtOrTrunc(C
.Stride
, DeltaType
);
606 if (IndexOffset
.isPowerOf2()) {
607 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
608 ConstantInt
*Exponent
= ConstantInt::get(DeltaType
, IndexOffset
.logBase2());
609 return Builder
.CreateShl(ExtendedStride
, Exponent
);
611 if ((-IndexOffset
).isPowerOf2()) {
612 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
613 ConstantInt
*Exponent
=
614 ConstantInt::get(DeltaType
, (-IndexOffset
).logBase2());
615 return Builder
.CreateNeg(Builder
.CreateShl(ExtendedStride
, Exponent
));
617 Constant
*Delta
= ConstantInt::get(DeltaType
, IndexOffset
);
618 return Builder
.CreateMul(ExtendedStride
, Delta
);
621 void StraightLineStrengthReduce::rewriteCandidateWithBasis(
622 const Candidate
&C
, const Candidate
&Basis
) {
623 assert(C
.CandidateKind
== Basis
.CandidateKind
&& C
.Base
== Basis
.Base
&&
624 C
.Stride
== Basis
.Stride
);
625 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
626 // basis of a candidate cannot be unlinked before the candidate.
627 assert(Basis
.Ins
->getParent() != nullptr && "the basis is unlinked");
629 // An instruction can correspond to multiple candidates. Therefore, instead of
630 // simply deleting an instruction when we rewrite it, we mark its parent as
631 // nullptr (i.e. unlink it) so that we can skip the candidates whose
632 // instruction is already rewritten.
633 if (!C
.Ins
->getParent())
636 IRBuilder
<> Builder(C
.Ins
);
637 bool BumpWithUglyGEP
;
638 Value
*Bump
= emitBump(Basis
, C
, Builder
, DL
, BumpWithUglyGEP
);
639 Value
*Reduced
= nullptr; // equivalent to but weaker than C.Ins
640 switch (C
.CandidateKind
) {
642 case Candidate::Mul
: {
645 if (match(Bump
, m_Neg(m_Value(NegBump
)))) {
646 // If Bump is a neg instruction, emit C = Basis - (-Bump).
647 Reduced
= Builder
.CreateSub(Basis
.Ins
, NegBump
);
648 // We only use the negative argument of Bump, and Bump itself may be
650 RecursivelyDeleteTriviallyDeadInstructions(Bump
);
652 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
653 // usually unsound, e.g.,
655 // X = (-2 +nsw 1) *nsw INT_MAX
656 // Y = (-2 +nsw 3) *nsw INT_MAX
658 // Y = X + 2 * INT_MAX
660 // Neither + and * in the resultant expression are nsw.
661 Reduced
= Builder
.CreateAdd(Basis
.Ins
, Bump
);
667 Type
*IntPtrTy
= DL
->getIntPtrType(C
.Ins
->getType());
668 bool InBounds
= cast
<GetElementPtrInst
>(C
.Ins
)->isInBounds();
669 if (BumpWithUglyGEP
) {
670 // C = (char *)Basis + Bump
671 unsigned AS
= Basis
.Ins
->getType()->getPointerAddressSpace();
672 Type
*CharTy
= Type::getInt8PtrTy(Basis
.Ins
->getContext(), AS
);
673 Reduced
= Builder
.CreateBitCast(Basis
.Ins
, CharTy
);
676 Builder
.CreateInBoundsGEP(Builder
.getInt8Ty(), Reduced
, Bump
);
678 Reduced
= Builder
.CreateGEP(Builder
.getInt8Ty(), Reduced
, Bump
);
679 Reduced
= Builder
.CreateBitCast(Reduced
, C
.Ins
->getType());
681 // C = gep Basis, Bump
682 // Canonicalize bump to pointer size.
683 Bump
= Builder
.CreateSExtOrTrunc(Bump
, IntPtrTy
);
685 Reduced
= Builder
.CreateInBoundsGEP(
686 cast
<GetElementPtrInst
>(Basis
.Ins
)->getResultElementType(),
689 Reduced
= Builder
.CreateGEP(
690 cast
<GetElementPtrInst
>(Basis
.Ins
)->getResultElementType(),
696 llvm_unreachable("C.CandidateKind is invalid");
698 Reduced
->takeName(C
.Ins
);
699 C
.Ins
->replaceAllUsesWith(Reduced
);
700 // Unlink C.Ins so that we can skip other candidates also corresponding to
701 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
702 C
.Ins
->removeFromParent();
703 UnlinkedInstructions
.push_back(C
.Ins
);
706 bool StraightLineStrengthReduce::runOnFunction(Function
&F
) {
710 TTI
= &getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
711 DT
= &getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
712 SE
= &getAnalysis
<ScalarEvolutionWrapperPass
>().getSE();
713 // Traverse the dominator tree in the depth-first order. This order makes sure
714 // all bases of a candidate are in Candidates when we process it.
715 for (const auto Node
: depth_first(DT
))
716 for (auto &I
: *(Node
->getBlock()))
717 allocateCandidatesAndFindBasis(&I
);
719 // Rewrite candidates in the reverse depth-first order. This order makes sure
720 // a candidate being rewritten is not a basis for any other candidate.
721 while (!Candidates
.empty()) {
722 const Candidate
&C
= Candidates
.back();
723 if (C
.Basis
!= nullptr) {
724 rewriteCandidateWithBasis(C
, *C
.Basis
);
726 Candidates
.pop_back();
729 // Delete all unlink instructions.
730 for (auto *UnlinkedInst
: UnlinkedInstructions
) {
731 for (unsigned I
= 0, E
= UnlinkedInst
->getNumOperands(); I
!= E
; ++I
) {
732 Value
*Op
= UnlinkedInst
->getOperand(I
);
733 UnlinkedInst
->setOperand(I
, nullptr);
734 RecursivelyDeleteTriviallyDeadInstructions(Op
);
736 UnlinkedInst
->deleteValue();
738 bool Ret
= !UnlinkedInstructions
.empty();
739 UnlinkedInstructions
.clear();