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