97 #define DEBUG_TYPE "loop-versioning-licm" 105 cl::desc(
"LoopVersioningLICM's minimum allowed percentage" 106 "of possible invariant instructions per loop"),
111 "licm-versioning-max-depth-threshold",
113 "LoopVersioningLICM's threshold for maximum allowed loop nest/depth"),
132 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
149 struct LoopVersioningLICM :
public LoopPass {
174 StringRef getPassName()
const override {
return "Loop Versioning for LICM"; }
181 LoadAndStoreCounter = 0;
182 InvariantCounter = 0;
183 IsReadOnlyLoop =
true;
190 AutoResetter(LoopVersioningLICM &LVLICM) : LVLICM(LVLICM) {}
191 ~AutoResetter() { LVLICM.reset(); }
194 LoopVersioningLICM &LVLICM;
211 Loop *CurLoop =
nullptr;
214 std::unique_ptr<AliasSetTracker> CurAST;
217 unsigned LoopDepthThreshold;
220 float InvariantThreshold;
223 unsigned LoadAndStoreCounter = 0;
226 unsigned InvariantCounter = 0;
229 bool IsReadOnlyLoop =
true;
234 bool isLegalForVersioning();
235 bool legalLoopStructure();
236 bool legalLoopInstructions();
237 bool legalLoopMemoryAccesses();
238 bool isLoopAlreadyVisited();
239 void setNoAliasToLoop(
Loop *VerLoop);
246 bool LoopVersioningLICM::legalLoopStructure() {
248 if (!CurLoop->isLoopSimplifyForm()) {
253 if (!CurLoop->getSubLoops().empty()) {
258 if (CurLoop->getNumBackEdges() != 1) {
263 if (!CurLoop->getExitingBlock()) {
270 if (CurLoop->getExitingBlock() != CurLoop->getLoopLatch()) {
276 if (CurLoop->isAnnotatedParallel()) {
281 if (CurLoop->getLoopDepth() > LoopDepthThreshold) {
287 const SCEV *ExitCount = SE->getBackedgeTakenCount(CurLoop);
288 if (ExitCount == SE->getCouldNotCompute()) {
297 bool LoopVersioningLICM::legalLoopMemoryAccesses() {
298 bool HasMayAlias =
false;
299 bool TypeSafety =
false;
313 for (
const auto &
I : *CurAST) {
323 bool TypeCheck =
true;
326 HasMod |= AS.
isMod();
327 for (
const auto &A : AS) {
330 TypeCheck = (TypeCheck && (SomePtr->
getType() == Ptr->
getType()));
333 TypeSafety |= TypeCheck;
360 bool LoopVersioningLICM::instructionSafeForVersioning(
Instruction *
I) {
361 assert(I !=
nullptr &&
"Null instruction found!");
363 if (isa<CallInst>(I) && !AA->doesNotAccessMemory(
CallSite(I))) {
369 LLVM_DEBUG(
dbgs() <<
" May throw instruction found in loop body\n");
380 LoadAndStoreCounter++;
383 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
394 LoadAndStoreCounter++;
397 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
400 IsReadOnlyLoop =
false;
407 bool LoopVersioningLICM::legalLoopInstructions() {
409 LoadAndStoreCounter = 0;
410 InvariantCounter = 0;
411 IsReadOnlyLoop =
true;
415 for (
auto *Block : CurLoop->getBlocks())
416 for (
auto &Inst : *Block) {
418 if (!instructionSafeForVersioning(&Inst)) {
421 <<
" Unsafe Loop Instruction";
427 LAI = &LAA->getInfo(CurLoop);
429 if (LAI->getRuntimePointerChecking()->getChecks().empty()) {
434 if (LAI->getNumRuntimePointerChecks() >
437 dbgs() <<
" LAA: Runtime checks are more than threshold !!\n");
440 CurLoop->getStartLoc(),
441 CurLoop->getHeader())
442 <<
"Number of runtime checks " 443 <<
NV(
"RuntimeChecks", LAI->getNumRuntimePointerChecks())
444 <<
" exceeds threshold " 450 if (!InvariantCounter) {
455 if (IsReadOnlyLoop) {
461 if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
464 <<
" Invariant load & store are less then defined threshold\n");
466 << ((InvariantCounter * 100) / LoadAndStoreCounter)
469 << InvariantThreshold <<
"%\n");
472 CurLoop->getStartLoc(),
473 CurLoop->getHeader())
474 <<
"Invariant load & store " 475 <<
NV(
"LoadAndStoreCounter",
476 ((InvariantCounter * 100) / LoadAndStoreCounter))
477 <<
" are less then defined threshold " 478 <<
NV(
"Threshold", InvariantThreshold);
488 bool LoopVersioningLICM::isLoopAlreadyVisited() {
500 bool LoopVersioningLICM::isLegalForVersioning() {
504 if (isLoopAlreadyVisited()) {
506 dbgs() <<
" Revisiting loop in LoopVersioningLICM not allowed.\n\n");
510 if (!legalLoopStructure()) {
512 dbgs() <<
" Loop structure not suitable for LoopVersioningLICM\n\n");
515 CurLoop->getStartLoc(),
516 CurLoop->getHeader())
517 <<
" Unsafe Loop structure";
522 if (!legalLoopInstructions()) {
525 <<
" Loop instructions not suitable for LoopVersioningLICM\n\n");
529 if (!legalLoopMemoryAccesses()) {
532 <<
" Loop memory access not suitable for LoopVersioningLICM\n\n");
535 CurLoop->getStartLoc(),
536 CurLoop->getHeader())
537 <<
" Unsafe Loop memory access";
542 LLVM_DEBUG(
dbgs() <<
" Loop Versioning found to be beneficial\n\n");
545 CurLoop->getStartLoc(), CurLoop->getHeader())
546 <<
" Versioned loop for LICM." 547 <<
" Number of runtime checks we had to insert " 548 <<
NV(
"RuntimeChecks", LAI->getNumRuntimePointerChecks());
558 void LoopVersioningLICM::setNoAliasToLoop(
Loop *VerLoop) {
563 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain(
"LVDomain");
566 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
569 for (
auto *Block : CurLoop->getBlocks()) {
570 for (
auto &Inst : *Block) {
572 if (!Inst.mayReadFromMemory() && !Inst.mayWriteToMemory())
593 AutoResetter Resetter(*
this);
598 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
599 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
600 LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
601 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
608 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
614 bool Changed =
false;
619 if (isLegalForVersioning()) {
623 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
632 "llvm.mem.parallel_loop_access");
643 "Loop Versioning For LICM",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static unsigned RuntimeMemoryCheckThreshold
performing memory disambiguation checks at runtime do not make more than this number of comparisons...
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
DiagnosticInfoOptimizationBase::Argument NV
Compute iterated dominance frontiers using a linear time algorithm.
This is the interface for a simple mod/ref and alias analysis over globals.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDString * get(LLVMContext &Context, StringRef Str)
static cl::opt< float > LVInvarThreshold("licm-versioning-invariant-threshold", cl::desc("LoopVersioningLICM's minimum allowed percentage" "of possible invariant instructions per loop"), cl::init(25), cl::Hidden)
Threshold minimum allowed percentage for possible invariant instructions in a loop.
The main scalar evolution driver.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
INITIALIZE_PASS_BEGIN(LoopVersioningLICM, "loop-versioning-licm", "Loop Versioning For LICM", false, false) INITIALIZE_PASS_END(LoopVersioningLICM
LLVMContext & getContext() const
All values hold a context through their type.
const MDOperand & getOperand(unsigned I) const
An instruction for reading from memory.
LLVMContext & getContext() const
Get the context in which this basic block lives.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static const char * LICMVersioningMetaData
BlockT * getHeader() const
Type * getType() const
All values are typed, get the type of this value.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
static cl::opt< unsigned > LVLoopDepthThreshold("licm-versioning-max-depth-threshold", cl::desc("LoopVersioningLICM's threshold for maximum allowed loop nest/depth"), cl::init(2), cl::Hidden)
Threshold for maximum allowed loop nest/depth.
An instruction for storing to memory.
void versionLoop()
Performs the CFG manipulation part of versioning the loop including the DominatorTree and LoopInfo up...
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Loop * getVersionedLoop()
Returns the versioned loop.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
This is an important class for using LLVM in a threaded context.
This analysis provides dependence information for the memory accesses of a loop.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool mayThrow() const
Return true if this instruction may throw an exception.
Represent the analysis usage information of a pass.
Value * getPointerOperand()
Pass * createLoopVersioningLICMPass()
Optional< const MDOperand * > findStringMetadataForLoop(Loop *TheLoop, StringRef Name)
Find string metadata for loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void initializeLoopVersioningLICMPass(PassRegistry &)
AnalysisUsage & addRequiredID(const void *ID)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Drive the analysis of memory accesses in the loop.
static cl::opt< bool > NoAliases("riscv-no-aliases", cl::desc("Disable the emission of assembler pseudo instructions"), cl::init(false), cl::Hidden)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static MDNode * createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V)
Create MDNode for input string.
LLVM Value Representation.
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
bool isForwardingAliasSet() const
Return true if this alias set should be ignored as part of the AliasSetTracker object.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned getNumOperands() const
Return number of MDNode operands.
Value * getPointerOperand()
Loop * getNonVersionedLoop()
Returns the fall-back loop.
loop versioning Loop Versioning For LICM