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 whose poison-generating annotations must be dropped
226 // if this candidate is used as the basis of an executed rewrite.
227 SmallVector<Instruction *> DropList;
228
229 /// Cost model: Evaluate the computational efficiency of the candidate.
230 ///
231 /// Efficiency levels (higher is better):
232 /// ZeroInst (5) - [Variable] or [Const]
233 /// OneInstOneVar (4) - [Variable + Const] or [Variable * Const]
234 /// OneInstTwoVar (3) - [Variable + Variable] or [Variable * Variable]
235 /// TwoInstOneVar (2) - [Const + Const * Variable]
236 /// TwoInstTwoVar (1) - [Variable + Const * Variable]
237 enum EfficiencyLevel : unsigned {
238 Unknown = 0,
239 TwoInstTwoVar = 1,
240 TwoInstOneVar = 2,
241 OneInstTwoVar = 3,
242 OneInstOneVar = 4,
243 ZeroInst = 5
244 };
245
246 static EfficiencyLevel
247 getComputationEfficiency(Kind CandidateKind, const ConstantInt *Index,
248 const Value *Stride, const SCEV *Base = nullptr) {
249 bool IsConstantBase = false;
250 bool IsZeroBase = false;
251 // When evaluating the efficiency of a rewrite, if the Base's SCEV is
252 // not available, conservatively assume the base is not constant.
253 if (auto *ConstBase = dyn_cast_or_null<SCEVConstant>(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 // Record delta if none has been found yet, or the new delta is
812 // a constant that is better than the existing delta.
813 if (!C.Delta || isa<ConstantInt>(Delta)) {
814 C.Delta = Delta;
815 C.Basis = Basis;
816 C.DeltaKind = K;
817 }
818 return isa<ConstantInt>(C.Delta);
819}
820
821// return true if find a Basis with constant delta and stop searching,
822// return false if did not find a Basis or the delta is not a constant
823// and continue searching for a Basis with constant delta
824bool StraightLineStrengthReduce::searchFrom(
825 const CandidateDictTy::BBToCandsTy &BBToCands, Candidate &C,
826 Candidate::DKind K) {
827
828 // Stride delta rewrite on Mul form is usually non-profitable, and Base
829 // delta rewrite sometimes is profitable, so we do not support them on Mul.
830 if (C.CandidateKind == Candidate::Mul && K != Candidate::IndexDelta)
831 return false;
832
833 // Search dominating candidates by walking the immediate-dominator chain
834 // from the candidate's defining block upward. Visiting blocks in this
835 // order ensures we prefer the closest dominating basis.
836 const BasicBlock *BB = C.Ins->getParent();
837 while (BB) {
838 auto It = BBToCands.find(BB);
839 if (It != BBToCands.end())
840 for (Candidate *Basis : reverse(It->second))
841 if (candidatePredicate(Basis, C, K))
842 return true;
843
844 const DomTreeNode *Node = DT->getNode(BB);
845 if (!Node)
846 break;
847 Node = Node->getIDom();
848 BB = Node ? Node->getBlock() : nullptr;
849 }
850 return false;
851}
852
853void StraightLineStrengthReduce::setBasisAndDeltaFor(Candidate &C) {
854 if (const auto *BaseDeltaCandidates =
855 CandidateDict.getCandidatesWithDeltaKind(C, Candidate::BaseDelta))
856 if (searchFrom(*BaseDeltaCandidates, C, Candidate::BaseDelta)) {
857 LLVM_DEBUG(dbgs() << "Found delta from Base: " << *C.Delta << "\n");
858 return;
859 }
860
861 if (const auto *StrideDeltaCandidates =
862 CandidateDict.getCandidatesWithDeltaKind(C, Candidate::StrideDelta))
863 if (searchFrom(*StrideDeltaCandidates, C, Candidate::StrideDelta)) {
864 LLVM_DEBUG(dbgs() << "Found delta from Stride: " << *C.Delta << "\n");
865 return;
866 }
867
868 if (const auto *IndexDeltaCandidates =
869 CandidateDict.getCandidatesWithDeltaKind(C, Candidate::IndexDelta))
870 if (searchFrom(*IndexDeltaCandidates, C, Candidate::IndexDelta)) {
871 LLVM_DEBUG(dbgs() << "Found delta from Index: " << *C.Delta << "\n");
872 return;
873 }
874
875 // If we did not find a constant delta, we might have found a variable delta
876 if (C.Delta) {
877 LLVM_DEBUG({
878 dbgs() << "Found delta from ";
879 if (C.DeltaKind == Candidate::BaseDelta)
880 dbgs() << "Base: ";
881 else
882 dbgs() << "Stride: ";
883 dbgs() << *C.Delta << "\n";
884 });
885 assert(C.DeltaKind != Candidate::InvalidDelta && C.Basis);
886 }
887}
888
889// Compress the path from `Basis` to the deepest Basis in the Basis chain
890// to avoid non-profitable data dependency and improve ILP.
891// X = A + 1
892// Y = X + 1
893// Z = Y + 1
894// ->
895// X = A + 1
896// Y = A + 2
897// Z = A + 3
898// Return the delta info for C aginst the new Basis
899auto StraightLineStrengthReduce::compressPath(Candidate &C,
900 Candidate *Basis) const
901 -> DeltaInfo {
902 if (!Basis || !Basis->Basis || C.CandidateKind == Candidate::Mul)
903 return {};
904 Candidate *Root = Basis;
905 Value *NewDelta = nullptr;
906 auto NewKind = Candidate::InvalidDelta;
907
908 while (Root->Basis) {
909 Candidate *NextRoot = Root->Basis;
910 if (C.Base == NextRoot->Base && C.StrideSCEV == NextRoot->StrideSCEV &&
911 isSimilar(C, *NextRoot, Candidate::IndexDelta)) {
912 ConstantInt *CI =
913 cast<ConstantInt>(getDelta(C, *NextRoot, Candidate::IndexDelta));
914 if (CI->isZero() || CI->isOne() || isa<SCEVConstant>(C.StrideSCEV)) {
915 Root = NextRoot;
916 NewKind = Candidate::IndexDelta;
917 NewDelta = CI;
918 continue;
919 }
920 }
921
922 const SCEV *CandPart = nullptr;
923 const SCEV *BasisPart = nullptr;
924 auto CurrKind = Candidate::InvalidDelta;
925 if (C.Base == NextRoot->Base && C.Index == NextRoot->Index) {
926 CandPart = C.StrideSCEV;
927 BasisPart = NextRoot->StrideSCEV;
928 CurrKind = Candidate::StrideDelta;
929 } else if (C.StrideSCEV == NextRoot->StrideSCEV &&
930 C.Index == NextRoot->Index) {
931 CandPart = C.Base;
932 BasisPart = NextRoot->Base;
933 CurrKind = Candidate::BaseDelta;
934 } else
935 break;
936
937 assert(CandPart && BasisPart);
938 if (!isSimilar(C, *NextRoot, CurrKind))
939 break;
940
941 // Path compression folds a constant Stride-delta directly against the
942 // deeper basis NextRoot, bypassing candidatePredicate's wrap guard. With a
943 // constant delta sext(Sb) + C can differ from sext(Sc) if the deeper
944 // basis's stride wraps, so do not compress past such a basis (mirrors the
945 // check in candidatePredicate).
946 if (CurrKind == Candidate::StrideDelta &&
947 C.CandidateKind == Candidate::GEP &&
948 !isSafeToFactorGepIndex(NextRoot->Stride,
949 cast<GetElementPtrInst>(NextRoot->Ins), DL))
950 break;
951
952 ++NumSCEVCandidateBasisDifferences;
953 if (auto DeltaVal =
954 dyn_cast<SCEVConstant>(SE->getMinusSCEV(CandPart, BasisPart))) {
955 Root = NextRoot;
956 NewDelta = DeltaVal->getValue();
957 NewKind = CurrKind;
958 } else
959 break;
960 }
961
962 if (Root != Basis) {
963 assert(NewKind != Candidate::InvalidDelta && NewDelta);
964 LLVM_DEBUG(dbgs() << "Found new Basis with " << *NewDelta
965 << " from path compression.\n");
966 return {Root, NewKind, NewDelta};
967 }
968
969 return {};
970}
971
972// Topologically sort candidate instructions based on their relationship in
973// dependency graph.
974void StraightLineStrengthReduce::sortCandidateInstructions() {
975 SortedCandidateInsts.clear();
976 // An instruction may have multiple candidates that get different Basis
977 // instructions, and each candidate can get dependencies from Basis and
978 // Stride when Stride will also be rewritten by SLSR. Hence, an instruction
979 // may have multiple dependencies. Use InDegree to ensure all dependencies
980 // processed before processing itself.
981 DenseMap<Instruction *, int> InDegree;
982 for (auto &KV : DependencyGraph) {
983 InDegree.try_emplace(KV.first, 0);
984
985 for (auto *Child : KV.second) {
986 InDegree[Child]++;
987 }
988 }
989 std::queue<Instruction *> WorkList;
990 DenseSet<Instruction *> Visited;
991
992 for (auto &KV : DependencyGraph)
993 if (InDegree[KV.first] == 0)
994 WorkList.push(KV.first);
995
996 while (!WorkList.empty()) {
997 Instruction *I = WorkList.front();
998 WorkList.pop();
999 if (!Visited.insert(I).second)
1000 continue;
1001
1002 SortedCandidateInsts.push_back(I);
1003
1004 for (auto *Next : DependencyGraph[I]) {
1005 auto &Degree = InDegree[Next];
1006 if (--Degree == 0)
1007 WorkList.push(Next);
1008 }
1009 }
1010
1011 assert(SortedCandidateInsts.size() == DependencyGraph.size() &&
1012 "Dependency graph should not have cycles");
1013}
1014
1015auto StraightLineStrengthReduce::pickRewriteCandidate(Instruction *I) const
1016 -> Candidate * {
1017 // Return the candidate of instruction I that has the highest profit.
1018 auto It = RewriteCandidates.find(I);
1019 if (It == RewriteCandidates.end())
1020 return nullptr;
1021
1022 Candidate *BestC = nullptr;
1023 auto BestEfficiency = Candidate::Unknown;
1024 for (Candidate *C : reverse(It->second))
1025 if (C->Basis) {
1026 auto Efficiency = C->getRewriteEfficiency();
1027 if (Efficiency > BestEfficiency) {
1028 BestEfficiency = Efficiency;
1029 BestC = C;
1030 }
1031 }
1032
1033 return BestC;
1034}
1035
1037 const TargetTransformInfo *TTI) {
1038 SmallVector<const Value *, 4> Indices(GEP->indices());
1039 return TTI->getGEPCost(
1040 GEP->getSourceElementType(), GEP->getPointerOperand(), Indices,
1043}
1044
1045// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
1046static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
1048 // Index->getSExtValue() may crash if Index is wider than 64-bit.
1049 return Index->getBitWidth() <= 64 &&
1050 TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
1051 Index->getSExtValue(), UnknownAddressSpace);
1052}
1053
1054bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
1055 TargetTransformInfo *TTI) {
1056 if (C.CandidateKind == Candidate::Add)
1057 return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
1058 if (C.CandidateKind == Candidate::GEP)
1060 return false;
1061}
1062
1063void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1064 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
1065 Instruction *I) {
1066 bool IsSafe = CT != Candidate::GEP ||
1068 // Record the SCEV of S that we may use it as a variable delta.
1069 // Ensure that we rewrite C with a existing IR that reproduces delta value.
1070
1071 Candidate C(CT, B, Idx, S, I, getAndRecordSCEV(S));
1072 // If we can fold I into an addressing mode, computing I is likely free or
1073 // takes only one instruction. So, we don't need to analyze or rewrite it.
1074 //
1075 // Currently, this algorithm can at best optimize complex computations into
1076 // a `variable +/* constant` form. However, some targets have stricter
1077 // constraints on the their addressing mode.
1078 // For example, a `variable + constant` can only be folded to an addressing
1079 // mode if the constant falls within a certain range.
1080 // So, we also check if the instruction is already high efficient enough
1081 // for the strength reduction algorithm.
1082 if (IsSafe && !isFoldable(C, TTI) && !C.isHighEfficiency()) {
1083 setBasisAndDeltaFor(C);
1084
1085 // Compress unnecessary rewrite to improve ILP
1086 if (auto Res = compressPath(C, C.Basis)) {
1087 C.Basis = Res.Cand;
1088 C.DeltaKind = Res.DeltaKind;
1089 C.Delta = Res.Delta;
1090 }
1091 }
1092 // Regardless of whether we find a basis for C, we need to push C to the
1093 // candidate list so that it can be the basis of other candidates.
1094 LLVM_DEBUG(dbgs() << "Allocated Candidate: " << C << "\n");
1095 Candidates.push_back(C);
1096 RewriteCandidates[C.Ins].push_back(&Candidates.back());
1097 // Only add to the dict if this instruction is safe to reuse as a basis. By
1098 // doing this early we avoid calling canReuseInstruction repeatedly for the
1099 // same instruction. The DropList is stored on the Candidate so the flags can
1100 // be dropped only if this candidate is used by an executed rewrite.
1102 SE->canReuseInstruction(SE->getSCEV(I), I, Candidates.back().DropList)) {
1103 CandidateDict.add(Candidates.back());
1104 }
1105}
1106
1107void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
1108 Instruction *I) {
1109 switch (I->getOpcode()) {
1110 case Instruction::Add:
1111 allocateCandidatesAndFindBasisForAdd(I);
1112 break;
1113 case Instruction::Mul:
1114 allocateCandidatesAndFindBasisForMul(I);
1115 break;
1116 case Instruction::GetElementPtr:
1117 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
1118 break;
1119 }
1120}
1121
1122void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1123 Instruction *I) {
1124 // Try matching B + i * S.
1125 if (!isa<IntegerType>(I->getType()))
1126 return;
1127
1128 assert(I->getNumOperands() == 2 && "isn't I an add?");
1129 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
1130 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
1131 if (LHS != RHS)
1132 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
1133}
1134
1135void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
1136 Value *LHS, Value *RHS, Instruction *I) {
1137 Value *S = nullptr;
1138 ConstantInt *Idx = nullptr;
1139 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
1140 // I = LHS + RHS = LHS + Idx * S
1141 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
1142 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
1143 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
1144 APInt One(Idx->getBitWidth(), 1);
1145 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
1146 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
1147 } else {
1148 // At least, I = LHS + 1 * RHS
1149 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
1150 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
1151 I);
1152 }
1153}
1154
1155// Returns true if A matches B + C where C is constant.
1156static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
1157 return match(A, m_c_Add(m_Value(B), m_ConstantInt(C)));
1158}
1159
1160// Returns true if A matches B | C where C is constant.
1161static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
1162 return match(A, m_c_Or(m_Value(B), m_ConstantInt(C)));
1163}
1164
1165void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1166 Value *LHS, Value *RHS, Instruction *I) {
1167 Value *B = nullptr;
1168 ConstantInt *Idx = nullptr;
1169 if (matchesAdd(LHS, B, Idx)) {
1170 // If LHS is in the form of "Base + Index", then I is in the form of
1171 // "(Base + Index) * RHS".
1172 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
1173 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
1174 // If LHS is in the form of "Base | Index" and Base and Index have no common
1175 // bits set, then
1176 // Base | Index = Base + Index
1177 // and I is thus in the form of "(Base + Index) * RHS".
1178 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
1179 } else {
1180 // Otherwise, at least try the form (LHS + 0) * RHS.
1181 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
1182 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
1183 I);
1184 }
1185}
1186
1187void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
1188 Instruction *I) {
1189 // Try matching (B + i) * S.
1190 // TODO: we could extend SLSR to float and vector types.
1191 if (!isa<IntegerType>(I->getType()))
1192 return;
1193
1194 assert(I->getNumOperands() == 2 && "isn't I a mul?");
1195 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
1196 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
1197 if (LHS != RHS) {
1198 // Symmetrically, try to split RHS to Base + Index.
1199 allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
1200 }
1201}
1202
1203void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
1204 GetElementPtrInst *GEP) {
1205 // TODO: handle vector GEPs
1206 if (GEP->getType()->isVectorTy())
1207 return;
1208
1209 SmallVector<SCEVUse, 4> IndexExprs;
1210 for (Use &Idx : GEP->indices())
1211 IndexExprs.push_back(SE->getSCEV(Idx));
1212
1214 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1215 if (GTI.isStruct())
1216 continue;
1217
1218 SCEVUse OrigIndexExpr = IndexExprs[I - 1];
1219 IndexExprs[I - 1] = SE->getZero(OrigIndexExpr.getPointer()->getType());
1220
1221 // The base of this candidate is GEP's base plus the offsets of all
1222 // indices except this current one.
1223 SCEVUse BaseExpr = SE->getGEPExpr(cast<GEPOperator>(GEP), IndexExprs);
1224 Value *ArrayIdx = GEP->getOperand(I);
1225 uint64_t ElementSize = GTI.getSequentialElementStride(*DL);
1226 IntegerType *PtrIdxTy = cast<IntegerType>(DL->getIndexType(GEP->getType()));
1227 // If the element size overflows the type, truncate.
1228 ConstantInt *ElementSizeIdx =
1229 ConstantInt::getSigned(PtrIdxTy, ElementSize, /*ImplicitTrunc=*/true);
1230 if (ArrayIdx->getType()->getIntegerBitWidth() <=
1231 DL->getIndexSizeInBits(GEP->getAddressSpace())) {
1232 // Skip factoring if ArrayIdx is wider than the index size, because
1233 // ArrayIdx is implicitly truncated to the index size.
1234 allocateCandidatesAndFindBasis(Candidate::GEP, BaseExpr, ElementSizeIdx,
1235 ArrayIdx, GEP);
1236 }
1237 // When ArrayIdx is the sext of a value, we try to factor that value as
1238 // well. Handling this case is important because array indices are
1239 // typically sign-extended to the pointer index size.
1240 Value *TruncatedArrayIdx = nullptr;
1241 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))) &&
1242 TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
1243 DL->getIndexSizeInBits(GEP->getAddressSpace())) {
1244 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
1245 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
1246 allocateCandidatesAndFindBasis(Candidate::GEP, BaseExpr, ElementSizeIdx,
1247 TruncatedArrayIdx, GEP);
1248 }
1249
1250 IndexExprs[I - 1] = OrigIndexExpr;
1251 }
1252}
1253
1254Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
1255 const Candidate &C,
1256 IRBuilder<> &Builder,
1257 const DataLayout *DL) {
1258 auto CreateMul = [&](Value *LHS, Value *RHS) {
1259 if (ConstantInt *CR = dyn_cast<ConstantInt>(RHS)) {
1260 const APInt &ConstRHS = CR->getValue();
1261 IntegerType *DeltaType =
1262 IntegerType::get(C.Ins->getContext(), ConstRHS.getBitWidth());
1263 if (ConstRHS.isPowerOf2()) {
1264 ConstantInt *Exponent =
1265 ConstantInt::get(DeltaType, ConstRHS.logBase2());
1266 return Builder.CreateShl(LHS, Exponent);
1267 }
1268 if (ConstRHS.isNegatedPowerOf2()) {
1269 ConstantInt *Exponent =
1270 ConstantInt::get(DeltaType, (-ConstRHS).logBase2());
1271 return Builder.CreateNeg(Builder.CreateShl(LHS, Exponent));
1272 }
1273 }
1274
1275 return Builder.CreateMul(LHS, RHS);
1276 };
1277
1278 Value *Delta = C.Delta;
1279 // If Delta is 0, C is a fully redundant of C.Basis,
1280 // just replace C.Ins with Basis.Ins
1281 if (ConstantInt *CI = dyn_cast<ConstantInt>(Delta);
1282 CI && CI->getValue().isZero())
1283 return nullptr;
1284
1285 if (C.DeltaKind == Candidate::IndexDelta) {
1286 APInt IndexDelta = cast<ConstantInt>(C.Delta)->getValue();
1287 // IndexDelta
1288 // X = B + i * S
1289 // Y = B + i` * S
1290 // = B + (i + IndexDelta) * S
1291 // = B + i * S + IndexDelta * S
1292 // = X + IndexDelta * S
1293 // Bump = (i' - i) * S
1294
1295 // Common case 1: if (i' - i) is 1, Bump = S.
1296 if (IndexDelta == 1)
1297 return C.Stride;
1298 // Common case 2: if (i' - i) is -1, Bump = -S.
1299 if (IndexDelta.isAllOnes())
1300 return Builder.CreateNeg(C.Stride);
1301
1302 IntegerType *DeltaType =
1303 IntegerType::get(Basis.Ins->getContext(), IndexDelta.getBitWidth());
1304 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
1305
1306 return CreateMul(ExtendedStride, C.Delta);
1307 }
1308
1309 assert(C.DeltaKind == Candidate::StrideDelta ||
1310 C.DeltaKind == Candidate::BaseDelta);
1311 assert(C.CandidateKind != Candidate::Mul);
1312 // StrideDelta
1313 // X = B + i * S
1314 // Y = B + i * S'
1315 // = B + i * (S + StrideDelta)
1316 // = B + i * S + i * StrideDelta
1317 // = X + i * StrideDelta
1318 // Bump = i * (S' - S)
1319 //
1320 // BaseDelta
1321 // X = B + i * S
1322 // Y = B' + i * S
1323 // = (B + BaseDelta) + i * S
1324 // = X + BaseDelta
1325 // Bump = (B' - B).
1326 Value *Bump = C.Delta;
1327 if (C.DeltaKind == Candidate::StrideDelta) {
1328 // If this value is consumed by a GEP, promote StrideDelta before doing
1329 // StrideDelta * Index to ensure the same semantics as the original GEP.
1330 if (C.CandidateKind == Candidate::GEP) {
1331 auto *GEP = cast<GetElementPtrInst>(C.Ins);
1332 Type *NewScalarIndexTy =
1333 DL->getIndexType(GEP->getPointerOperandType()->getScalarType());
1334 Bump = Builder.CreateSExtOrTrunc(Bump, NewScalarIndexTy);
1335 }
1336 if (!C.Index->isOne()) {
1337 Value *ExtendedIndex =
1338 Builder.CreateSExtOrTrunc(C.Index, Bump->getType());
1339 Bump = CreateMul(Bump, ExtendedIndex);
1340 }
1341 }
1342 return Bump;
1343}
1344
1345void StraightLineStrengthReduce::rewriteCandidate(const Candidate &C) {
1346 if (!DebugCounter::shouldExecute(StraightLineStrengthReduceCounter))
1347 return;
1348
1349 const Candidate &Basis = *C.Basis;
1350 assert(C.Delta && C.CandidateKind == Basis.CandidateKind &&
1351 C.hasValidDelta(Basis));
1352
1353 for (Instruction *I : Basis.DropList)
1354 I->dropPoisonGeneratingAnnotations();
1355
1356 IRBuilder<> Builder(C.Ins);
1357 Value *Bump = emitBump(Basis, C, Builder, DL);
1358 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
1359 // If delta is 0, C is a fully redundant of Basis, and Bump is nullptr,
1360 // just replace C.Ins with Basis.Ins
1361 if (!Bump)
1362 Reduced = Basis.Ins;
1363 else {
1364 switch (C.CandidateKind) {
1365 case Candidate::Add:
1366 case Candidate::Mul: {
1367 // C = Basis + Bump
1368 Value *NegBump;
1369 if (match(Bump, m_Neg(m_Value(NegBump)))) {
1370 // If Bump is a neg instruction, emit C = Basis - (-Bump).
1371 Reduced = Builder.CreateSub(Basis.Ins, NegBump);
1372 // We only use the negative argument of Bump, and Bump itself may be
1373 // trivially dead.
1375 } else {
1376 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
1377 // usually unsound, e.g.,
1378 //
1379 // X = (-2 +nsw 1) *nsw INT_MAX
1380 // Y = (-2 +nsw 3) *nsw INT_MAX
1381 // =>
1382 // Y = X + 2 * INT_MAX
1383 //
1384 // Neither + and * in the resultant expression are nsw.
1385 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
1386 }
1387 break;
1388 }
1389 case Candidate::GEP: {
1390 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
1391 // C = (char *)Basis + Bump
1392 Reduced = Builder.CreatePtrAdd(Basis.Ins, Bump, "", InBounds);
1393 break;
1394 }
1395 default:
1396 llvm_unreachable("C.CandidateKind is invalid");
1397 };
1398 Reduced->takeName(C.Ins);
1399 }
1400 C.Ins->replaceAllUsesWith(Reduced);
1401 DeadInstructions.push_back(C.Ins);
1402}
1403
1404bool StraightLineStrengthReduceLegacyPass::runOnFunction(Function &F) {
1405 if (skipFunction(F))
1406 return false;
1407
1408 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1409 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1410 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1411 return StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F);
1412}
1413
1414bool StraightLineStrengthReduce::runOnFunction(Function &F) {
1415 LLVM_DEBUG(dbgs() << "SLSR on Function: " << F.getName() << "\n");
1416 // Traverse the dominator tree in the depth-first order. This order makes sure
1417 // all bases of a candidate are in Candidates when we process it.
1418 for (const auto Node : depth_first(DT))
1419 for (auto &I : *(Node->getBlock()))
1420 allocateCandidatesAndFindBasis(&I);
1421
1422 // Build the dependency graph and sort candidate instructions from dependency
1423 // roots to leaves
1424 for (auto &C : Candidates) {
1425 DependencyGraph.try_emplace(C.Ins);
1426 addDependency(C, C.Basis);
1427 }
1428 sortCandidateInstructions();
1429
1430 // Rewrite candidates in the topological order that rewrites a Candidate
1431 // always before rewriting its Basis
1432 for (Instruction *I : reverse(SortedCandidateInsts))
1433 if (Candidate *C = pickRewriteCandidate(I))
1434 rewriteCandidate(*C);
1435
1436 for (auto *DeadIns : DeadInstructions)
1437 // A dead instruction may be another dead instruction's op,
1438 // don't delete an instruction twice
1439 if (DeadIns->getParent())
1441
1442 bool Ret = !DeadInstructions.empty();
1443 DeadInstructions.clear();
1444 DependencyGraph.clear();
1445 RewriteCandidates.clear();
1446 SortedCandidateInsts.clear();
1447 // First clear all references to candidates in the list
1448 CandidateDict.clear();
1449 // Then destroy the list
1450 Candidates.clear();
1451 return Ret;
1452}
1453
1454PreservedAnalyses
1456 const DataLayout *DL = &F.getDataLayout();
1457 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1458 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
1459 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
1460
1461 if (!StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F))
1462 return PreservedAnalyses::all();
1463
1468 return PA;
1469}
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