90#define DEBUG_TYPE "loop-versioning-licm"
96struct LoopVersioningLICM {
104 :
AA(
AA), SE(SE), LAIs(LAIs), LI(LI), CurLoop(CurLoop),
105 LoopDepthThreshold(Opts.licm_versioning_max_depth_threshold),
106 InvariantThreshold(Opts.licm_versioning_invariant_threshold), ORE(ORE) {
130 unsigned LoopDepthThreshold;
133 float InvariantThreshold;
136 unsigned LoadAndStoreCounter = 0;
139 unsigned InvariantCounter = 0;
142 bool IsReadOnlyLoop =
true;
147 bool isLegalForVersioning();
148 bool legalLoopStructure();
149 bool legalLoopInstructions();
150 bool legalLoopMemoryAccesses();
151 bool isLoopAlreadyVisited();
158bool LoopVersioningLICM::legalLoopStructure() {
209bool LoopVersioningLICM::legalLoopMemoryAccesses() {
211 BatchAAResults BAA(*AA);
212 AliasSetTracker AST(BAA);
231 bool HasMayAlias =
false;
232 bool TypeSafety =
false;
234 for (
const auto &
I : AST) {
235 const AliasSet &AS =
I;
244 bool TypeCheck =
true;
247 HasMod |= AS.
isMod();
248 for (
const auto &MemLoc : AS) {
249 const Value *Ptr = MemLoc.Ptr;
256 TypeCheck = (TypeCheck && (SomePtr->
getType() == Ptr->
getType()));
259 TypeSafety |= TypeCheck;
287bool LoopVersioningLICM::instructionSafeForVersioning(Instruction *
I) {
288 assert(
I !=
nullptr &&
"Null instruction found!");
314 LLVM_DEBUG(
dbgs() <<
" May throw instruction found in loop body\n");
319 if (
I->mayReadFromMemory()) {
321 if (!Ld || !Ld->isSimple()) {
325 LoadAndStoreCounter++;
326 Value *Ptr = Ld->getPointerOperand();
333 else if (
I->mayWriteToMemory()) {
335 if (!St || !St->isSimple()) {
339 LoadAndStoreCounter++;
340 Value *Ptr = St->getPointerOperand();
344 if (!
any_of(Pointers, [&](
auto &
P) {
return P.PointerValue == Ptr; })) {
345 LLVM_DEBUG(
dbgs() <<
" Found a store without a runtime check.\n");
352 IsReadOnlyLoop =
false;
359bool LoopVersioningLICM::legalLoopInstructions() {
361 LoadAndStoreCounter = 0;
362 InvariantCounter = 0;
363 IsReadOnlyLoop =
true;
366 LAI = &LAIs.
getInfo(*CurLoop,
true);
375 for (
auto &Inst : *
Block) {
377 if (!instructionSafeForVersioning(&Inst)) {
379 return OptimizationRemarkMissed(
DEBUG_TYPE,
"IllegalLoopInst", &Inst)
380 <<
" Unsafe Loop Instruction";
389 dbgs() <<
" LAA: Runtime checks are more than threshold !!\n");
391 return OptimizationRemarkMissed(
DEBUG_TYPE,
"RuntimeCheck",
394 <<
"Number of runtime checks "
396 <<
" exceeds threshold "
402 if (!InvariantCounter) {
407 if (IsReadOnlyLoop) {
413 if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
416 <<
" Invariant load & store are less then defined threshold\n");
418 << ((InvariantCounter * 100) / LoadAndStoreCounter)
421 << InvariantThreshold <<
"%\n");
423 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InvariantThreshold",
426 <<
"Invariant load & store "
427 <<
NV(
"LoadAndStoreCounter",
428 ((InvariantCounter * 100) / LoadAndStoreCounter))
429 <<
" are less then defined threshold "
430 <<
NV(
"Threshold", InvariantThreshold);
440bool LoopVersioningLICM::isLoopAlreadyVisited() {
452bool LoopVersioningLICM::isLegalForVersioning() {
456 if (isLoopAlreadyVisited()) {
458 dbgs() <<
" Revisiting loop in LoopVersioningLICM not allowed.\n\n");
462 if (!legalLoopStructure()) {
464 dbgs() <<
" Loop structure not suitable for LoopVersioningLICM\n\n");
466 return OptimizationRemarkMissed(
DEBUG_TYPE,
"IllegalLoopStruct",
469 <<
" Unsafe Loop structure";
474 if (!legalLoopInstructions()) {
477 <<
" Loop instructions not suitable for LoopVersioningLICM\n\n");
481 if (!legalLoopMemoryAccesses()) {
484 <<
" Loop memory access not suitable for LoopVersioningLICM\n\n");
486 return OptimizationRemarkMissed(
DEBUG_TYPE,
"IllegalLoopMemoryAccess",
489 <<
" Unsafe Loop memory access";
494 LLVM_DEBUG(
dbgs() <<
" Loop Versioning found to be beneficial\n\n");
496 return OptimizationRemark(
DEBUG_TYPE,
"IsLegalForVersioning",
498 <<
" Versioned loop for LICM."
499 <<
" Number of runtime checks we had to insert "
505bool LoopVersioningLICM::run(DominatorTree *DT) {
515 if (isLegalForVersioning()) {
520 CurLoop, &LI, DT, SE);
530 "llvm.mem.parallel_loop_access");
532 LVer.annotateLoopWithNoAlias();
544 const Function *
F = L.getHeader()->getParent();
548 if (!LoopVersioningLICM(ScalarOptions::Global,
AA, SE, &ORE, LAIs, LAR.
LI, &L)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for a simple mod/ref and alias analysis over globals.
static const char * LICMVersioningMetaData
This file defines the SmallVector class.
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
bool isForwardingAliasSet() const
Return true if this alias set should be ignored as part of the AliasSetTracker object.
bool cannotDuplicate() const
Determine if the invoke cannot be duplicated.
bool isConvergent() const
Determine if the invoke is convergent.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
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.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &LAR, LPMUpdater &U)
Represents a single loop in the control flow graph.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
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.
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
The main scalar evolution driver.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
Type * getType() const
All values are typed, get the type of this value.
Abstract Attribute helper functions.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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 TransformationMode hasLICMVersioningTransformation(const Loop *L)
@ TM_Disable
The transformation should not be applied.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static LLVM_ABI unsigned RuntimeMemoryCheckThreshold
\When performing memory disambiguation checks at runtime do not make more than this number of compari...