53#define DEBUG_TYPE "lcssa"
55STATISTIC(NumLCSSA,
"Number of live out of a loop variables");
57#ifdef EXPENSIVE_CHECKS
65 cl::desc(
"Verify loop lcssa form (time consuming)"));
93 while (!Worklist.
empty()) {
94 UsesToRewrite.
clear();
97 assert(!
I->getType()->isTokenLikeTy() &&
98 "Token-like values shouldn't be in the worklist");
101 assert(L &&
"Instruction belongs to a BB that's not part of a loop");
102 auto [It, Inserted] = LoopExitBlocks.try_emplace(L);
104 L->getExitBlocks(It->second);
107 if (ExitBlocks.
empty())
111 bool DropLifetimeMarkers =
false;
119 if (
User->isLifetimeStartOrEnd()) {
121 if (InstBB != UserBB && !L->contains(UserBB))
122 DropLifetimeMarkers =
true;
136 UserBB = PN->getIncomingBlock(U);
138 if (InstBB != UserBB && !L->contains(UserBB))
142 if (DropLifetimeMarkers) {
145 Marker->eraseFromParent();
150 if (UsesToRewrite.
empty())
161 DomBB = Inv->getNormalDest();
174 bool HasSCEV = SE && SE->
isSCEVable(
I->getType()) &&
184 I->getName() +
".lcssa");
202 if (!L->contains(Pred))
222 if (!L->contains(OtherLoop))
235 for (
Use *UseToRewrite : UsesToRewrite) {
243 UserBB = PN->getIncomingBlock(*UseToRewrite);
250 UseToRewrite->set(&UserBB->
front());
256 if (AddedPHIs.
size() == 1) {
257 UseToRewrite->set(AddedPHIs[0]);
271 if (InstBB == UserBB || L->contains(UserBB))
276 Value *V = AddedPHIs.
size() == 1 ? AddedPHIs[0]
279 DVR->replaceVariableLocationOp(
I, V);
284 for (
PHINode *InsertedPN : LocalInsertedPHIs) {
285 if (
auto *OtherLoop = LI.
getLoopFor(InsertedPN->getParent()))
286 if (!L->contains(OtherLoop))
294 for (
auto *PostProcessPN : PostProcessPHIs)
295 if (!PostProcessPN->use_empty())
302 LocalPHIsToRemove.
insert(PN);
316 PHIsToRemove->
append(LocalPHIsToRemove.
begin(), LocalPHIsToRemove.
end());
318 for (
PHINode *PN : LocalPHIsToRemove)
320 PN->eraseFromParent();
336 InsertedPHIs, LoopExitBlocks);
347 while (!BBWorklist.
empty()) {
351 if (L.getHeader() == BB)
374 if (!L.contains(IDomBB))
377 if (BlocksDominatingExits.
insert(IDomBB))
387#ifdef EXPENSIVE_CHECKS
389 for (
Loop *SubLoop: L) {
391 assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) &&
"Subloop not in LCSSA!");
395 auto [It, Inserted] = LoopExitBlocks.try_emplace(&L);
397 L.getExitBlocks(It->second);
399 if (ExitBlocks.
empty())
415 for (
BasicBlock *BB : BlocksDominatingExits) {
424 (
I.hasOneUse() &&
I.user_back()->getParent() == BB &&
432 if (
I.getType()->isTokenLikeTy())
440 nullptr, LoopExitBlocks);
442 assert(L.isLCSSAForm(DT));
461 for (
Loop *SubLoop : L.getSubLoops())
480 for (
const auto &L : *LI)
488 LCSSAWrapperPass() : FunctionPass(ID) {
498 void verifyAnalysis()
const override {
506 return L->isRecursivelyLCSSAForm(*DT, *LI);
508 "LCSSA form is broken!");
515 void getAnalysisUsage(AnalysisUsage &AU)
const override {
536char LCSSAWrapperPass::ID = 0;
549bool LCSSAWrapperPass::runOnFunction(
Function &
F) {
550 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
551 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
552 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
553 SE = SEWP ? &SEWP->getSE() :
nullptr;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
static bool formLCSSAForInstructionsImpl(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove, SmallVectorImpl< PHINode * > *InsertedPHIs, LoopExitBlocksTy &LoopExitBlocks)
For every instruction from the worklist, check to see if it has any uses that are outside the current...
static bool isExitBlock(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks)
Return true if the specified block is in the list.
static bool VerifyLoopLCSSA
static bool formLCSSAImpl(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE, LoopExitBlocksTy &LoopExitBlocks)
static bool formLCSSAOnAllLoops(const LoopInfo *LI, const DominatorTree &DT, ScalarEvolution *SE)
Process all loops in the function, inner-most out.
SmallDenseMap< Loop *, SmallVector< BasicBlock *, 1 > > LoopExitBlocksTy
static void computeBlocksDominatingExits(Loop &L, const DominatorTree &DT, ArrayRef< BasicBlock * > ExitBlocks, SmallSetVector< BasicBlock *, 8 > &BlocksDominatingExits)
static bool formLCSSARecursivelyImpl(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE, LoopExitBlocksTy &LoopExitBlocks)
Process a loop nest depth first.
static cl::opt< bool, true > VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA), cl::Hidden, cl::desc("Verify loop lcssa form (time consuming)"))
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This is the interface for a SCEV-based alias analysis.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const Instruction & front() const
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
Analysis pass which computes BranchProbabilityInfo.
Represents analyses that only rely on functions' control flow.
LLVM_ABI const BasicBlock * getParent() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DomTreeNodeBase * getIDom() const
Analysis pass which computes a DominatorTree.
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.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
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.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
An analysis that produces MemorySSA for a function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static unsigned getOperandNumForIncomingValue(unsigned i)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
size_t size(BasicBlock *BB)
ArrayRef< BasicBlock * > get(BasicBlock *BB)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Helper class for SSA formation on a set of values defined in multiple blocks.
LLVM_ABI void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
LLVM_ABI Value * FindValueForBlock(BasicBlock *BB) const
Return the value for the specified block if the SSAUpdater has one, otherwise return nullptr.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
iterator end()
Get an iterator to the end of the SetVector.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
const Use & getOperandUse(unsigned i) const
LLVM Value Representation.
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Pass * createLCSSAPass()
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI char & LoopSimplifyID
DomTreeNodeBase< BasicBlock > DomTreeNode
LLVM_ABI void initializeLCSSAWrapperPassPass(PassRegistry &)
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...
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.