LLVM 20.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"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "loop-versioning"
34
35static cl::opt<bool>
36 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
38 cl::desc("Add no-alias annotation for instructions that "
39 "are disambiguated by memchecks"));
40
43 LoopInfo *LI, DominatorTree *DT,
45 : VersionedLoop(L), AliasChecks(Checks), Preds(LAI.getPSE().getPredicate()),
46 LAI(LAI), LI(LI), DT(DT), SE(SE) {}
47
49 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
50 assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
51 assert(VersionedLoop->isLoopSimplifyForm() &&
52 "Loop is not in loop-simplify form");
53
54 Value *MemRuntimeCheck;
55 Value *SCEVRuntimeCheck;
56 Value *RuntimeCheck = nullptr;
57
58 // Add the memcheck in the original preheader (this is empty initially).
59 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
60 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
61
62 SCEVExpander Exp2(*RtPtrChecking.getSE(),
63 VersionedLoop->getHeader()->getDataLayout(),
64 "induction");
65 MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
66 VersionedLoop, AliasChecks, Exp2);
67
68 SCEVExpander Exp(*SE, RuntimeCheckBB->getDataLayout(),
69 "scev.check");
70 SCEVRuntimeCheck =
71 Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
72
74 RuntimeCheckBB->getContext(),
75 InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
76 if (MemRuntimeCheck && SCEVRuntimeCheck) {
77 Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
78 RuntimeCheck =
79 Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
80 } else
81 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
82
83 assert(RuntimeCheck && "called even though we don't need "
84 "any runtime checks");
85
86 // Rename the block to make the IR more readable.
87 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
88 ".lver.check");
89
90 // Create empty preheader for the loop (and after cloning for the
91 // non-versioned loop).
92 BasicBlock *PH =
93 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
94 nullptr, VersionedLoop->getHeader()->getName() + ".ph");
95
96 // Clone the loop including the preheader.
97 //
98 // FIXME: This does not currently preserve SimplifyLoop because the exit
99 // block is a join between the two loops.
100 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
101 NonVersionedLoop =
102 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
103 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
104 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
105
106 // Insert the conditional branch based on the result of the memchecks.
107 Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
108 Builder.SetInsertPoint(OrigTerm);
109 Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
110 VersionedLoop->getLoopPreheader());
111 OrigTerm->eraseFromParent();
112
113 // The loops merge in the original exit block. This is now dominated by the
114 // memchecking block.
115 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
116
117 // Adds the necessary PHI nodes for the versioned loops based on the
118 // loop-defined values used outside of the loop.
119 addPHINodes(DefsUsedOutside);
120 formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
121 formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
122 assert(NonVersionedLoop->isLoopSimplifyForm() &&
123 VersionedLoop->isLoopSimplifyForm() &&
124 "The versioned loops should be in simplify form.");
125}
126
127void LoopVersioning::addPHINodes(
128 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
129 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
130 assert(PHIBlock && "No single successor to loop exit block");
131 PHINode *PN;
132
133 // First add a single-operand PHI for each DefsUsedOutside if one does not
134 // exists yet.
135 for (auto *Inst : DefsUsedOutside) {
136 // See if we have a single-operand PHI with the value defined by the
137 // original loop.
138 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
139 if (PN->getIncomingValue(0) == Inst) {
140 SE->forgetValue(PN);
141 break;
142 }
143 }
144 // If not create it.
145 if (!PN) {
146 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");
147 PN->insertBefore(PHIBlock->begin());
148 SmallVector<User*, 8> UsersToUpdate;
149 for (User *U : Inst->users())
150 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
151 UsersToUpdate.push_back(U);
152 for (User *U : UsersToUpdate)
153 U->replaceUsesOfWith(Inst, PN);
154 PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
155 }
156 }
157
158 // Then for each PHI add the operand for the edge from the cloned loop.
159 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
160 assert(PN->getNumOperands() == 1 &&
161 "Exit block should only have on predecessor");
162
163 // If the definition was cloned used that otherwise use the same value.
164 Value *ClonedValue = PN->getIncomingValue(0);
165 auto Mapped = VMap.find(ClonedValue);
166 if (Mapped != VMap.end())
167 ClonedValue = Mapped->second;
168
169 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
170 }
171}
172
174 // We need to turn the no-alias relation between pointer checking groups into
175 // no-aliasing annotations between instructions.
176 //
177 // We accomplish this by mapping each pointer checking group (a set of
178 // pointers memchecked together) to an alias scope and then also mapping each
179 // group to the list of scopes it can't alias.
180
181 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
182 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
183
184 // First allocate an aliasing scope for each pointer checking group.
185 //
186 // While traversing through the checking groups in the loop, also create a
187 // reverse map from pointers to the pointer checking group they were assigned
188 // to.
189 MDBuilder MDB(Context);
190 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
191
192 for (const auto &Group : RtPtrChecking->CheckingGroups) {
193 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
194
195 for (unsigned PtrIdx : Group.Members)
196 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
197 }
198
199 // Go through the checks and for each pointer group, collect the scopes for
200 // each non-aliasing pointer group.
202 GroupToNonAliasingScopes;
203
204 for (const auto &Check : AliasChecks)
205 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
206
207 // Finally, transform the above to actually map to scope list which is what
208 // the metadata uses.
209
210 for (const auto &Pair : GroupToNonAliasingScopes)
211 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
212}
213
215 if (!AnnotateNoAlias)
216 return;
217
218 // First prepare the maps.
220
221 // Add the scope and no-alias metadata to the instructions.
224 }
225}
226
228 const Instruction *OrigInst) {
229 if (!AnnotateNoAlias)
230 return;
231
232 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
233 const Value *Ptr = isa<LoadInst>(OrigInst)
234 ? cast<LoadInst>(OrigInst)->getPointerOperand()
235 : cast<StoreInst>(OrigInst)->getPointerOperand();
236
237 // Find the group for the pointer and then add the scope metadata.
238 auto Group = PtrToGroup.find(Ptr);
239 if (Group != PtrToGroup.end()) {
240 VersionedInst->setMetadata(
241 LLVMContext::MD_alias_scope,
243 VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
244 MDNode::get(Context, GroupToScope[Group->second])));
245
246 // Add the no-alias metadata.
247 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
248 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
249 VersionedInst->setMetadata(
250 LLVMContext::MD_noalias,
252 VersionedInst->getMetadata(LLVMContext::MD_noalias),
253 NonAliasingScopeList->second));
254 }
255}
256
257namespace {
259 ScalarEvolution *SE) {
260 // Build up a worklist of inner-loops to version. This is necessary as the
261 // act of versioning a loop creates new loops and can invalidate iterators
262 // across the loops.
263 SmallVector<Loop *, 8> Worklist;
264
265 for (Loop *TopLevelLoop : *LI)
266 for (Loop *L : depth_first(TopLevelLoop))
267 // We only handle inner-most loops.
268 if (L->isInnermost())
269 Worklist.push_back(L);
270
271 // Now walk the identified inner loops.
272 bool Changed = false;
273 for (Loop *L : Worklist) {
274 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
275 !L->getExitingBlock())
276 continue;
277 const LoopAccessInfo &LAI = LAIs.getInfo(*L);
278 if (!LAI.hasConvergentOp() &&
280 !LAI.getPSE().getPredicate().isAlwaysTrue())) {
282 LI, DT, SE);
283 LVer.versionLoop();
284 LVer.annotateLoopWithNoAlias();
285 Changed = true;
286 LAIs.clear();
287 }
288 }
289
290 return Changed;
291}
292}
293
296 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
297 auto &LI = AM.getResult<LoopAnalysis>(F);
299 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
300
301 if (runImpl(&LI, LAIs, &DT, &SE))
303 return PreservedAnalyses::all();
304}
static bool runImpl(Function &F, const TargetLowering &TLI)
#define Check(C,...)
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
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
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:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:296
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:168
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:239
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1137
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1514
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:97
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:381
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1642
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
This analysis provides dependence information for the memory accesses of a loop.
const LoopAccessInfo & getInfo(Loop &L)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
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:566
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks 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...
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:39
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition: LoopInfo.cpp:480
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition: MDBuilder.h:174
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition: MDBuilder.h:167
Metadata node.
Definition: Metadata.h:1069
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:1114
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
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...
const SCEVPredicate & getPredicate() const
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
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.
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
unsigned getNumOperands() const
Definition: User.h:191
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator end()
Definition: ValueMap.h:135
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
iterator_range< user_iterator > users()
Definition: Value.h:421
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
Definition: LoopUtils.cpp:1894
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
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:57
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
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)
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.