39#define DEBUG_TYPE "loop-versioning"
44 cl::desc(
"Add no-alias annotation for instructions that "
45 "are disambiguated by memchecks"));
51 : VersionedLoop(L), AliasChecks(Checks), Preds(LAI.getPSE().getPredicate()),
52 LAI(LAI), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU) {}
56 assert(VersionedLoop->getUniqueExitBlock() &&
"No single exit block");
57 assert(VersionedLoop->isLoopSimplifyForm() &&
58 "Loop is not in loop-simplify form");
61 assert(VersionedLoop->isRecursivelyLCSSAForm(*DT, *LI) &&
62 "Loop is not in LCSSA form");
64 Value *MemRuntimeCheck;
65 Value *SCEVRuntimeCheck;
66 Value *RuntimeCheck =
nullptr;
69 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
70 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
74 VersionedLoop, AliasChecks, Exp2);
78 Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->
getTerminator());
83 if (MemRuntimeCheck && SCEVRuntimeCheck) {
86 Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck,
"lver.safe");
88 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
90 Exp.eraseDeadInstructions(SCEVRuntimeCheck);
92 assert(RuntimeCheck &&
"called even though we don't need "
93 "any runtime checks");
96 RuntimeCheckBB->
setName(VersionedLoop->getHeader()->getName() +
103 VersionedLoop->getHeader()->
getName() +
".ph");
112 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
117 Builder.SetInsertPoint(OrigTerm);
119 Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
120 VersionedLoop->getLoopPreheader());
128 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
134 MSSAU->updateForClonedLoop(LoopRPOT, {}, VMap);
140 NonVersionedLoop->getLoopPreheader()});
142 LI->getExitEdges(*NonVersionedLoop, ExitEdges);
143 for (
auto [Exiting, Exit] : ExitEdges)
145 MSSAU->applyInsertUpdates(Updates, *DT);
150 addPHINodes(DefsUsedOutside);
153 assert(NonVersionedLoop->isLoopSimplifyForm() &&
154 VersionedLoop->isLoopSimplifyForm() &&
155 "The versioned loops should be in simplify form.");
158void LoopVersioning::addPHINodes(
161 assert(PHIBlock &&
"No single successor to loop exit block");
166 for (
auto *Inst : DefsUsedOutside) {
180 for (User *U : Inst->users())
183 for (User *U : UsersToUpdate)
184 U->replaceUsesOfWith(Inst, PN);
185 PN->
addIncoming(Inst, VersionedLoop->getExitingBlock());
192 "Exit block should only have on predecessor");
196 auto Mapped = VMap.find(ClonedValue);
197 if (Mapped != VMap.end())
198 ClonedValue = Mapped->second;
200 PN->
addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
213 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
226 for (
unsigned PtrIdx : Group.Members)
233 GroupToNonAliasingScopes;
235 for (
const auto &
Check : AliasChecks)
236 GroupToNonAliasingScopes[
Check.first].push_back(GroupToScope[
Check.second]);
241 for (
const auto &Pair : GroupToNonAliasingScopes)
242 GroupToNonAliasingScopeList[Pair.first] =
MDNode::get(Context, Pair.second);
253 for (
Instruction *
I : LAI.getDepChecker().getMemoryInstructions()) {
258std::pair<MDNode *, MDNode *>
261 return {
nullptr,
nullptr};
263 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
268 MDNode *AliasScope =
nullptr;
269 MDNode *NoAlias =
nullptr;
271 auto Group = PtrToGroup.find(Ptr);
272 if (Group != PtrToGroup.end()) {
274 OrigInst->
getMetadata(LLVMContext::MD_alias_scope),
275 MDNode::get(Context, GroupToScope.lookup(Group->second)));
278 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
279 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
282 NonAliasingScopeList->second);
284 return {AliasScope, NoAlias};
291 VersionedInst->
setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
294 VersionedInst->
setMetadata(LLVMContext::MD_noalias, NoAliasMD);
305 for (
Loop *TopLevelLoop : *LI)
308 if (L->isInnermost())
313 for (
Loop *L : Worklist) {
314 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
315 !L->getExitingBlock())
322 if (!L->isRecursivelyLCSSAForm(*DT, *LI))
328 LVer.annotateLoopWithNoAlias();
347 std::unique_ptr<MemorySSAUpdater> MSSAU;
349 MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAAnalysis->getMSSA());
351 if (!
runImpl(&LI, LAIs, &DT, &SE, MSSAU.get()))
355 MSSAAnalysis->getMSSA().verifyMemorySSA();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool runImpl(MachineFunction &MF)
This header defines various interfaces for pass management in LLVM.
static cl::opt< bool > AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true), cl::Hidden, cl::desc("Add no-alias annotation for instructions that " "are disambiguated by memchecks"))
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for profiling metadata utility functions.
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
This analysis provides dependence information for the memory accesses of a loop.
LLVM_ABI const LoopAccessInfo & getInfo(Loop &L, bool AllowPartial=false)
Drive the analysis of memory accesses in the loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
Analysis pass that exposes the LoopInfo for a function.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
LLVM_ABI void annotateLoopWithNoAlias()
Annotate memory instructions in the versioned loop with no-alias metadata based on the memchecks issu...
LLVM_ABI void prepareNoAliasMetadata()
Set up the aliasing scopes based on the memchecks.
LLVM_ABI void annotateInstWithNoAlias(Instruction *VersionedInst, const Instruction *OrigInst)
Add the noalias annotations to VersionedInst.
void versionLoop()
Performs the CFG manipulation part of versioning the loop including the DominatorTree,...
LLVM_ABI std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
LLVM_ABI LoopVersioning(const LoopAccessInfo &LAI, ArrayRef< RuntimePointerCheck > Checks, Loop *L, LoopInfo *LI, DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU=nullptr)
Expects LoopAccessInfo, Loop, LoopInfo, DominatorTree as input.
Represents a single loop in the control flow graph.
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
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.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
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...
LLVM_ABI const SCEVPredicate & getPredicate() const
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 & preserve()
Mark an analysis as preserved.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
SmallVector< RuntimeCheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This class uses information about analyze scalars to rewrite expressions in canonical form.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
unsigned getNumOperands() const
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
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...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.