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