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