74 #define DEBUG_TYPE "licm" 76 STATISTIC(NumSunk,
"Number of instructions sunk out of loop");
77 STATISTIC(NumHoisted,
"Number of instructions hoisted out of loop");
78 STATISTIC(NumMovedLoads,
"Number of load insts hoisted or sunk");
79 STATISTIC(NumMovedCalls,
"Number of call insts hoisted or sunk");
80 STATISTIC(NumPromoted,
"Number of memory locations promoted to registers");
85 cl::desc(
"Disable memory promotion in LICM pass"));
89 cl::desc(
"Max num uses visited for identifying load " 90 "invariance in loop using invariant start (default = 8)"));
117 struct LoopInvariantCodeMotion {
124 return LoopToAliasSetMap;
134 struct LegacyLICMPass :
public LoopPass {
145 for (
auto <AS :
LICM.getLoopToAliasSetMap())
147 LICM.getLoopToAliasSetMap().clear();
151 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
153 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
159 return LICM.runOnLoop(L,
160 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
161 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
162 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
163 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
164 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
166 SE ? &SE->getSE() :
nullptr, MSSA, &ORE,
false);
184 bool doFinalization()
override {
186 "Didn't free loop alias sets");
191 LoopInvariantCodeMotion
LICM;
199 void deleteAnalysisValue(
Value *V,
Loop *L)
override;
202 void deleteAnalysisLoop(
Loop *L)
override;
210 Function *
F = L.getHeader()->getParent();
216 "cached at a higher level");
218 LoopInvariantCodeMotion
LICM;
219 if (!LICM.runOnLoop(&L, &AR.
AA, &AR.
LI, &AR.
DT, &AR.
TLI, &AR.
TTI, &AR.
SE,
249 bool LoopInvariantCodeMotion::runOnLoop(
253 bool Changed =
false;
278 CurAST, &SafetyInfo, ORE);
281 CurAST, &SafetyInfo, ORE);
300 if (!HasCatchSwitch) {
304 InsertPts.
push_back(&*ExitBlock->getFirstInsertionPt());
308 bool Promoted =
false;
315 if (
AS.isForwardingAliasSet() || !
AS.isMod() || !
AS.isMustAlias() ||
321 "Must alias set should have at least one pointer element in it!");
324 for (
const auto &ASI :
AS)
325 PointerMustAliases.
insert(ASI.getValue());
328 InsertPts, PIC, LI, DT, TLI, L,
329 CurAST, &SafetyInfo, ORE);
350 "Parent loop not left in LCSSA form after LICM!");
355 LoopToAliasSetMap[L] = CurAST;
376 assert(N !=
nullptr && AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
377 CurLoop !=
nullptr && CurAST !=
nullptr && SafetyInfo !=
nullptr &&
378 "Unexpected input to sinkRegion");
385 bool Changed =
false;
413 bool FreeInLoop =
false;
416 if (
sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
440 assert(N !=
nullptr && AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
441 CurLoop !=
nullptr && CurAST !=
nullptr && SafetyInfo !=
nullptr &&
442 "Unexpected input to hoistRegion");
448 bool Changed =
false;
459 bool IsMustExecute = CurLoop->
getHeader() == BB;
488 I, DT, CurLoop, SafetyInfo, ORE,
490 Changed |=
hoist(I, DT, CurLoop, SafetyInfo, ORE);
496 if (I.
getOpcode() == Instruction::FDiv &&
501 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
503 ReciprocalDivisor->insertBefore(&I);
506 BinaryOperator::CreateFMul(I.
getOperand(0), ReciprocalDivisor);
508 Product->insertAfter(&I);
512 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
534 cast<PointerType>(Addr->
getType())->getElementType());
540 unsigned BitcastsVisited = 0;
543 while (Addr->
getType() != PtrInt8Ty) {
548 Addr = BC->getOperand(0);
551 unsigned UsesVisited = 0;
554 for (
auto *U : Addr->
users()) {
564 unsigned InvariantSizeInBits =
570 if (LocSizeInBits <= InvariantSizeInBits &&
584 const bool SinkingToLoopBody = !SafetyInfo;
586 if (
LoadInst *LI = dyn_cast<LoadInst>(&I)) {
587 if (!LI->isUnordered())
597 if (LI->isAtomic() && SinkingToLoopBody)
606 if (LI->getType()->isSized())
610 LI->getAAMetadata(AAInfo);
616 if (ORE && Invalidated && CurLoop->
isLoopInvariant(LI->getPointerOperand()))
619 DEBUG_TYPE,
"LoadWithLoopInvariantAddressInvalidated", LI)
620 <<
"failed to move load with loop-invariant address " 621 "because the loop may invalidate its value";
625 }
else if (
CallInst *CI = dyn_cast<CallInst>(&I)) {
627 if (isa<DbgInfoIntrinsic>(I))
643 for (
Value *
Op : CI->arg_operands())
644 if (
Op->getType()->isPointerTy() &&
652 bool FoundMod =
false;
654 if (!
AS.isForwardingAliasSet() &&
AS.isMod()) {
670 if (!isa<BinaryOperator>(I) && !isa<CastInst>(
I) && !isa<SelectInst>(I) &&
671 !isa<GetElementPtrInst>(
I) && !isa<CmpInst>(I) &&
672 !isa<InsertElementInst>(
I) && !isa<ExtractElementInst>(I) &&
673 !isa<ShuffleVectorInst>(
I) && !isa<ExtractValueInst>(I) &&
674 !isa<InsertValueInst>(
I))
679 if (SinkingToLoopBody)
712 for (
const User *U :
GEP->users()) {
716 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
737 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
745 if (isa<CallInst>(I))
746 if (!BlockColors.empty() &&
747 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
767 if (
auto *CI = dyn_cast<CallInst>(&I)) {
774 for (
unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
775 BundleIdx != BundleEnd; ++BundleIdx) {
783 if (!BlockColors.empty()) {
784 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
785 assert(CV.
size() == 1 &&
"non-unique color for exit block!");
810 if (
Instruction *OInst = dyn_cast<Instruction>(*OI))
812 if (!OLoop->contains(&PN)) {
815 OInst->getName() +
".lcssa", &ExitBlock.
front());
828 "Expect only trivially replaceable PHI");
831 auto It = SunkCopies.
find(ExitBlock);
832 if (It != SunkCopies.
end())
835 New = SunkCopies[ExitBlock] =
868 assert(ExitBlockSet.count(ExitBB) &&
"Expect the PHI is in an exit block.");
904 while (!PredBBs.
empty()) {
907 "Expect all predecessors are in the loop");
910 ExitBB, PredBB,
".split.loop.exit", DT, LI,
true);
914 if (!BlockColors.empty()) {
918 ColorVector &ColorsForNewBlock = BlockColors[NewPred];
919 ColorVector &ColorsForOldBlock = BlockColors[PredBB];
920 ColorsForNewBlock = ColorsForOldBlock;
938 <<
"sinking " <<
ore::NV(
"Inst", &I);
940 bool Changed =
false;
941 if (isa<LoadInst>(I))
943 else if (isa<CallInst>(I))
951 auto *
User = cast<Instruction>(*UI);
952 Use &U = UI.getUse();
994 if (VisitedUsers.
empty())
1011 for (
auto *UI :
Users) {
1012 auto *
User = cast<Instruction>(UI);
1019 "The LCSSA PHI is not in an exit block!");
1022 SafetyInfo, CurLoop);
1037 LLVM_DEBUG(
dbgs() <<
"LICM hoisting to " << Preheader->getName() <<
": " << I
1063 if (!isa<CallInst>(I))
1066 if (isa<LoadInst>(I))
1068 else if (isa<CallInst>(I))
1079 const Loop *CurLoop,
1086 bool GuaranteedToExecute =
1089 if (!GuaranteedToExecute) {
1094 DEBUG_TYPE,
"LoadWithLoopInvariantAddressCondExecuted", LI)
1095 <<
"failed to hoist load with loop-invariant address " 1096 "because load is conditionally executed";
1100 return GuaranteedToExecute;
1114 bool UnorderedAtomic;
1124 I->getName() +
".lcssa", &BB->
front());
1138 bool UnorderedAtomic,
const AAMDNodes &AATags)
1140 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
1141 LI(li), DL(std::move(dl)), Alignment(alignment),
1142 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
1147 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
1148 Ptr = LI->getOperand(0);
1151 return PointerMustAliases.
count(Ptr);
1154 void doExtraRewritesBeforeFinalDeletion()
const override {
1159 for (
unsigned i = 0, e = LoopExitBlocks.
size(); i != e; ++i) {
1161 Value *LiveInValue =
SSA.GetValueInMiddleOfBlock(ExitBlock);
1162 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1163 Value *
Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1166 if (UnorderedAtomic)
1175 void replaceLoadWithValue(
LoadInst *LI,
Value *V)
const override {
1186 if (isa<AllocaInst>(Object))
1220 assert(LI !=
nullptr && DT !=
nullptr && CurLoop !=
nullptr &&
1221 CurAST !=
nullptr && SafetyInfo !=
nullptr &&
1222 "Unexpected Input to promoteLoopAccessesToScalars");
1224 Value *SomePtr = *PointerMustAliases.
begin();
1264 bool DereferenceableInPH =
false;
1265 bool SafeToInsertStore =
false;
1271 unsigned Alignment = 1;
1273 bool SawUnorderedAtomic =
false;
1274 bool SawNotAtomic =
false;
1279 bool IsKnownThreadLocalObject =
false;
1287 if (!isKnownNonEscaping(Object, TLI))
1291 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1297 for (
Value *ASIV : PointerMustAliases) {
1301 if (SomePtr->
getType() != ASIV->getType())
1314 if (!
Load->isUnordered())
1317 SawUnorderedAtomic |=
Load->isAtomic();
1318 SawNotAtomic |= !
Load->isAtomic();
1320 if (!DereferenceableInPH)
1329 if (!
Store->isUnordered())
1332 SawUnorderedAtomic |=
Store->isAtomic();
1333 SawNotAtomic |= !
Store->isAtomic();
1340 unsigned InstAlignment =
Store->getAlignment();
1345 if (!DereferenceableInPH || !SafeToInsertStore ||
1346 (InstAlignment > Alignment)) {
1348 DereferenceableInPH =
true;
1349 SafeToInsertStore =
true;
1350 Alignment =
std::max(Alignment, InstAlignment);
1360 if (!SafeToInsertStore)
1367 if (!DereferenceableInPH) {
1369 Store->getPointerOperand(),
Store->getAlignment(), MDL,
1376 if (LoopUses.
empty()) {
1379 }
else if (AATags) {
1391 if (SawUnorderedAtomic && SawNotAtomic)
1395 if (!DereferenceableInPH)
1402 if (!SafeToInsertStore) {
1403 if (IsKnownThreadLocalObject)
1404 SafeToInsertStore =
true;
1414 if (!SafeToInsertStore)
1418 LLVM_DEBUG(
dbgs() <<
"LICM: Promoting value stored to in loop: " << *SomePtr
1423 <<
"Moving accesses to memory location out of the loop";
1431 DebugLoc DL = LoopUses[0]->getDebugLoc();
1436 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1437 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1438 SawUnorderedAtomic, AATags);
1444 if (SawUnorderedAtomic)
1454 Promoter.run(LoopUses);
1470 LoopInvariantCodeMotion::collectAliasInfoForLoop(
Loop *L,
LoopInfo *LI,
1475 auto MapI = LoopToAliasSetMap.find(InnerL);
1479 if (MapI == LoopToAliasSetMap.end()) {
1485 if (CurAST !=
nullptr) {
1487 CurAST->
add(*InnerAST);
1495 LoopToAliasSetMap.erase(MapI);
1497 if (CurAST ==
nullptr)
1500 auto mergeLoop = [&](
Loop *L) {
1507 for (
Loop *InnerL : RecomputeLoops)
1529 void LegacyLICMPass::deleteAnalysisValue(
Value *V,
Loop *L) {
1539 void LegacyLICMPass::deleteAnalysisLoop(
Loop *L) {
1545 LICM.getLoopToAliasSetMap().erase(L);
1562 assert(CurLoop->
contains(BB) &&
"Only valid if BB is IN the loop");
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
bool canSplitPredecessors() const
A parsed version of the target data layout string in and methods for querying it. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Compute iterated dominance frontiers using a linear time algorithm.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
bool hasMetadataOtherThanDebugLoc() const
Return true if this instruction has metadata attached to it other than a debug location.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
void add(Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo)
These methods are used to add different types of instructions to the alias sets.
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
bool onlyReadsMemory(ImmutableCallSite CS)
Checks if the specified call is known to only read from non-volatile memory (or not access memory at ...
LLVMContext & getContext() const
All values hold a context through their type.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is free in the loop.
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
An instruction for reading from memory.
iv Induction Variable Users
void reserve(size_type N)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
DenseMap< BasicBlock *, ColorVector > BlockColors
iterator begin()
Instruction iterator methods.
Loop Invariant Code Motion
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
ArrayRef< BasicBlock * > get(BasicBlock *BB)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
This is the interface for a SCEV-based alias analysis.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE)
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
bool hasAllowReciprocal() const
Determine whether the allow-reciprocal flag is set.
A Use represents the edge between a Value definition and its users.
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Encapsulates MemorySSA, including all data associated with memory accesses.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
bool remove(const value_type &X)
Remove an item from the set vector.
BlockT * getHeader() const
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, false) INITIALIZE_PASS_END(LegacyLICMPass
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
AliasSet & getAliasSetForPointer(Value *P, LocationSize Size, const AAMDNodes &AAInfo)
Return the alias set that the specified pointer lives in.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, const AAMDNodes &AAInfo, AliasSetTracker *CurAST)
Return true if the body of this loop may store into the memory location pointed to by V...
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries...
FunctionModRefBehavior
Summary of how a function affects memory in the program.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
iterator begin()
Get an iterator to the beginning of the SetVector.
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), cl::desc("Disable memory promotion in LICM pass"))
Memory promotion is enabled by default.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock *> &, SmallVectorImpl< Instruction *> &, PredIteratorCache &, LoopInfo *, DominatorTree *, const TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
iterator find(const_arg_type_t< KeyT > Val)
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
Checks whether the given location points to constant memory, or if OrLocal is true whether it points ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
size_t size(BasicBlock *BB) const
bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS)
Return the behavior of the given call site.
Represent the analysis usage information of a pass.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Interval::pred_iterator pred_end(Interval *I)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void setAlignment(unsigned Align)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This function does not perform any non-local loads or stores to memory.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
static cl::opt< uint32_t > MaxNumUsesTraversed("licm-max-num-uses-traversed", cl::Hidden, cl::init(8), cl::desc("Max num uses visited for identifying load " "invariance in loop using invariant start (default = 8)"))
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo)
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
void copyValue(Value *From, Value *To)
This method should be used whenever a preexisting value in the program is copied or cloned...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FreeInLoop)
Return true if the only users of this instruction are outside of the loop.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
A lightweight accessor for an operand bundle meant to be passed around by value.
iterator_range< user_iterator > users()
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI=nullptr)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to read and write at most from objects poin...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator insert(iterator where, pointer New)
Captures loop safety information.
static Instruction * CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo)
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
bool empty() const
Determine if the SetVector is empty or not.
user_iterator_impl< User > user_iterator
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
SmallVector< DomTreeNode *, 16 > collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
void setAlignment(unsigned Align)
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
void initializeLegacyLICMPassPass(PassRegistry &)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager's analysis pass to compute loop information.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
This is the interface for LLVM's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested...
bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if the hoister and sinker can handle this instruction.
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...
op_range incoming_values()
iterator_range< block_iterator > blocks() const
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo)
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
static IntegerType * getInt8Ty(LLVMContext &C)
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, bool FreeInLoop)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
void deleteValue(Value *PtrVal)
This method is used to remove a pointer value from the AliasSetTracker entirely.
loop versioning Loop Versioning For LICM
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop)