85 #define DEBUG_TYPE "loop-unswitch" 87 STATISTIC(NumBranches,
"Number of branches unswitched");
88 STATISTIC(NumSwitches,
"Number of switches unswitched");
89 STATISTIC(NumGuards,
"Number of guards unswitched");
90 STATISTIC(NumSelects ,
"Number of selects unswitched");
91 STATISTIC(NumTrivial ,
"Number of unswitches that are trivial");
92 STATISTIC(NumSimplify,
"Number of simplifications of unswitched code");
93 STATISTIC(TotalInsts,
"Total number of instructions analyzed");
103 class LUAnalysisCache {
104 using UnswitchedValsMap =
106 using UnswitchedValsIt = UnswitchedValsMap::iterator;
108 struct LoopProperties {
109 unsigned CanBeUnswitchedCount;
110 unsigned WasUnswitchedCount;
111 unsigned SizeEstimation;
112 UnswitchedValsMap UnswitchedVals;
117 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
118 using LoopPropsMapIt = LoopPropsMap::iterator;
120 LoopPropsMap LoopsProperties;
121 UnswitchedValsMap *CurLoopInstructions =
nullptr;
122 LoopProperties *CurrentLoopProperties =
nullptr;
141 LUAnalysisCache() : MaxSize(
Threshold) {}
149 void forgetLoop(
const Loop *L);
161 bool CostAllowsUnswitching();
166 void cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
170 class LoopUnswitch :
public LoopPass {
177 std::vector<Loop*> LoopProcessWorklist;
179 LUAnalysisCache BranchesInfo;
181 bool OptimizeForSize;
182 bool redoLoop =
false;
184 Loop *currentLoop =
nullptr;
187 std::unique_ptr<MemorySSAUpdater> MSSAU;
197 std::vector<BasicBlock*> LoopBlocks;
199 std::vector<BasicBlock*> NewBlocks;
201 bool hasBranchDivergence;
206 explicit LoopUnswitch(
bool Os =
false,
bool hasBranchDivergence =
false)
207 :
LoopPass(ID), OptimizeForSize(Os),
208 hasBranchDivergence(hasBranchDivergence) {
213 bool processCurrentLoop();
214 bool isUnreachableDueToPreviousUnswitching(
BasicBlock *);
226 if (hasBranchDivergence)
232 void releaseMemory()
override {
233 BranchesInfo.forgetLoop(currentLoop);
236 void initLoopData() {
243 void SplitExitEdges(
Loop *L,
246 bool TryTrivialLoopUnswitch(
bool &Changed);
255 void RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
258 void EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
263 void SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L);
277 LoopPropsMapIt PropsIt;
279 std::tie(PropsIt, Inserted) =
280 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
282 LoopProperties &Props = PropsIt->second;
303 Props.SizeEstimation = Metrics.
NumInsts;
304 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
305 Props.WasUnswitchedCount = 0;
306 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
310 <<
", contents cannot be " 317 CurrentLoopProperties = &Props;
318 CurLoopInstructions = &Props.UnswitchedVals;
324 void LUAnalysisCache::forgetLoop(
const Loop *L) {
325 LoopPropsMapIt LIt = LoopsProperties.find(L);
327 if (LIt != LoopsProperties.end()) {
328 LoopProperties &Props = LIt->second;
329 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
330 Props.SizeEstimation;
331 LoopsProperties.erase(LIt);
334 CurrentLoopProperties =
nullptr;
335 CurLoopInstructions =
nullptr;
342 (*CurLoopInstructions)[
SI].insert(V);
346 bool LUAnalysisCache::isUnswitched(
const SwitchInst *SI,
const Value *V) {
347 return (*CurLoopInstructions)[
SI].count(V);
350 bool LUAnalysisCache::CostAllowsUnswitching() {
351 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
357 void LUAnalysisCache::cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
359 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360 LoopProperties &OldLoopProps = *CurrentLoopProperties;
361 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
365 --OldLoopProps.CanBeUnswitchedCount;
366 ++OldLoopProps.WasUnswitchedCount;
367 NewLoopProps.WasUnswitchedCount = 0;
368 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
372 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
377 for (UnswitchedValsIt
I = Insts.begin();
I != Insts.end(); ++
I) {
380 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
381 assert(NewInst &&
"All instructions that are in SrcBB must be in VMap.");
383 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
400 return new LoopUnswitch(Os, hasBranchDivergence);
425 auto CacheIt = Cache.
find(Cond);
426 if (CacheIt != Cache.
end())
427 return CacheIt->second;
437 if (isa<Constant>(Cond))
return nullptr;
449 if (BO->getOpcode() == Instruction::And ||
450 BO->getOpcode() == Instruction::Or) {
453 switch (ParentChain) {
455 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
459 NewChain = BO->getOpcode() == Instruction::Or ?
OC_OpChainOr :
463 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
477 ParentChain = NewChain;
482 ParentChain, Cache)) {
488 ParentChain = NewChain;
490 ParentChain, Cache)) {
497 Cache[Cond] =
nullptr;
514 "Do not expect a partial LIV with mixed operator chain");
515 return {FCond, OpChain};
522 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
524 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
526 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
528 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
529 MSSAU = make_unique<MemorySSAUpdater>(MSSA);
530 assert(DT &&
"Cannot update MemorySSA without a valid DomTree.");
542 bool Changed =
false;
548 Changed |= processCurrentLoop();
559 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(
BasicBlock *BB) {
562 while (currentLoop->
contains(DomBB)) {
566 DomBB = Node->getBlock();
572 if (!isa<ConstantInt>(Cond))
600 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
603 auto hasUndefInPHI = [](
PHINode &PN) {
604 for (
Value *Opd : PN.incoming_values()) {
605 if (isa<UndefValue>(Opd))
612 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
616 if (isa<UndefValue>(SI.getTrueValue()) ||
617 isa<UndefValue>(SI.getFalseValue()))
623 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
629 bool LoopUnswitch::processCurrentLoop() {
630 bool Changed =
false;
649 if (!BranchesInfo.countLoop(
650 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
656 if (TryTrivialLoopUnswitch(Changed)) {
662 if (OptimizeForSize ||
682 for (
const auto BB : currentLoop->
blocks()) {
683 for (
auto &
I : *BB) {
688 if (
auto *II = dyn_cast<InvokeInst>(&
I))
689 if (!II->getUnwindDest()->canSplitPredecessors())
691 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
723 if (SanitizeMemory &&
727 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
731 if (isUnreachableDueToPreviousUnswitching(*
I))
736 if (BI->isConditional()) {
740 currentLoop, Changed).
first;
747 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
751 std::tie(LoopCond, OpChain) =
755 if (LoopCond && NumCases) {
766 if (BranchesInfo.isUnswitched(SI, AllZero))
769 UnswitchVal = AllZero;
774 if (BranchesInfo.isUnswitched(SI, AllOne))
777 UnswitchVal = AllOne;
780 "Expect to unswitch on trivial chain");
784 for (
auto Case : SI->
cases()) {
785 Constant *UnswitchValCandidate = Case.getCaseValue();
786 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
787 UnswitchVal = UnswitchValCandidate;
796 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
802 BranchesInfo.setUnswitched(SI, UnswitchVal);
811 if (
SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
813 currentLoop, Changed).
first;
814 if (LoopCond && UnswitchIfProfitable(LoopCond,
832 std::set<BasicBlock*> &Visited) {
833 if (!Visited.insert(BB).second) {
841 if (ExitBB)
return false;
856 if (
I.mayHaveSideEffects())
866 std::set<BasicBlock*> Visited;
877 bool LoopUnswitch::UnswitchIfProfitable(
Value *LoopCond,
Constant *Val,
880 if (!BranchesInfo.CostAllowsUnswitching()) {
883 <<
" at non-trivial condition '" << *Val
884 <<
"' == " << *LoopCond <<
"\n" 885 <<
". Cost too high.\n");
888 if (hasBranchDivergence &&
889 getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
892 <<
" at non-trivial condition '" << *Val
893 <<
"' == " << *LoopCond <<
"\n" 894 <<
". Condition is divergent.\n");
898 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
929 void LoopUnswitch::EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
935 assert(TrueDest != FalseDest &&
"Branch targets should be different");
938 Value *BranchVal = LIC;
939 bool Swapped =
false;
940 if (!isa<ConstantInt>(Val) ||
952 auto *OldBranchParent = OldBranch->
getParent();
956 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
968 if (TrueDest != OldBranchSucc)
970 if (FalseDest != OldBranchSucc)
974 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
980 MSSAU->applyUpdates(Updates, *DT);
1001 <<
" blocks] in Function " 1003 <<
" on cond: " << *Val <<
" == " << *Cond <<
"\n");
1006 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1007 SEWP->getSE().forgetTopmostLoop(L);
1029 assert(OldBranch &&
"Failed to split the preheader");
1030 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1043 RewriteLoopBodyWithConditionConstant(L, Cond, Val,
false);
1054 bool LoopUnswitch::TryTrivialLoopUnswitch(
bool &Changed) {
1080 if (!currentLoop->
contains(CurrentBB) || !Visited.
insert(CurrentBB).second)
1087 if (
I.mayHaveSideEffects())
1090 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1091 if (BI->isUnconditional()) {
1092 CurrentBB = BI->getSuccessor(0);
1094 CurrentBB = BI->getSuccessor(0);
1096 CurrentBB = BI->getSuccessor(1);
1101 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1114 CurrentTerm = CurrentBB->getTerminator();
1122 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1124 if (!BI->isConditional())
1128 currentLoop, Changed).
first;
1132 if (!LoopCond || LoopCond != BI->getCondition())
1140 BI->getSuccessor(0)))) {
1143 BI->getSuccessor(1)))) {
1149 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1155 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1159 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1162 currentLoop, Changed).
first;
1175 for (
auto Case : SI->
cases()) {
1177 if ((LoopExitCandidate =
1184 if (BranchesInfo.isUnswitched(SI, CaseVal))
1186 LoopExitBB = LoopExitCandidate;
1194 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1197 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1201 BranchesInfo.setUnswitched(SI, CondVal);
1210 void LoopUnswitch::SplitExitEdges(
Loop *L,
1213 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1228 void LoopUnswitch::UnswitchNontrivialCondition(
Value *LIC,
Constant *Val,
1233 <<
" blocks] in Function " << F->
getName() <<
" when '" 1234 << *Val <<
"' == " << *LIC <<
"\n");
1238 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1239 SEWP->getSE().forgetTopmostLoop(L);
1247 SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1248 LoopBlocks.push_back(NewPreheader);
1258 SplitExitEdges(L, ExitBlocks);
1265 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.
begin(), ExitBlocks.
end());
1270 NewBlocks.reserve(LoopBlocks.size());
1272 for (
unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1275 NewBlocks.push_back(NewBB);
1276 VMap[LoopBlocks[i]] = NewBB;
1284 NewBlocks[0]->getIterator(), F->
end());
1291 BranchesInfo.cloneData(NewLoop, L, VMap);
1300 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1301 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1303 if (
Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1304 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1307 "Exit block should have been split to have one successor!");
1312 for (
PHINode &PN : ExitSucc->phis()) {
1313 Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
1316 PN.addIncoming(V, NewExit);
1321 &*ExitSucc->getFirstInsertionPt());
1334 for (
unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1338 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
1347 "Preheader splitting did not work correctly!");
1354 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1358 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1363 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1372 LoopProcessWorklist.push_back(NewLoop);
1384 RewriteLoopBodyWithConditionConstant(L, LIC, Val,
false);
1389 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1390 LICHandle && !isa<Constant>(LICHandle))
1391 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
true);
1399 std::vector<Instruction*> &Worklist) {
1401 Worklist.erase(
std::remove(Worklist.begin(), Worklist.end(),
I),
1408 std::vector<Instruction*> &Worklist,
1410 LLVM_DEBUG(
dbgs() <<
"Replace with '" << *V <<
"': " << *I <<
"\n");
1415 Worklist.push_back(
Use);
1419 Worklist.push_back(cast<Instruction>(U));
1431 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
1434 assert(!isa<Constant>(LIC) &&
"Why are we unswitching on a constant?");
1445 std::vector<Instruction*> Worklist;
1450 if (IsEqual || (isa<ConstantInt>(Val) &&
1457 !cast<ConstantInt>(Val)->getZExtValue());
1463 Worklist.push_back(UI);
1469 SimplifyCode(Worklist, L);
1483 if (
Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1499 Worklist.push_back(UI);
1503 if (!SI || !isa<ConstantInt>(Val))
continue;
1526 if (Latch && DT->
dominates(SISucc, Latch))
1533 SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1546 NewSISucc->getTerminator()->eraseFromParent();
1550 for (
PHINode &PN : NewSISucc->phis())
1551 PN.setIncomingValue(PN.getBasicBlockIndex(Switch),
1560 SimplifyCode(Worklist, L);
1571 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L) {
1573 while (!Worklist.empty()) {
1575 Worklist.pop_back();
1584 Worklist.push_back(
Use);
1588 MSSAU->removeMemoryAccess(I);
1604 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1605 if (BI->isUnconditional()) {
1611 if (!SinglePred)
continue;
1612 assert(SinglePred == Pred &&
"CFG broken");
1629 MSSAU->moveAllAfterMergeBlocks(Succ, Pred, BI);
1632 BI->eraseFromParent();
1657 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void initializeLoopUnswitchPass(PassRegistry &)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
bool VerifyMemorySSA
Enables verification of MemorySSA.
This class represents lattice values for constants.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
ArrayRef< BasicBlock *>::const_iterator block_iterator
OperatorChain
Operator chain lattice.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
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 push_back(const T &Elt)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Value * getCondition() const
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...
bool isVectorTy() const
True if this is an instance of VectorType.
bool notDuplicatable
True if this function cannot be duplicated.
LLVMContext & getContext() const
Get the context in which this basic block lives.
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
static void ReplaceUsesOfWith(Instruction *I, Value *V, std::vector< Instruction *> &Worklist, Loop *L, LPPassManager *LPM)
When we find that I really equals V, remove I from the program, replacing all uses with V and update ...
static Loop * CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Option class for critical edge splitting.
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
A Use represents the edge between a Value definition and its users.
Encapsulates MemorySSA, including all data associated with memory accesses.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
static bool isEqual(const Function &Caller, const Function &Callee)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once. ...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
iterator find(const KeyT &Val)
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const_arg_type_t< KeyT > Val)
static Value * FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed, OperatorChain &ParentChain, DenseMap< Value *, Value *> &Cache)
Cond is a condition that occurs in L.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void RemoveFromWorklist(Instruction *I, std::vector< Instruction *> &Worklist)
Remove all instances of I from the worklist vector specified.
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.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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...
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, BasicBlock *&ExitBB, std::set< BasicBlock *> &Visited)
Check to see if all paths from BB exit the loop with no side effects (including infinite loops)...
This instruction compares its operands according to the predicate given to the constructor.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
static bool EqualityPropUnSafe(Value &LoopCond)
FIXME: Remove this workaround when freeze related patches are done.
INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops", false, false) INITIALIZE_PASS_END(LoopUnswitch
static Constant * getAllOnesValue(Type *Ty)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
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.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
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.
Module.h This file contains the declarations for the Module class.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
LoopT * AllocateLoop(ArgsTy &&... Args)
CHAIN = SC CHAIN, Imm128 - System call.
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.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
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...
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
Pass * createLoopUnswitchPass(bool OptimizeForSize=false, bool hasBranchDivergence=false)
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LoopT * getParentLoop() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
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.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
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)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
block_iterator block_end() const
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
unsigned NumInsts
Number of instructions in the analyzed blocks.
iterator_range< block_iterator > blocks() const
static BasicBlock * isTrivialLoopExitBlock(Loop *L, BasicBlock *BB)
Return true if the specified block unconditionally leads to an exit from the specified loop...
block_iterator block_begin() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
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.