LLVM 22.0.0git
LoopVersioning.cpp
Go to the documentation of this file.
1//===- LoopVersioning.cpp - Utility to version a loop ---------------------===//
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 defines a utility class to perform loop versioning. The versioned
10// loop speculates that otherwise may-aliasing memory accesses don't overlap and
11// emits checks to prove this.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/ArrayRef.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/PassManager.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "loop-versioning"
35
36static cl::opt<bool>
37 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
39 cl::desc("Add no-alias annotation for instructions that "
40 "are disambiguated by memchecks"));
41
44 LoopInfo *LI, DominatorTree *DT,
46 : VersionedLoop(L), AliasChecks(Checks), Preds(LAI.getPSE().getPredicate()),
47 LAI(LAI), LI(LI), DT(DT), SE(SE) {}
48
50 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
51 assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
52 assert(VersionedLoop->isLoopSimplifyForm() &&
53 "Loop is not in loop-simplify form");
54
55 Value *MemRuntimeCheck;
56 Value *SCEVRuntimeCheck;
57 Value *RuntimeCheck = nullptr;
58
59 // Add the memcheck in the original preheader (this is empty initially).
60 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
61 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
62
63 SCEVExpander Exp2(*RtPtrChecking.getSE(),
64 VersionedLoop->getHeader()->getDataLayout(),
65 "induction");
66 MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
67 VersionedLoop, AliasChecks, Exp2);
68
69 SCEVExpander Exp(*SE, RuntimeCheckBB->getDataLayout(),
70 "scev.check");
71 SCEVRuntimeCheck =
72 Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
73
75 RuntimeCheckBB->getContext(),
76 InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
77 if (MemRuntimeCheck && SCEVRuntimeCheck) {
78 Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
79 RuntimeCheck =
80 Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
81 } else
82 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
83
84 Exp.eraseDeadInstructions(SCEVRuntimeCheck);
85
86 assert(RuntimeCheck && "called even though we don't need "
87 "any runtime checks");
88
89 // Rename the block to make the IR more readable.
90 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
91 ".lver.check");
92
93 // Create empty preheader for the loop (and after cloning for the
94 // non-versioned loop).
95 BasicBlock *PH =
96 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
97 nullptr, VersionedLoop->getHeader()->getName() + ".ph");
98
99 // Clone the loop including the preheader.
100 //
101 // FIXME: This does not currently preserve SimplifyLoop because the exit
102 // block is a join between the two loops.
103 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
104 NonVersionedLoop =
105 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
106 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
107 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
108
109 // Insert the conditional branch based on the result of the memchecks.
110 Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
111 Builder.SetInsertPoint(OrigTerm);
112 Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
113 VersionedLoop->getLoopPreheader());
114 OrigTerm->eraseFromParent();
115
116 // The loops merge in the original exit block. This is now dominated by the
117 // memchecking block.
118 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
119
120 // Adds the necessary PHI nodes for the versioned loops based on the
121 // loop-defined values used outside of the loop.
122 addPHINodes(DefsUsedOutside);
123 formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
124 formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
125 assert(NonVersionedLoop->isLoopSimplifyForm() &&
126 VersionedLoop->isLoopSimplifyForm() &&
127 "The versioned loops should be in simplify form.");
128}
129
130void LoopVersioning::addPHINodes(
131 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
132 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
133 assert(PHIBlock && "No single successor to loop exit block");
134 PHINode *PN;
135
136 // First add a single-operand PHI for each DefsUsedOutside if one does not
137 // exists yet.
138 for (auto *Inst : DefsUsedOutside) {
139 // See if we have a single-operand PHI with the value defined by the
140 // original loop.
141 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
142 if (PN->getIncomingValue(0) == Inst) {
143 SE->forgetLcssaPhiWithNewPredecessor(VersionedLoop, PN);
144 break;
145 }
146 }
147 // If not create it.
148 if (!PN) {
149 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");
150 PN->insertBefore(PHIBlock->begin());
151 SmallVector<User*, 8> UsersToUpdate;
152 for (User *U : Inst->users())
153 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
154 UsersToUpdate.push_back(U);
155 for (User *U : UsersToUpdate)
156 U->replaceUsesOfWith(Inst, PN);
157 PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
158 }
159 }
160
161 // Then for each PHI add the operand for the edge from the cloned loop.
162 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
163 assert(PN->getNumOperands() == 1 &&
164 "Exit block should only have on predecessor");
165
166 // If the definition was cloned used that otherwise use the same value.
167 Value *ClonedValue = PN->getIncomingValue(0);
168 auto Mapped = VMap.find(ClonedValue);
169 if (Mapped != VMap.end())
170 ClonedValue = Mapped->second;
171
172 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
173 }
174}
175
177 // We need to turn the no-alias relation between pointer checking groups into
178 // no-aliasing annotations between instructions.
179 //
180 // We accomplish this by mapping each pointer checking group (a set of
181 // pointers memchecked together) to an alias scope and then also mapping each
182 // group to the list of scopes it can't alias.
183
184 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
185 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
186
187 // First allocate an aliasing scope for each pointer checking group.
188 //
189 // While traversing through the checking groups in the loop, also create a
190 // reverse map from pointers to the pointer checking group they were assigned
191 // to.
192 MDBuilder MDB(Context);
193 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
194
195 for (const auto &Group : RtPtrChecking->CheckingGroups) {
196 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
197
198 for (unsigned PtrIdx : Group.Members)
199 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
200 }
201
202 // Go through the checks and for each pointer group, collect the scopes for
203 // each non-aliasing pointer group.
205 GroupToNonAliasingScopes;
206
207 for (const auto &Check : AliasChecks)
208 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
209
210 // Finally, transform the above to actually map to scope list which is what
211 // the metadata uses.
212
213 for (const auto &Pair : GroupToNonAliasingScopes)
214 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
215}
216
218 if (!AnnotateNoAlias)
219 return;
220
221 // First prepare the maps.
223
224 // Add the scope and no-alias metadata to the instructions.
225 for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {
227 }
228}
229
230std::pair<MDNode *, MDNode *>
232 if (!AnnotateNoAlias)
233 return {nullptr, nullptr};
234
235 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
236 const Value *Ptr = isa<LoadInst>(OrigInst)
237 ? cast<LoadInst>(OrigInst)->getPointerOperand()
238 : cast<StoreInst>(OrigInst)->getPointerOperand();
239
240 MDNode *AliasScope = nullptr;
241 MDNode *NoAlias = nullptr;
242 // Find the group for the pointer and then add the scope metadata.
243 auto Group = PtrToGroup.find(Ptr);
244 if (Group != PtrToGroup.end()) {
245 AliasScope = MDNode::concatenate(
246 OrigInst->getMetadata(LLVMContext::MD_alias_scope),
247 MDNode::get(Context, GroupToScope.lookup(Group->second)));
248
249 // Add the no-alias metadata.
250 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
251 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
252 NoAlias =
253 MDNode::concatenate(OrigInst->getMetadata(LLVMContext::MD_noalias),
254 NonAliasingScopeList->second);
255 }
256 return {AliasScope, NoAlias};
257}
258
260 const Instruction *OrigInst) {
261 const auto &[AliasScopeMD, NoAliasMD] = getNoAliasMetadataFor(OrigInst);
262 if (AliasScopeMD)
263 VersionedInst->setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
264
265 if (NoAliasMD)
266 VersionedInst->setMetadata(LLVMContext::MD_noalias, NoAliasMD);
267}
268
269namespace {
271 ScalarEvolution *SE) {
272 // Build up a worklist of inner-loops to version. This is necessary as the
273 // act of versioning a loop creates new loops and can invalidate iterators
274 // across the loops.
275 SmallVector<Loop *, 8> Worklist;
276
277 for (Loop *TopLevelLoop : *LI)
278 for (Loop *L : depth_first(TopLevelLoop))
279 // We only handle inner-most loops.
280 if (L->isInnermost())
281 Worklist.push_back(L);
282
283 // Now walk the identified inner loops.
284 bool Changed = false;
285 for (Loop *L : Worklist) {
286 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
287 !L->getExitingBlock())
288 continue;
289 const LoopAccessInfo &LAI = LAIs.getInfo(*L);
290 if (!LAI.hasConvergentOp() &&
292 !LAI.getPSE().getPredicate().isAlwaysTrue())) {
293 if (!L->isLCSSAForm(*DT))
294 formLCSSARecursively(*L, *DT, LI, SE);
295
297 LI, DT, SE);
298 LVer.versionLoop();
299 LVer.annotateLoopWithNoAlias();
300 Changed = true;
301 LAIs.clear();
302 }
303 }
304
305 return Changed;
306}
307}
308
311 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
312 auto &LI = AM.getResult<LoopAnalysis>(F);
314 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
315
316 if (runImpl(&LI, LAIs, &DT, &SE))
318 return PreservedAnalyses::all();
319}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool runImpl(Function &F, const TargetLowering &TLI, AssumptionCache *AC)
Definition ExpandFp.cpp:992
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"))
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
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 if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2780
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.
Definition LLVMContext.h:68
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.
Definition LoopInfo.h:569
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
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...
void annotateLoopWithNoAlias()
Annotate memory instructions in the versioned loop with no-alias metadata based on the memchecks issu...
void prepareNoAliasMetadata()
Set up the aliasing scopes based on the memchecks.
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 and LoopInfo up...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
LoopVersioning(const LoopAccessInfo &LAI, ArrayRef< RuntimePointerCheck > Checks, Loop *L, LoopInfo *LI, DominatorTree *DT, ScalarEvolution *SE)
Expects LoopAccessInfo, Loop, LoopInfo, DominatorTree as input.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:181
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition MDBuilder.h:174
Metadata node.
Definition Metadata.h:1077
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
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.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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
Definition User.h:254
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Changed
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:449
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...
Definition Casting.h:548
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.
Definition LoopUtils.cpp:58
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.
Definition Casting.h:565
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
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.