1//===- StraightLineStrengthReduce.cpp - -----------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
14//
15// There are many optimizations we can perform in the domain of SLSR.
16// We look for strength reduction candidates in the following forms:
17//
18// Form Add: B + i * S
19// Form Mul: (B + i) * S
20// Form GEP: &B[i * S]
21//
22// where S is an integer variable, and i is a constant integer. If we found two
23// candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
24// in a simpler way with respect to S1 (index delta). For example,
25//
26// S1: X = B + i * S
27// S2: Y = B + i' * S => X + (i' - i) * S
28//
29// S1: X = (B + i) * S
30// S2: Y = (B + i') * S => X + (i' - i) * S
31//
32// S1: X = &B[i * S]
33// S2: Y = &B[i' * S] => &X[(i' - i) * S]
34//
35// Note: (i' - i) * S is folded to the extent possible.
36//
37// For Add and GEP forms, we can also rewrite a candidate in a simpler way
38// with respect to other dominating candidates if their B or S are different
39// but other parts are the same. For example,
40//
41// Base Delta:
42// S1: X = B + i * S
43// S2: Y = B' + i * S => X + (B' - B)
44//
45// S1: X = &B [i * S]
46// S2: Y = &B'[i * S] => X + (B' - B)
47//
48// Stride Delta:
49// S1: X = B + i * S
50// S2: Y = B + i * S' => X + i * (S' - S)
51//
52// S1: X = &B[i * S]
53// S2: Y = &B[i * S'] => X + i * (S' - S)
54//
55// PS: Stride delta rewrite on Mul form is usually non-profitable, and Base
56// delta rewrite sometimes is profitable, so we do not support them on Mul.
57//
58// This rewriting is in general a good idea. The code patterns we focus on
59// usually come from loop unrolling, so the delta is likely the same
60// across iterations and can be reused. When that happens, the optimized form
61// takes only one add starting from the second iteration.
62//
63// When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
64// multiple bases, we choose to rewrite S2 with respect to its "immediate"
65// basis, the basis that is the closest ancestor in the dominator tree.
66//
67// TODO:
68//
69// - Floating point arithmetics when fast math is enabled.
70
71#include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/DepthFirstIterator.h"
74#include "llvm/ADT/SetVector.h"
75#include "llvm/ADT/SmallPtrSet.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/Statistic.h"
78#include "llvm/Analysis/ScalarEvolution.h"
79#include "llvm/Analysis/ScalarEvolutionExpressions.h"
80#include "llvm/Analysis/TargetTransformInfo.h"
81#include "llvm/Analysis/ValueTracking.h"
82#include "llvm/IR/Constants.h"
83#include "llvm/IR/DataLayout.h"
84#include "llvm/IR/DerivedTypes.h"
85#include "llvm/IR/Dominators.h"
86#include "llvm/IR/GetElementPtrTypeIterator.h"
87#include "llvm/IR/IRBuilder.h"
88#include "llvm/IR/Instruction.h"
89#include "llvm/IR/Instructions.h"
90#include "llvm/IR/Module.h"
91#include "llvm/IR/Operator.h"
92#include "llvm/IR/PatternMatch.h"
93#include "llvm/IR/Type.h"
94#include "llvm/IR/Value.h"
95#include "llvm/InitializePasses.h"
96#include "llvm/Pass.h"
97#include "llvm/Support/Casting.h"
98#include "llvm/Support/DebugCounter.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Transforms/Scalar.h"
101#include "llvm/Transforms/Utils/Local.h"
102#include <cassert>
103#include <cstdint>
104#include <limits>
105#include <list>
106#include <queue>
107#include <vector>
108
109using namespace llvm;
110using namespace PatternMatch;
111
112#define DEBUG_TYPE "slsr"
113
114static const unsigned UnknownAddressSpace =
115 std::numeric_limits<unsigned>::max();
116
117DEBUG_COUNTER(StraightLineStrengthReduceCounter, "slsr-counter",
118 "Controls whether rewriteCandidate is executed.");
119
120// Only for testing.
121static cl::opt<bool>
122 EnablePoisonReuseGuard("enable-poison-reuse-guard", cl::init(Val: true),
123 cl::desc("Enable poison-reuse guard"));
124
125STATISTIC(NumSCEVCandidateBasisDifferences,
126 "Number of candidate-basis SCEV differences computed by SLSR");
127
128namespace {
129
130class StraightLineStrengthReduceLegacyPass : public FunctionPass {
131 const DataLayout *DL = nullptr;
132
133public:
134 static char ID;
135
136 StraightLineStrengthReduceLegacyPass() : FunctionPass(ID) {
137 initializeStraightLineStrengthReduceLegacyPassPass(
138 *PassRegistry::getPassRegistry());
139 }
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
142 AU.addRequired<DominatorTreeWrapperPass>();
143 AU.addRequired<ScalarEvolutionWrapperPass>();
144 AU.addRequired<TargetTransformInfoWrapperPass>();
145 // We do not modify the shape of the CFG.
146 AU.setPreservesCFG();
147 }
148
149 bool doInitialization(Module &M) override {
150 DL = &M.getDataLayout();
151 return false;
152 }
153
154 bool runOnFunction(Function &F) override;
155};
156
157class StraightLineStrengthReduce {
158public:
159 StraightLineStrengthReduce(const DataLayout *DL, DominatorTree *DT,
160 ScalarEvolution *SE, TargetTransformInfo *TTI)
161 : DL(DL), DT(DT), SE(SE), TTI(TTI) {}
162
163 // SLSR candidate. Such a candidate must be in one of the forms described in
164 // the header comments.
165 struct Candidate {
166 enum Kind {
167 Invalid, // reserved for the default constructor
168 Add, // B + i * S
169 Mul, // (B + i) * S
170 GEP, // &B[..][i * S][..]
171 };
172
173 enum DKind {
174 InvalidDelta, // reserved for the default constructor
175 IndexDelta, // Delta is a constant from Index
176 BaseDelta, // Delta is a constant or variable from Base
177 StrideDelta, // Delta is a constant or variable from Stride
178 };
179
180 Candidate() = default;
181 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
182 Instruction *I, const SCEV *StrideSCEV)
183 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
184 StrideSCEV(StrideSCEV) {}
185
186 Kind CandidateKind = Invalid;
187
188 const SCEV *Base = nullptr;
189 // TODO: Swap Index and Stride's name.
190 // Note that Index and Stride of a GEP candidate do not necessarily have the
191 // same integer type. In that case, during rewriting, Stride will be
192 // sign-extended or truncated to Index's type.
193 ConstantInt *Index = nullptr;
194
195 Value *Stride = nullptr;
196
197 // The instruction this candidate corresponds to. It helps us to rewrite a
198 // candidate with respect to its immediate basis. Note that one instruction
199 // can correspond to multiple candidates depending on how you associate the
200 // expression. For instance,
201 //
202 // (a + 1) * (b + 2)
203 //
204 // can be treated as
205 //
206 // <Base: a, Index: 1, Stride: b + 2>
207 //
208 // or
209 //
210 // <Base: b, Index: 2, Stride: a + 1>
211 Instruction *Ins = nullptr;
212
213 // Points to the immediate basis of this candidate, or nullptr if we cannot
214 // find any basis for this candidate.
215 Candidate *Basis = nullptr;
216
217 DKind DeltaKind = InvalidDelta;
218
219 // Store SCEV of Stride to compute delta from different strides
220 const SCEV *StrideSCEV = nullptr;
221
222 // Points to (Y - X) that will be used to rewrite this candidate.
223 Value *Delta = nullptr;
224
225 // List of instructions whose poison-generating annotations must be dropped
226 // if this candidate is used as the basis of an executed rewrite.
227 SmallVector<Instruction *> DropList;
228
229 /// Cost model: Evaluate the computational efficiency of the candidate.
230 ///
231 /// Efficiency levels (higher is better):
232 /// ZeroInst (5) - [Variable] or [Const]
233 /// OneInstOneVar (4) - [Variable + Const] or [Variable * Const]
234 /// OneInstTwoVar (3) - [Variable + Variable] or [Variable * Variable]
235 /// TwoInstOneVar (2) - [Const + Const * Variable]
236 /// TwoInstTwoVar (1) - [Variable + Const * Variable]
237 enum EfficiencyLevel : unsigned {
238 Unknown = 0,
239 TwoInstTwoVar = 1,
240 TwoInstOneVar = 2,
241 OneInstTwoVar = 3,
242 OneInstOneVar = 4,
243 ZeroInst = 5
244 };
245
246 static EfficiencyLevel
247 getComputationEfficiency(Kind CandidateKind, const ConstantInt *Index,
248 const Value *Stride, const SCEV *Base = nullptr) {
249 bool IsConstantBase = false;
250 bool IsZeroBase = false;
251 // When evaluating the efficiency of a rewrite, if the Base's SCEV is
252 // not available, conservatively assume the base is not constant.
253 if (auto *ConstBase = dyn_cast_or_null<SCEVConstant>(Val: Base)) {
254 IsConstantBase = true;
255 IsZeroBase = ConstBase->getValue()->isZero();
256 }
257
258 bool IsConstantStride = isa<ConstantInt>(Val: Stride);
259 bool IsZeroStride =
260 IsConstantStride && cast<ConstantInt>(Val: Stride)->isZero();
261 // All constants
262 if (IsConstantBase && IsConstantStride)
263 return ZeroInst;
264
265 // (Base + Index) * Stride
266 if (CandidateKind == Mul) {
267 if (IsZeroStride)
268 return ZeroInst;
269 if (Index->isZero())
270 return (IsConstantStride || IsConstantBase) ? OneInstOneVar
271 : OneInstTwoVar;
272
273 if (IsConstantBase)
274 return IsZeroBase && (Index->isOne() || Index->isMinusOne())
275 ? ZeroInst
276 : OneInstOneVar;
277
278 if (IsConstantStride) {
279 auto *CI = cast<ConstantInt>(Val: Stride);
280 return (CI->isOne() || CI->isMinusOne()) ? OneInstOneVar
281 : TwoInstOneVar;
282 }
283 return TwoInstTwoVar;
284 }
285
286 // Base + Index * Stride
287 assert(CandidateKind == Add || CandidateKind == GEP);
288 if (Index->isZero() || IsZeroStride)
289 return ZeroInst;
290
291 bool IsSimpleIndex = Index->isOne() || Index->isMinusOne();
292
293 if (IsConstantBase)
294 return IsZeroBase ? (IsSimpleIndex ? ZeroInst : OneInstOneVar)
295 : (IsSimpleIndex ? OneInstOneVar : TwoInstOneVar);
296
297 if (IsConstantStride)
298 return IsZeroStride ? ZeroInst : OneInstOneVar;
299
300 if (IsSimpleIndex)
301 return OneInstTwoVar;
302
303 return TwoInstTwoVar;
304 }
305
306 // Evaluate if the given delta is profitable to rewrite this candidate.
307 bool isProfitableRewrite(const Value &Delta, const DKind DeltaKind) const {
308 // This function cannot accurately evaluate the profit of whole expression
309 // with context. A candidate (B + I * S) cannot express whether this
310 // instruction needs to compute on its own (I * S), which may be shared
311 // with other candidates or may need instructions to compute.
312 // If the rewritten form has the same strength, still rewrite to
313 // (X + Delta) since it may expose more CSE opportunities on Delta, as
314 // unrolled loops usually have identical Delta for each unrolled body.
315 //
316 // Note, this function should only be used on Index Delta rewrite.
317 // Base and Stride delta need context info to evaluate the register
318 // pressure impact from variable delta.
319 return getComputationEfficiency(CandidateKind, Index, Stride, Base) <=
320 getRewriteEfficiency(Delta, DeltaKind);
321 }
322
323 // Evaluate the rewrite efficiency of this candidate with its Basis
324 EfficiencyLevel getRewriteEfficiency() const {
325 return Basis ? getRewriteEfficiency(Delta: *Delta, DeltaKind) : Unknown;
326 }
327
328 // Evaluate the rewrite efficiency of this candidate with a given delta
329 EfficiencyLevel getRewriteEfficiency(const Value &Delta,
330 const DKind DeltaKind) const {
331 switch (DeltaKind) {
332 case BaseDelta: // [X + Delta]
333 return getComputationEfficiency(
334 CandidateKind,
335 Index: ConstantInt::get(Ty: cast<IntegerType>(Val: Delta.getType()), V: 1), Stride: &Delta);
336 case StrideDelta: // [X + Index * Delta]
337 return getComputationEfficiency(CandidateKind, Index, Stride: &Delta);
338 case IndexDelta: // [X + Delta * Stride]
339 return getComputationEfficiency(CandidateKind,
340 Index: cast<ConstantInt>(Val: &Delta), Stride);
341 default:
342 return Unknown;
343 }
344 }
345
346 bool isHighEfficiency() const {
347 return getComputationEfficiency(CandidateKind, Index, Stride, Base) >=
348 OneInstOneVar;
349 }
350
351 // Verify that this candidate has valid delta components relative to the
352 // basis
353 bool hasValidDelta(const Candidate &Basis) const {
354 switch (DeltaKind) {
355 case IndexDelta:
356 // Index differs, Base and Stride must match
357 return Base == Basis.Base && StrideSCEV == Basis.StrideSCEV;
358 case StrideDelta:
359 // Stride differs, Base and Index must match
360 return Base == Basis.Base && Index == Basis.Index;
361 case BaseDelta:
362 // Base differs, Stride and Index must match
363 return StrideSCEV == Basis.StrideSCEV && Index == Basis.Index;
364 default:
365 return false;
366 }
367 }
368 };
369
370 bool runOnFunction(Function &F);
371
372private:
373 // Fetch straight-line basis for rewriting C, update C.Basis to point to it,
374 // and store the delta between C and its Basis in C.Delta.
375 void setBasisAndDeltaFor(Candidate &C);
376 // Returns whether the candidate can be folded into an addressing mode.
377 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI);
378
379 // Checks whether I is in a candidate form. If so, adds all the matching forms
380 // to Candidates, and tries to find the immediate basis for each of them.
381 void allocateCandidatesAndFindBasis(Instruction *I);
382
383 // Allocate candidates and find bases for Add instructions.
384 void allocateCandidatesAndFindBasisForAdd(Instruction *I);
385
386 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
387 // candidate.
388 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
389 Instruction *I);
390 // Allocate candidates and find bases for Mul instructions.
391 void allocateCandidatesAndFindBasisForMul(Instruction *I);
392
393 // Splits LHS into Base + Index and, if succeeds, calls
394 // allocateCandidatesAndFindBasis.
395 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
396 Instruction *I);
397
398 // Allocate candidates and find bases for GetElementPtr instructions.
399 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
400
401 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
402 // basis.
403 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
404 ConstantInt *Idx, Value *S,
405 Instruction *I);
406
407 // Rewrites candidate C with respect to Basis.
408 void rewriteCandidate(const Candidate &C);
409
410 // Emit code that computes the "bump" from Basis to C.
411 static Value *emitBump(const Candidate &Basis, const Candidate &C,
412 IRBuilder<> &Builder, const DataLayout *DL);
413
414 const DataLayout *DL = nullptr;
415 DominatorTree *DT = nullptr;
416 ScalarEvolution *SE;
417 TargetTransformInfo *TTI = nullptr;
418 std::list<Candidate> Candidates;
419
420 // Map from SCEV to instructions that represent the value,
421 // instructions are sorted in depth-first order.
422 DenseMap<const SCEV *, SmallSetVector<Instruction *, 2>> SCEVToInsts;
423
424 using SCEVUnknownSet = SmallPtrSet<const SCEVUnknown *, 4>;
425 DenseMap<const SCEV *, SCEVUnknownSet> SCEVUnknownsCache;
426
427 // Record the dependency between instructions. If C.Basis == B, we would have
428 // {B.Ins -> {C.Ins, ...}}.
429 MapVector<Instruction *, std::vector<Instruction *>> DependencyGraph;
430
431 // Map between each instruction and its possible candidates.
432 DenseMap<Instruction *, SmallVector<Candidate *, 3>> RewriteCandidates;
433
434 // All instructions that have candidates sort in topological order based on
435 // dependency graph, from roots to leaves.
436 std::vector<Instruction *> SortedCandidateInsts;
437
438 // Record all instructions that are already rewritten and will be removed
439 // later.
440 std::vector<Instruction *> DeadInstructions;
441
442 // Classify candidates against Delta kind
443 class CandidateDictTy {
444 public:
445 using CandsTy = SmallVector<Candidate *, 8>;
446 using BBToCandsTy = DenseMap<const BasicBlock *, CandsTy>;
447
448 private:
449 // Index delta Basis must have the same (Base, StrideSCEV, Inst.Type)
450 using IndexDeltaKeyTy = std::tuple<const SCEV *, const SCEV *, Type *>;
451 DenseMap<IndexDeltaKeyTy, BBToCandsTy> IndexDeltaCandidates;
452
453 // Base delta Basis must have the same (StrideSCEV, Index, Inst.Type)
454 using BaseDeltaKeyTy = std::tuple<const SCEV *, ConstantInt *, Type *>;
455 DenseMap<BaseDeltaKeyTy, BBToCandsTy> BaseDeltaCandidates;
456
457 // Stride delta Basis must have the same (Base, Index, Inst.Type)
458 using StrideDeltaKeyTy = std::tuple<const SCEV *, ConstantInt *, Type *>;
459 DenseMap<StrideDeltaKeyTy, BBToCandsTy> StrideDeltaCandidates;
460
461 public:
462 // TODO: Disable index delta on GEP after we completely move
463 // from typed GEP to PtrAdd.
464 const BBToCandsTy *getCandidatesWithDeltaKind(const Candidate &C,
465 Candidate::DKind K) const {
466 assert(K != Candidate::InvalidDelta);
467 if (K == Candidate::IndexDelta) {
468 IndexDeltaKeyTy IndexDeltaKey(C.Base, C.StrideSCEV, C.Ins->getType());
469 auto It = IndexDeltaCandidates.find(Val: IndexDeltaKey);
470 if (It != IndexDeltaCandidates.end())
471 return &It->second;
472 } else if (K == Candidate::BaseDelta) {
473 BaseDeltaKeyTy BaseDeltaKey(C.StrideSCEV, C.Index, C.Ins->getType());
474 auto It = BaseDeltaCandidates.find(Val: BaseDeltaKey);
475 if (It != BaseDeltaCandidates.end())
476 return &It->second;
477 } else {
478 assert(K == Candidate::StrideDelta);
479 StrideDeltaKeyTy StrideDeltaKey(C.Base, C.Index, C.Ins->getType());
480 auto It = StrideDeltaCandidates.find(Val: StrideDeltaKey);
481 if (It != StrideDeltaCandidates.end())
482 return &It->second;
483 }
484 return nullptr;
485 }
486
487 // Pointers to C must remain valid until CandidateDict is cleared.
488 void add(Candidate &C) {
489 Type *ValueType = C.Ins->getType();
490 BasicBlock *BB = C.Ins->getParent();
491 IndexDeltaKeyTy IndexDeltaKey(C.Base, C.StrideSCEV, ValueType);
492 BaseDeltaKeyTy BaseDeltaKey(C.StrideSCEV, C.Index, ValueType);
493 StrideDeltaKeyTy StrideDeltaKey(C.Base, C.Index, ValueType);
494 IndexDeltaCandidates[IndexDeltaKey][BB].push_back(Elt: &C);
495 BaseDeltaCandidates[BaseDeltaKey][BB].push_back(Elt: &C);
496 StrideDeltaCandidates[StrideDeltaKey][BB].push_back(Elt: &C);
497 }
498 // Remove all mappings from set
499 void clear() {
500 IndexDeltaCandidates.clear();
501 BaseDeltaCandidates.clear();
502 StrideDeltaCandidates.clear();
503 }
504 } CandidateDict;
505
506 const SCEV *getAndRecordSCEV(Value *V) {
507 auto *S = SE->getSCEV(V);
508 if (isa<Instruction>(Val: V) && !(isa<SCEVCouldNotCompute>(Val: S) ||
509 isa<SCEVUnknown>(Val: S) || isa<SCEVConstant>(Val: S)))
510 SCEVToInsts[S].insert(X: cast<Instruction>(Val: V));
511
512 return S;
513 }
514
515 bool candidatePredicate(Candidate *Basis, Candidate &C, Candidate::DKind K);
516
517 bool hasSameSCEVUnknowns(const SCEV *A, const SCEV *B);
518
519 bool searchFrom(const CandidateDictTy::BBToCandsTy &BBToCands, Candidate &C,
520 Candidate::DKind K);
521
522 // Get the nearest instruction before CI that represents the value of S,
523 // return nullptr if no instruction is associated with S or S is not a
524 // reusable expression.
525 Value *getNearestValueOfSCEV(const SCEV *S, const Instruction *CI) const {
526 if (isa<SCEVCouldNotCompute>(Val: S))
527 return nullptr;
528
529 if (auto *SU = dyn_cast<SCEVUnknown>(Val: S))
530 return SU->getValue();
531 if (auto *SC = dyn_cast<SCEVConstant>(Val: S))
532 return SC->getValue();
533
534 auto It = SCEVToInsts.find(Val: S);
535 if (It == SCEVToInsts.end())
536 return nullptr;
537
538 // Instructions are sorted in depth-first order, so search for the nearest
539 // instruction by walking the list in reverse order.
540 for (Instruction *I : reverse(C: It->second))
541 if (DT->dominates(Def: I, User: CI))
542 return I;
543
544 return nullptr;
545 }
546
547 struct DeltaInfo {
548 Candidate *Cand;
549 Candidate::DKind DeltaKind;
550 Value *Delta;
551
552 DeltaInfo()
553 : Cand(nullptr), DeltaKind(Candidate::InvalidDelta), Delta(nullptr) {}
554 DeltaInfo(Candidate *Cand, Candidate::DKind DeltaKind, Value *Delta)
555 : Cand(Cand), DeltaKind(DeltaKind), Delta(Delta) {}
556 operator bool() const { return Cand != nullptr; }
557 };
558
559 friend raw_ostream &operator<<(raw_ostream &OS, const DeltaInfo &DI);
560
561 DeltaInfo compressPath(Candidate &C, Candidate *Basis) const;
562
563 Candidate *pickRewriteCandidate(Instruction *I) const;
564 void sortCandidateInstructions();
565 Value *getDelta(const Candidate &C, const Candidate &Basis,
566 Candidate::DKind K) const;
567 static bool isSimilar(Candidate &C, Candidate &Basis, Candidate::DKind K);
568
569 // Add Basis -> C in DependencyGraph and propagate
570 // C.Stride and C.Delta's dependency to C
571 void addDependency(Candidate &C, Candidate *Basis) {
572 if (Basis)
573 DependencyGraph[Basis->Ins].emplace_back(args&: C.Ins);
574
575 // If any candidate of Inst has a basis, then Inst will be rewritten,
576 // C must be rewritten after rewriting Inst, so we need to propagate
577 // the dependency to C
578 auto PropagateDependency = [&](Instruction *Inst) {
579 if (auto CandsIt = RewriteCandidates.find(Val: Inst);
580 CandsIt != RewriteCandidates.end() &&
581 llvm::any_of(Range&: CandsIt->second,
582 P: [](Candidate *Cand) { return Cand->Basis; }))
583 DependencyGraph[Inst].emplace_back(args&: C.Ins);
584 };
585
586 // If C has a variable delta and the delta is a candidate,
587 // propagate its dependency to C
588 if (auto *DeltaInst = dyn_cast_or_null<Instruction>(Val: C.Delta))
589 PropagateDependency(DeltaInst);
590
591 // If the stride is a candidate, propagate its dependency to C
592 if (auto *StrideInst = dyn_cast<Instruction>(Val: C.Stride))
593 PropagateDependency(StrideInst);
594 };
595};
596
597inline raw_ostream &operator<<(raw_ostream &OS,
598 const StraightLineStrengthReduce::Candidate &C) {
599 OS << "Ins: " << *C.Ins << "\n Base: " << *C.Base
600 << "\n Index: " << *C.Index << "\n Stride: " << *C.Stride
601 << "\n StrideSCEV: " << *C.StrideSCEV;
602 if (C.Basis)
603 OS << "\n Delta: " << *C.Delta << "\n Basis: \n [ " << *C.Basis << " ]";
604 return OS;
605}
606
607[[maybe_unused]] LLVM_DUMP_METHOD inline raw_ostream &
608operator<<(raw_ostream &OS, const StraightLineStrengthReduce::DeltaInfo &DI) {
609 OS << "Cand: " << *DI.Cand << "\n";
610 OS << "Delta Kind: ";
611 switch (DI.DeltaKind) {
612 case StraightLineStrengthReduce::Candidate::IndexDelta:
613 OS << "Index";
614 break;
615 case StraightLineStrengthReduce::Candidate::BaseDelta:
616 OS << "Base";
617 break;
618 case StraightLineStrengthReduce::Candidate::StrideDelta:
619 OS << "Stride";
620 break;
621 default:
622 break;
623 }
624 OS << "\nDelta: " << *DI.Delta;
625 return OS;
626}
627
628} // end anonymous namespace
629
630char StraightLineStrengthReduceLegacyPass::ID = 0;
631
632INITIALIZE_PASS_BEGIN(StraightLineStrengthReduceLegacyPass, "slsr",
633 "Straight line strength reduction", false, false)
634INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
635INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
636INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
637INITIALIZE_PASS_END(StraightLineStrengthReduceLegacyPass, "slsr",
638 "Straight line strength reduction", false, false)
639
640FunctionPass *llvm::createStraightLineStrengthReducePass() {
641 return new StraightLineStrengthReduceLegacyPass();
642}
643
644// A helper function that unifies the bitwidth of A and B.
645static void unifyBitWidth(APInt &A, APInt &B) {
646 if (A.getBitWidth() < B.getBitWidth())
647 A = A.sext(width: B.getBitWidth());
648 else if (A.getBitWidth() > B.getBitWidth())
649 B = B.sext(width: A.getBitWidth());
650}
651
652// Whether sign-extending V to a wider type may not distribute over arithmetic,
653// i.e. the narrow value does not sign-extend linearly. Only an add/sub/mul/shl
654// carrying the `nsw` flag is known to sign-extend linearly; anything else is
655// treated conservatively as possibly wrapping. This notably covers
656// `xor X, signmask`, which merely flips the sign bit but ScalarEvolution models
657// as a non-nsw `add X, signmask` (so sext does not distribute over it).
658static bool mayHaveSignedWrap(const Value *V) {
659 // OverflowingBinaryOperator covers exactly add/sub/mul/shl.
660 const auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: V);
661 return !OBO || !OBO->hasNoSignedWrap();
662}
663
664// True when the GEP index is narrower than the index width, i.e. it is
665// implicitly sign-extended to the index width (not the pointer width) of the
666// address space before the address computation. A value already at or wider
667// than the index width is not sign-extended (it is used as-is or truncated), so
668// it cannot trigger the non-distributing-sext problem.
669static bool isSignExtendedGepIndex(const Value *Idx, GetElementPtrInst *GEP,
670 const DataLayout *DL) {
671 return Idx->getType()->getIntegerBitWidth() <
672 DL->getIndexSizeInBits(AS: GEP->getAddressSpace());
673}
674
675// A narrow GEP index is sign-extended to the index width before the address
676// computation. SLSR's Stride-delta rewrite turns two such GEPs into
677// Basis + Index * (Sc - Sb), so the stride difference Sc - Sb is reconstructed
678// in the sign-extended domain. This requires sext(Sc) == sext(Sb) +
679// sext(Delta).
680//
681// This screens the rewritten candidate's stride Sc = Sb + Delta: if Sc is
682// computed by a possibly-wrapping op, sext(Sc) does not equal sext(Sb) +
683// sext(Delta) and the rewrite would produce a wrong pointer.
684static bool isSafeToFactorGepIndex(const Value *Idx, GetElementPtrInst *GEP,
685 const DataLayout *DL) {
686 return !isSignExtendedGepIndex(Idx, GEP, DL) || !mayHaveSignedWrap(V: Idx);
687}
688
689Value *StraightLineStrengthReduce::getDelta(const Candidate &C,
690 const Candidate &Basis,
691 Candidate::DKind K) const {
692 if (K == Candidate::IndexDelta) {
693 APInt Idx = C.Index->getValue();
694 APInt BasisIdx = Basis.Index->getValue();
695 unifyBitWidth(A&: Idx, B&: BasisIdx);
696 APInt IndexDelta = Idx - BasisIdx;
697 IntegerType *DeltaType =
698 IntegerType::get(C&: C.Ins->getContext(), NumBits: IndexDelta.getBitWidth());
699 return ConstantInt::get(Ty: DeltaType, V: IndexDelta);
700 } else if (K == Candidate::BaseDelta || K == Candidate::StrideDelta) {
701 const SCEV *BasisPart =
702 (K == Candidate::BaseDelta) ? Basis.Base : Basis.StrideSCEV;
703 const SCEV *CandPart = (K == Candidate::BaseDelta) ? C.Base : C.StrideSCEV;
704 ++NumSCEVCandidateBasisDifferences;
705 const SCEV *Diff = SE->getMinusSCEV(LHS: CandPart, RHS: BasisPart);
706 return getNearestValueOfSCEV(S: Diff, CI: C.Ins);
707 }
708 return nullptr;
709}
710
711bool StraightLineStrengthReduce::isSimilar(Candidate &C, Candidate &Basis,
712 Candidate::DKind K) {
713 bool SameType = false;
714 switch (K) {
715 case Candidate::StrideDelta:
716 SameType = C.StrideSCEV->getType() == Basis.StrideSCEV->getType();
717 break;
718 case Candidate::BaseDelta:
719 SameType = C.Base->getType() == Basis.Base->getType();
720 break;
721 case Candidate::IndexDelta:
722 SameType = true;
723 break;
724 default:;
725 }
726 return SameType && Basis.Ins != C.Ins &&
727 Basis.CandidateKind == C.CandidateKind;
728}
729
730bool StraightLineStrengthReduce::hasSameSCEVUnknowns(const SCEV *A,
731 const SCEV *B) {
732 auto CacheUnknowns = [&](const SCEV *Root) {
733 auto [It, Inserted] = SCEVUnknownsCache.try_emplace(Key: Root);
734 if (!Inserted)
735 return;
736
737 struct Collector {
738 SCEVUnknownSet &Unknowns;
739
740 bool follow(const SCEV *S) {
741 if (auto *Unknown = dyn_cast<SCEVUnknown>(Val: S))
742 Unknowns.insert(Ptr: Unknown);
743 return true;
744 }
745 bool isDone() const { return false; }
746 } C{.Unknowns: It->second};
747 visitAll(Root, Visitor&: C);
748 };
749 CacheUnknowns(A);
750 CacheUnknowns(B);
751
752 return SCEVUnknownsCache.find(Val: A)->second == SCEVUnknownsCache.find(Val: B)->second;
753}
754
755// Try to find a Delta that C can reuse Basis to rewrite.
756// Set C.Delta, C.Basis, and C.DeltaKind if found.
757// Return true if found a constant delta.
758// Return false if not found or the delta is not a constant.
759bool StraightLineStrengthReduce::candidatePredicate(Candidate *Basis,
760 Candidate &C,
761 Candidate::DKind K) {
762 if (!isSimilar(C, Basis&: *Basis, K))
763 return false;
764
765 // Once a reusable delta is found, only a constant delta can improve it.
766 // Different symbolic leaves cannot cancel to a constant, so such a basis
767 // cannot improve C. Skip it and continue searching older candidates.
768 if (C.Delta && K != Candidate::IndexDelta) {
769 const SCEV *CandidateSCEV =
770 K == Candidate::BaseDelta ? C.Base : C.StrideSCEV;
771 const SCEV *BasisSCEV =
772 K == Candidate::BaseDelta ? Basis->Base : Basis->StrideSCEV;
773 if (!hasSameSCEVUnknowns(A: CandidateSCEV, B: BasisSCEV))
774 return false;
775 }
776
777 assert(DT->dominates(Basis->Ins, C.Ins));
778 Value *Delta = getDelta(C, Basis: *Basis, K);
779 if (!Delta)
780 return false;
781
782 // For a GEP Stride-delta rewrite g2 = g1 + Index * Delta, the addresses are
783 // computed from the sign-extended strides, so this requires
784 // sext(Sc) == sext(Sb) + sext(Delta).
785 //
786 // The rewritten candidate's stride Sc = Sb + Delta is already screened
787 // broadly at allocation time (allocateCandidatesAndFindBasis): a wrapping Sc
788 // breaks the identity for any Delta. The basis's stride Sb = Sc - Delta only
789 // needs screening when Delta folds to a *constant*: then sext(Sb) + C can
790 // differ from sext(Sc) if Sb wraps. For a *variable* Delta the basis may wrap
791 // and still be sound, because the candidate stride carries the no-wrap
792 // guarantee (e.g. Sc is an `add nsw`, as in stride_var); rejecting it would
793 // pessimize those.
794 if (K == Candidate::StrideDelta && C.CandidateKind == Candidate::GEP &&
795 isa<ConstantInt>(Val: Delta)) {
796 auto *BasisGEP = cast<GetElementPtrInst>(Val: Basis->Ins);
797 if (!isSafeToFactorGepIndex(Idx: Basis->Stride, GEP: BasisGEP, DL))
798 return false;
799 }
800
801 // IndexDelta rewrite is not always profitable, e.g.,
802 // X = B + 8 * S
803 // Y = B + S,
804 // rewriting Y to X - 7 * S is probably a bad idea.
805 // So, we need to check if the rewrite form's computation efficiency
806 // is better than the original form.
807 if (K == Candidate::IndexDelta &&
808 !C.isProfitableRewrite(Delta: *Delta, DeltaKind: Candidate::IndexDelta))
809 return false;
810
811 // Record delta if none has been found yet, or the new delta is
812 // a constant that is better than the existing delta.
813 if (!C.Delta || isa<ConstantInt>(Val: Delta)) {
814 C.Delta = Delta;
815 C.Basis = Basis;
816 C.DeltaKind = K;
817 }
818 return isa<ConstantInt>(Val: C.Delta);
819}
820
821// return true if find a Basis with constant delta and stop searching,
822// return false if did not find a Basis or the delta is not a constant
823// and continue searching for a Basis with constant delta
824bool StraightLineStrengthReduce::searchFrom(
825 const CandidateDictTy::BBToCandsTy &BBToCands, Candidate &C,
826 Candidate::DKind K) {
827
828 // Stride delta rewrite on Mul form is usually non-profitable, and Base
829 // delta rewrite sometimes is profitable, so we do not support them on Mul.
830 if (C.CandidateKind == Candidate::Mul && K != Candidate::IndexDelta)
831 return false;
832
833 // Search dominating candidates by walking the immediate-dominator chain
834 // from the candidate's defining block upward. Visiting blocks in this
835 // order ensures we prefer the closest dominating basis.
836 const BasicBlock *BB = C.Ins->getParent();
837 while (BB) {
838 auto It = BBToCands.find(Val: BB);
839 if (It != BBToCands.end())
840 for (Candidate *Basis : reverse(C: It->second))
841 if (candidatePredicate(Basis, C, K))
842 return true;
843
844 const DomTreeNode *Node = DT->getNode(BB);
845 if (!Node)
846 break;
847 Node = Node->getIDom();
848 BB = Node ? Node->getBlock() : nullptr;
849 }
850 return false;
851}
852
853void StraightLineStrengthReduce::setBasisAndDeltaFor(Candidate &C) {
854 if (const auto *BaseDeltaCandidates =
855 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::BaseDelta))
856 if (searchFrom(BBToCands: *BaseDeltaCandidates, C, K: Candidate::BaseDelta)) {
857 LLVM_DEBUG(dbgs() << "Found delta from Base: " << *C.Delta << "\n");
858 return;
859 }
860
861 if (const auto *StrideDeltaCandidates =
862 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::StrideDelta))
863 if (searchFrom(BBToCands: *StrideDeltaCandidates, C, K: Candidate::StrideDelta)) {
864 LLVM_DEBUG(dbgs() << "Found delta from Stride: " << *C.Delta << "\n");
865 return;
866 }
867
868 if (const auto *IndexDeltaCandidates =
869 CandidateDict.getCandidatesWithDeltaKind(C, K: Candidate::IndexDelta))
870 if (searchFrom(BBToCands: *IndexDeltaCandidates, C, K: Candidate::IndexDelta)) {
871 LLVM_DEBUG(dbgs() << "Found delta from Index: " << *C.Delta << "\n");
872 return;
873 }
874
875 // If we did not find a constant delta, we might have found a variable delta
876 if (C.Delta) {
877 LLVM_DEBUG({
878 dbgs() << "Found delta from ";
879 if (C.DeltaKind == Candidate::BaseDelta)
880 dbgs() << "Base: ";
881 else
882 dbgs() << "Stride: ";
883 dbgs() << *C.Delta << "\n";
884 });
885 assert(C.DeltaKind != Candidate::InvalidDelta && C.Basis);
886 }
887}
888
889// Compress the path from `Basis` to the deepest Basis in the Basis chain
890// to avoid non-profitable data dependency and improve ILP.
891// X = A + 1
892// Y = X + 1
893// Z = Y + 1
894// ->
895// X = A + 1
896// Y = A + 2
897// Z = A + 3
898// Return the delta info for C aginst the new Basis
899auto StraightLineStrengthReduce::compressPath(Candidate &C,
900 Candidate *Basis) const
901 -> DeltaInfo {
902 if (!Basis || !Basis->Basis || C.CandidateKind == Candidate::Mul)
903 return {};
904 Candidate *Root = Basis;
905 Value *NewDelta = nullptr;
906 auto NewKind = Candidate::InvalidDelta;
907
908 while (Root->Basis) {
909 Candidate *NextRoot = Root->Basis;
910 if (C.Base == NextRoot->Base && C.StrideSCEV == NextRoot->StrideSCEV &&
911 isSimilar(C, Basis&: *NextRoot, K: Candidate::IndexDelta)) {
912 ConstantInt *CI =
913 cast<ConstantInt>(Val: getDelta(C, Basis: *NextRoot, K: Candidate::IndexDelta));
914 if (CI->isZero() || CI->isOne() || isa<SCEVConstant>(Val: C.StrideSCEV)) {
915 Root = NextRoot;
916 NewKind = Candidate::IndexDelta;
917 NewDelta = CI;
918 continue;
919 }
920 }
921
922 const SCEV *CandPart = nullptr;
923 const SCEV *BasisPart = nullptr;
924 auto CurrKind = Candidate::InvalidDelta;
925 if (C.Base == NextRoot->Base && C.Index == NextRoot->Index) {
926 CandPart = C.StrideSCEV;
927 BasisPart = NextRoot->StrideSCEV;
928 CurrKind = Candidate::StrideDelta;
929 } else if (C.StrideSCEV == NextRoot->StrideSCEV &&
930 C.Index == NextRoot->Index) {
931 CandPart = C.Base;
932 BasisPart = NextRoot->Base;
933 CurrKind = Candidate::BaseDelta;
934 } else
935 break;
936
937 assert(CandPart && BasisPart);
938 if (!isSimilar(C, Basis&: *NextRoot, K: CurrKind))
939 break;
940
941 // Path compression folds a constant Stride-delta directly against the
942 // deeper basis NextRoot, bypassing candidatePredicate's wrap guard. With a
943 // constant delta sext(Sb) + C can differ from sext(Sc) if the deeper
944 // basis's stride wraps, so do not compress past such a basis (mirrors the
945 // check in candidatePredicate).
946 if (CurrKind == Candidate::StrideDelta &&
947 C.CandidateKind == Candidate::GEP &&
948 !isSafeToFactorGepIndex(Idx: NextRoot->Stride,
949 GEP: cast<GetElementPtrInst>(Val: NextRoot->Ins), DL))
950 break;
951
952 ++NumSCEVCandidateBasisDifferences;
953 if (auto DeltaVal =
954 dyn_cast<SCEVConstant>(Val: SE->getMinusSCEV(LHS: CandPart, RHS: BasisPart))) {
955 Root = NextRoot;
956 NewDelta = DeltaVal->getValue();
957 NewKind = CurrKind;
958 } else
959 break;
960 }
961
962 if (Root != Basis) {
963 assert(NewKind != Candidate::InvalidDelta && NewDelta);
964 LLVM_DEBUG(dbgs() << "Found new Basis with " << *NewDelta
965 << " from path compression.\n");
966 return {Root, NewKind, NewDelta};
967 }
968
969 return {};
970}
971
972// Topologically sort candidate instructions based on their relationship in
973// dependency graph.
974void StraightLineStrengthReduce::sortCandidateInstructions() {
975 SortedCandidateInsts.clear();
976 // An instruction may have multiple candidates that get different Basis
977 // instructions, and each candidate can get dependencies from Basis and
978 // Stride when Stride will also be rewritten by SLSR. Hence, an instruction
979 // may have multiple dependencies. Use InDegree to ensure all dependencies
980 // processed before processing itself.
981 DenseMap<Instruction *, int> InDegree;
982 for (auto &KV : DependencyGraph) {
983 InDegree.try_emplace(Key: KV.first, Args: 0);
984
985 for (auto *Child : KV.second) {
986 InDegree[Child]++;
987 }
988 }
989 std::queue<Instruction *> WorkList;
990 DenseSet<Instruction *> Visited;
991
992 for (auto &KV : DependencyGraph)
993 if (InDegree[KV.first] == 0)
994 WorkList.push(x: KV.first);
995
996 while (!WorkList.empty()) {
997 Instruction *I = WorkList.front();
998 WorkList.pop();
999 if (!Visited.insert(V: I).second)
1000 continue;
1001
1002 SortedCandidateInsts.push_back(x: I);
1003
1004 for (auto *Next : DependencyGraph[I]) {
1005 auto &Degree = InDegree[Next];
1006 if (--Degree == 0)
1007 WorkList.push(x: Next);
1008 }
1009 }
1010
1011 assert(SortedCandidateInsts.size() == DependencyGraph.size() &&
1012 "Dependency graph should not have cycles");
1013}
1014
1015auto StraightLineStrengthReduce::pickRewriteCandidate(Instruction *I) const
1016 -> Candidate * {
1017 // Return the candidate of instruction I that has the highest profit.
1018 auto It = RewriteCandidates.find(Val: I);
1019 if (It == RewriteCandidates.end())
1020 return nullptr;
1021
1022 Candidate *BestC = nullptr;
1023 auto BestEfficiency = Candidate::Unknown;
1024 for (Candidate *C : reverse(C: It->second))
1025 if (C->Basis) {
1026 auto Efficiency = C->getRewriteEfficiency();
1027 if (Efficiency > BestEfficiency) {
1028 BestEfficiency = Efficiency;
1029 BestC = C;
1030 }
1031 }
1032
1033 return BestC;
1034}
1035
1036static bool isGEPFoldable(GetElementPtrInst *GEP,
1037 const TargetTransformInfo *TTI) {
1038 SmallVector<const Value *, 4> Indices(GEP->indices());
1039 return TTI->getGEPCost(
1040 PointeeType: GEP->getSourceElementType(), Ptr: GEP->getPointerOperand(), Operands: Indices,
1041 /*CostKind*/ TTI::TargetCostKind::TCK_SizeAndLatency) ==
1042 TargetTransformInfo::TCC_Free;
1043}
1044
1045// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
1046static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
1047 TargetTransformInfo *TTI) {
1048 // Index->getSExtValue() may crash if Index is wider than 64-bit.
1049 return Index->getBitWidth() <= 64 &&
1050 TTI->isLegalAddressingMode(Ty: Base->getType(), BaseGV: nullptr, BaseOffset: 0, HasBaseReg: true,
1051 Scale: Index->getSExtValue(), AddrSpace: UnknownAddressSpace);
1052}
1053
1054bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
1055 TargetTransformInfo *TTI) {
1056 if (C.CandidateKind == Candidate::Add)
1057 return isAddFoldable(Base: C.Base, Index: C.Index, Stride: C.Stride, TTI);
1058 if (C.CandidateKind == Candidate::GEP)
1059 return isGEPFoldable(GEP: cast<GetElementPtrInst>(Val: C.Ins), TTI);
1060 return false;
1061}
1062
1063void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1064 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
1065 Instruction *I) {
1066 bool IsSafe = CT != Candidate::GEP ||
1067 isSafeToFactorGepIndex(Idx: S, GEP: cast<GetElementPtrInst>(Val: I), DL);
1068 // Record the SCEV of S that we may use it as a variable delta.
1069 // Ensure that we rewrite C with a existing IR that reproduces delta value.
1070
1071 Candidate C(CT, B, Idx, S, I, getAndRecordSCEV(V: S));
1072 // If we can fold I into an addressing mode, computing I is likely free or
1073 // takes only one instruction. So, we don't need to analyze or rewrite it.
1074 //
1075 // Currently, this algorithm can at best optimize complex computations into
1076 // a `variable +/* constant` form. However, some targets have stricter
1077 // constraints on the their addressing mode.
1078 // For example, a `variable + constant` can only be folded to an addressing
1079 // mode if the constant falls within a certain range.
1080 // So, we also check if the instruction is already high efficient enough
1081 // for the strength reduction algorithm.
1082 if (IsSafe && !isFoldable(C, TTI) && !C.isHighEfficiency()) {
1083 setBasisAndDeltaFor(C);
1084
1085 // Compress unnecessary rewrite to improve ILP
1086 if (auto Res = compressPath(C, Basis: C.Basis)) {
1087 C.Basis = Res.Cand;
1088 C.DeltaKind = Res.DeltaKind;
1089 C.Delta = Res.Delta;
1090 }
1091 }
1092 // Regardless of whether we find a basis for C, we need to push C to the
1093 // candidate list so that it can be the basis of other candidates.
1094 LLVM_DEBUG(dbgs() << "Allocated Candidate: " << C << "\n");
1095 Candidates.push_back(x: C);
1096 RewriteCandidates[C.Ins].push_back(Elt: &Candidates.back());
1097 // Only add to the dict if this instruction is safe to reuse as a basis. By
1098 // doing this early we avoid calling canReuseInstruction repeatedly for the
1099 // same instruction. The DropList is stored on the Candidate so the flags can
1100 // be dropped only if this candidate is used by an executed rewrite.
1101 if (!EnablePoisonReuseGuard ||
1102 SE->canReuseInstruction(S: SE->getSCEV(V: I), I, DropPoisonGeneratingInsts&: Candidates.back().DropList)) {
1103 CandidateDict.add(C&: Candidates.back());
1104 }
1105}
1106
1107void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1108 Instruction *I) {
1109 switch (I->getOpcode()) {
1110 case Instruction::Add:
1111 allocateCandidatesAndFindBasisForAdd(I);
1112 break;
1113 case Instruction::Mul:
1114 allocateCandidatesAndFindBasisForMul(I);
1115 break;
1116 case Instruction::GetElementPtr:
1117 allocateCandidatesAndFindBasisForGEP(GEP: cast<GetElementPtrInst>(Val: I));
1118 break;
1119 }
1120}
1121
1122void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1123 Instruction *I) {
1124 // Try matching B + i * S.
1125 if (!isa<IntegerType>(Val: I->getType()))
1126 return;
1127
1128 assert(I->getNumOperands() == 2 && "isn't I an add?");
1129 Value *LHS = I->getOperand(i: 0), *RHS = I->getOperand(i: 1);
1130 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
1131 if (LHS != RHS)
1132 allocateCandidatesAndFindBasisForAdd(LHS: RHS, RHS: LHS, I);
1133}
1134
1135void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1136 Value *LHS, Value *RHS, Instruction *I) {
1137 Value *S = nullptr;
1138 ConstantInt *Idx = nullptr;
1139 if (match(V: RHS, P: m_Mul(L: m_Value(V&: S), R: m_ConstantInt(CI&: Idx)))) {
1140 // I = LHS + RHS = LHS + Idx * S
1141 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx, S, I);
1142 } else if (match(V: RHS, P: m_Shl(L: m_Value(V&: S), R: m_ConstantInt(CI&: Idx)))) {
1143 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
1144 APInt One(Idx->getBitWidth(), 1);
1145 Idx = ConstantInt::get(Context&: Idx->getContext(), V: One << Idx->getValue());
1146 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx, S, I);
1147 } else {
1148 // At least, I = LHS + 1 * RHS
1149 ConstantInt *One = ConstantInt::get(Ty: cast<IntegerType>(Val: I->getType()), V: 1);
1150 allocateCandidatesAndFindBasis(CT: Candidate::Add, B: SE->getSCEV(V: LHS), Idx: One, S: RHS,
1151 I);
1152 }
1153}
1154
1155// Returns true if A matches B + C where C is constant.
1156static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
1157 return match(V: A, P: m_c_Add(L: m_Value(V&: B), R: m_ConstantInt(CI&: C)));
1158}
1159
1160// Returns true if A matches B | C where C is constant.
1161static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
1162 return match(V: A, P: m_c_Or(L: m_Value(V&: B), R: m_ConstantInt(CI&: C)));
1163}
1164
1165void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1166 Value *LHS, Value *RHS, Instruction *I) {
1167 Value *B = nullptr;
1168 ConstantInt *Idx = nullptr;
1169 if (matchesAdd(A: LHS, B, C&: Idx)) {
1170 // If LHS is in the form of "Base + Index", then I is in the form of
1171 // "(Base + Index) * RHS".
1172 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: B), Idx, S: RHS, I);
1173 } else if (matchesOr(A: LHS, B, C&: Idx) && haveNoCommonBitsSet(LHSCache: B, RHSCache: Idx, SQ: *DL)) {
1174 // If LHS is in the form of "Base | Index" and Base and Index have no common
1175 // bits set, then
1176 // Base | Index = Base + Index
1177 // and I is thus in the form of "(Base + Index) * RHS".
1178 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: B), Idx, S: RHS, I);
1179 } else {
1180 // Otherwise, at least try the form (LHS + 0) * RHS.
1181 ConstantInt *Zero = ConstantInt::get(Ty: cast<IntegerType>(Val: I->getType()), V: 0);
1182 allocateCandidatesAndFindBasis(CT: Candidate::Mul, B: SE->getSCEV(V: LHS), Idx: Zero, S: RHS,
1183 I);
1184 }
1185}
1186
1187void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1188 Instruction *I) {
1189 // Try matching (B + i) * S.
1190 // TODO: we could extend SLSR to float and vector types.
1191 if (!isa<IntegerType>(Val: I->getType()))
1192 return;
1193
1194 assert(I->getNumOperands() == 2 && "isn't I a mul?");
1195 Value *LHS = I->getOperand(i: 0), *RHS = I->getOperand(i: 1);
1196 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
1197 if (LHS != RHS) {
1198 // Symmetrically, try to split RHS to Base + Index.
1199 allocateCandidatesAndFindBasisForMul(LHS: RHS, RHS: LHS, I);
1200 }
1201}
1202
1203void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
1204 GetElementPtrInst *GEP) {
1205 // TODO: handle vector GEPs
1206 if (GEP->getType()->isVectorTy())
1207 return;
1208
1209 SmallVector<SCEVUse, 4> IndexExprs;
1210 for (Use &Idx : GEP->indices())
1211 IndexExprs.push_back(Elt: SE->getSCEV(V: Idx));
1212
1213 gep_type_iterator GTI = gep_type_begin(GEP);
1214 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1215 if (GTI.isStruct())
1216 continue;
1217
1218 SCEVUse OrigIndexExpr = IndexExprs[I - 1];
1219 IndexExprs[I - 1] = SE->getZero(Ty: OrigIndexExpr.getPointer()->getType());
1220
1221 // The base of this candidate is GEP's base plus the offsets of all
1222 // indices except this current one.
1223 SCEVUse BaseExpr = SE->getGEPExpr(GEP: cast<GEPOperator>(Val: GEP), IndexExprs);
1224 Value *ArrayIdx = GEP->getOperand(i_nocapture: I);
1225 uint64_t ElementSize = GTI.getSequentialElementStride(DL: *DL);
1226 IntegerType *PtrIdxTy = cast<IntegerType>(Val: DL->getIndexType(PtrTy: GEP->getType()));
1227 // If the element size overflows the type, truncate.
1228 ConstantInt *ElementSizeIdx =
1229 ConstantInt::getSigned(Ty: PtrIdxTy, V: ElementSize, /*ImplicitTrunc=*/true);
1230 if (ArrayIdx->getType()->getIntegerBitWidth() <=
1231 DL->getIndexSizeInBits(AS: GEP->getAddressSpace())) {
1232 // Skip factoring if ArrayIdx is wider than the index size, because
1233 // ArrayIdx is implicitly truncated to the index size.
1234 allocateCandidatesAndFindBasis(CT: Candidate::GEP, B: BaseExpr, Idx: ElementSizeIdx,
1235 S: ArrayIdx, I: GEP);
1236 }
1237 // When ArrayIdx is the sext of a value, we try to factor that value as
1238 // well. Handling this case is important because array indices are
1239 // typically sign-extended to the pointer index size.
1240 Value *TruncatedArrayIdx = nullptr;
1241 if (match(V: ArrayIdx, P: m_SExt(Op: m_Value(V&: TruncatedArrayIdx))) &&
1242 TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
1243 DL->getIndexSizeInBits(AS: GEP->getAddressSpace())) {
1244 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
1245 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
1246 allocateCandidatesAndFindBasis(CT: Candidate::GEP, B: BaseExpr, Idx: ElementSizeIdx,
1247 S: TruncatedArrayIdx, I: GEP);
1248 }
1249
1250 IndexExprs[I - 1] = OrigIndexExpr;
1251 }
1252}
1253
1254Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
1255 const Candidate &C,
1256 IRBuilder<> &Builder,
1257 const DataLayout *DL) {
1258 auto CreateMul = [&](Value *LHS, Value *RHS) {
1259 if (ConstantInt *CR = dyn_cast<ConstantInt>(Val: RHS)) {
1260 const APInt &ConstRHS = CR->getValue();
1261 IntegerType *DeltaType =
1262 IntegerType::get(C&: C.Ins->getContext(), NumBits: ConstRHS.getBitWidth());
1263 if (ConstRHS.isPowerOf2()) {
1264 ConstantInt *Exponent =
1265 ConstantInt::get(Ty: DeltaType, V: ConstRHS.logBase2());
1266 return Builder.CreateShl(LHS, RHS: Exponent);
1267 }
1268 if (ConstRHS.isNegatedPowerOf2()) {
1269 ConstantInt *Exponent =
1270 ConstantInt::get(Ty: DeltaType, V: (-ConstRHS).logBase2());
1271 return Builder.CreateNeg(V: Builder.CreateShl(LHS, RHS: Exponent));
1272 }
1273 }
1274
1275 return Builder.CreateMul(LHS, RHS);
1276 };
1277
1278 Value *Delta = C.Delta;
1279 // If Delta is 0, C is a fully redundant of C.Basis,
1280 // just replace C.Ins with Basis.Ins
1281 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Delta);
1282 CI && CI->getValue().isZero())
1283 return nullptr;
1284
1285 if (C.DeltaKind == Candidate::IndexDelta) {
1286 APInt IndexDelta = cast<ConstantInt>(Val: C.Delta)->getValue();
1287 // IndexDelta
1288 // X = B + i * S
1289 // Y = B + i` * S
1290 // = B + (i + IndexDelta) * S
1291 // = B + i * S + IndexDelta * S
1292 // = X + IndexDelta * S
1293 // Bump = (i' - i) * S
1294
1295 // Common case 1: if (i' - i) is 1, Bump = S.
1296 if (IndexDelta == 1)
1297 return C.Stride;
1298 // Common case 2: if (i' - i) is -1, Bump = -S.
1299 if (IndexDelta.isAllOnes())
1300 return Builder.CreateNeg(V: C.Stride);
1301
1302 IntegerType *DeltaType =
1303 IntegerType::get(C&: Basis.Ins->getContext(), NumBits: IndexDelta.getBitWidth());
1304 Value *ExtendedStride = Builder.CreateSExtOrTrunc(V: C.Stride, DestTy: DeltaType);
1305
1306 return CreateMul(ExtendedStride, C.Delta);
1307 }
1308
1309 assert(C.DeltaKind == Candidate::StrideDelta ||
1310 C.DeltaKind == Candidate::BaseDelta);
1311 assert(C.CandidateKind != Candidate::Mul);
1312 // StrideDelta
1313 // X = B + i * S
1314 // Y = B + i * S'
1315 // = B + i * (S + StrideDelta)
1316 // = B + i * S + i * StrideDelta
1317 // = X + i * StrideDelta
1318 // Bump = i * (S' - S)
1319 //
1320 // BaseDelta
1321 // X = B + i * S
1322 // Y = B' + i * S
1323 // = (B + BaseDelta) + i * S
1324 // = X + BaseDelta
1325 // Bump = (B' - B).
1326 Value *Bump = C.Delta;
1327 if (C.DeltaKind == Candidate::StrideDelta) {
1328 // If this value is consumed by a GEP, promote StrideDelta before doing
1329 // StrideDelta * Index to ensure the same semantics as the original GEP.
1330 if (C.CandidateKind == Candidate::GEP) {
1331 auto *GEP = cast<GetElementPtrInst>(Val: C.Ins);
1332 Type *NewScalarIndexTy =
1333 DL->getIndexType(PtrTy: GEP->getPointerOperandType()->getScalarType());
1334 Bump = Builder.CreateSExtOrTrunc(V: Bump, DestTy: NewScalarIndexTy);
1335 }
1336 if (!C.Index->isOne()) {
1337 Value *ExtendedIndex =
1338 Builder.CreateSExtOrTrunc(V: C.Index, DestTy: Bump->getType());
1339 Bump = CreateMul(Bump, ExtendedIndex);
1340 }
1341 }
1342 return Bump;
1343}
1344
1345void StraightLineStrengthReduce::rewriteCandidate(const Candidate &C) {
1346 if (!DebugCounter::shouldExecute(Counter&: StraightLineStrengthReduceCounter))
1347 return;
1348
1349 const Candidate &Basis = *C.Basis;
1350 assert(C.Delta && C.CandidateKind == Basis.CandidateKind &&
1351 C.hasValidDelta(Basis));
1352
1353 for (Instruction *I : Basis.DropList)
1354 I->dropPoisonGeneratingAnnotations();
1355
1356 IRBuilder<> Builder(C.Ins);
1357 Value *Bump = emitBump(Basis, C, Builder, DL);
1358 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
1359 // If delta is 0, C is a fully redundant of Basis, and Bump is nullptr,
1360 // just replace C.Ins with Basis.Ins
1361 if (!Bump)
1362 Reduced = Basis.Ins;
1363 else {
1364 switch (C.CandidateKind) {
1365 case Candidate::Add:
1366 case Candidate::Mul: {
1367 // C = Basis + Bump
1368 Value *NegBump;
1369 if (match(V: Bump, P: m_Neg(V: m_Value(V&: NegBump)))) {
1370 // If Bump is a neg instruction, emit C = Basis - (-Bump).
1371 Reduced = Builder.CreateSub(LHS: Basis.Ins, RHS: NegBump);
1372 // We only use the negative argument of Bump, and Bump itself may be
1373 // trivially dead.
1374 RecursivelyDeleteTriviallyDeadInstructions(V: Bump);
1375 } else {
1376 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
1377 // usually unsound, e.g.,
1378 //
1379 // X = (-2 +nsw 1) *nsw INT_MAX
1380 // Y = (-2 +nsw 3) *nsw INT_MAX
1381 // =>
1382 // Y = X + 2 * INT_MAX
1383 //
1384 // Neither + and * in the resultant expression are nsw.
1385 Reduced = Builder.CreateAdd(LHS: Basis.Ins, RHS: Bump);
1386 }
1387 break;
1388 }
1389 case Candidate::GEP: {
1390 bool InBounds = cast<GetElementPtrInst>(Val: C.Ins)->isInBounds();
1391 // C = (char *)Basis + Bump
1392 Reduced = Builder.CreatePtrAdd(Ptr: Basis.Ins, Offset: Bump, Name: "", NW: InBounds);
1393 break;
1394 }
1395 default:
1396 llvm_unreachable("C.CandidateKind is invalid");
1397 };
1398 Reduced->takeName(V: C.Ins);
1399 }
1400 C.Ins->replaceAllUsesWith(V: Reduced);
1401 DeadInstructions.push_back(x: C.Ins);
1402}
1403
1404bool StraightLineStrengthReduceLegacyPass::runOnFunction(Function &F) {
1405 if (skipFunction(F))
1406 return false;
1407
1408 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1409 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1410 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1411 return StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F);
1412}
1413
1414bool StraightLineStrengthReduce::runOnFunction(Function &F) {
1415 LLVM_DEBUG(dbgs() << "SLSR on Function: " << F.getName() << "\n");
1416 // Traverse the dominator tree in the depth-first order. This order makes sure
1417 // all bases of a candidate are in Candidates when we process it.
1418 for (const auto Node : depth_first(G: DT))
1419 for (auto &I : *(Node->getBlock()))
1420 allocateCandidatesAndFindBasis(I: &I);
1421
1422 // Build the dependency graph and sort candidate instructions from dependency
1423 // roots to leaves
1424 for (auto &C : Candidates) {
1425 DependencyGraph.try_emplace(Key: C.Ins);
1426 addDependency(C, Basis: C.Basis);
1427 }
1428 sortCandidateInstructions();
1429
1430 // Rewrite candidates in the topological order that rewrites a Candidate
1431 // always before rewriting its Basis
1432 for (Instruction *I : reverse(C&: SortedCandidateInsts))
1433 if (Candidate *C = pickRewriteCandidate(I))
1434 rewriteCandidate(C: *C);
1435
1436 for (auto *DeadIns : DeadInstructions)
1437 // A dead instruction may be another dead instruction's op,
1438 // don't delete an instruction twice
1439 if (DeadIns->getParent())
1440 RecursivelyDeleteTriviallyDeadInstructions(V: DeadIns);
1441
1442 bool Ret = !DeadInstructions.empty();
1443 DeadInstructions.clear();
1444 DependencyGraph.clear();
1445 RewriteCandidates.clear();
1446 SortedCandidateInsts.clear();
1447 // First clear all references to candidates in the list
1448 CandidateDict.clear();
1449 // Then destroy the list
1450 Candidates.clear();
1451 return Ret;
1452}
1453
1454PreservedAnalyses
1455StraightLineStrengthReducePass::run(Function &F, FunctionAnalysisManager &AM) {
1456 const DataLayout *DL = &F.getDataLayout();
1457 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
1458 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
1459 auto *TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
1460
1461 if (!StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F))
1462 return PreservedAnalyses::all();
1463
1464 PreservedAnalyses PA;
1465 PA.preserveSet<CFGAnalyses>();
1466 PA.preserve<ScalarEvolutionAnalysis>();
1467 PA.preserve<TargetIRAnalysis>();
1468 return PA;
1469}
1470