38#define DEBUG_TYPE "break-crit-edges"
50 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
51 auto *DT = DTWP ? &DTWP->getDomTree() :
nullptr;
53 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
54 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() :
nullptr;
56 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
57 auto *LI = LIWP ? &LIWP->getLoopInfo() :
nullptr;
59 F, CriticalEdgeSplittingOptions(DT, LI,
nullptr, PDT));
64 void getAnalysisUsage(AnalysisUsage &AU)
const override {
74char BreakCriticalEdges::ID = 0;
76 "Break critical edges in CFG",
false,
false)
82 return new BreakCriticalEdges();
105 const Twine &BBName) {
115 const Twine &BBName) {
125 if (
Options.IgnoreUnreachableDests &&
135 if (
Loop *TIL = LI->getLoopFor(TIBB)) {
149 if (LI->getLoopFor(
P) != TIL) {
161 if (
Options.PreserveLoopSimplify)
170 if (BBName.
str() !=
"")
179 if (
auto *LoopMD = TI->
getMetadata(LLVMContext::MD_loop))
180 NewBI->setMetadata(LLVMContext::MD_loop, LoopMD);
185 F.insert(++FBBI, NewBB);
211 unsigned NumSplitIdenticalEdges = 1;
216 if (
Options.MergeIdenticalEdges) {
227 NumSplitIdenticalEdges++;
236 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
237 DestBB, NewBB, {TIBB},
Options.MergeIdenticalEdges);
239 if (!DT && !PDT && !LI)
259 DT->applyUpdates(Updates);
261 PDT->applyUpdates(Updates);
266 if (
Loop *TIL = LI->getLoopFor(TIBB)) {
269 if (
Loop *DestLoop = LI->getLoopFor(DestBB)) {
270 if (TIL == DestLoop) {
272 DestLoop->addBasicBlockToLoop(NewBB, *LI);
273 }
else if (TIL->contains(DestLoop)) {
275 TIL->addBasicBlockToLoop(NewBB, *LI);
276 }
else if (DestLoop->contains(TIL)) {
278 DestLoop->addBasicBlockToLoop(NewBB, *LI);
284 assert(DestLoop->getHeader() == DestBB &&
285 "Should not create irreducible loops!");
286 if (
Loop *
P = DestLoop->getParentLoop())
287 P->addBasicBlockToLoop(NewBB, *LI);
293 if (!TIL->contains(DestBB)) {
294 assert(!TIL->contains(NewBB) &&
295 "Split point for loop exit is contained in loop!");
306 if (!LoopPreds.
empty()) {
307 assert(!DestBB->
isEHPad() &&
"We don't split edges to EH pads!");
309 DestBB, LoopPreds,
"split", DT, LI, MSSAU,
Options.PreserveLCSSA);
333 case Instruction::IndirectBr:
338 case Instruction::UncondBr:
339 case Instruction::CondBr:
340 case Instruction::Switch:
352 bool IgnoreBlocksWithoutPHI,
368 bool ShouldUpdateAnalysis = BPI && BFI;
371 if (IgnoreBlocksWithoutPHI &&
Target->phis().empty())
378 if (!IBRPred || OtherPreds.
empty())
382 auto FirstNonPHIIt =
Target->getFirstNonPHIIt();
383 if (FirstNonPHIIt->isEHPad() ||
Target->isLandingPad())
388 if (ShouldUpdateAnalysis) {
389 EdgeProbabilities.
reserve(
Target->getTerminator()->getNumSuccessors());
390 for (
unsigned I = 0, E =
Target->getTerminator()->getNumSuccessors();
398 if (ShouldUpdateAnalysis) {
426 if (ShouldUpdateAnalysis)
434 if (ShouldUpdateAnalysis) {
451 End =
Target->getFirstNonPHIIt();
456 "Block was expected to only contain PHIs");
458 while (Indirect != End) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static BasicBlock * findIBRPredecessor(BasicBlock *BB, SmallVectorImpl< BasicBlock * > &OtherPreds)
static bool runOnFunction(Function &F, bool PostInlining)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic,...
bool isEHPad() const
Return true if this basic block is an exception handling block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis providing branch probability information.
LLVM_ABI void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
LLVM_ABI void setEdgeProbability(const BasicBlock *Src, const SmallVectorImpl< BranchProbability > &Probs)
Set the raw probabilities for all edges from the given block.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
Analysis pass which computes a DominatorTree.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
FunctionPass class - This class is used to implement most global optimizations.
BasicBlockListType::iterator iterator
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
Analysis pass that exposes the LoopInfo for a function.
Represents a single loop in the control flow graph.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
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...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
void insert_range(Range &&R)
bool empty() const
Determine if the SetVector is empty or not.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
self_iterator getIterator()
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
auto successors(const MachineBasicBlock *BB)
LLVM_ABI FunctionPass * createBreakCriticalEdgesPass()
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI char & LoopSimplifyID
LLVM_ABI BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
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 char & BreakCriticalEdgesID
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 BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, 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...
LLVM_ABI void createPHIsForSplitLoopExit(ArrayRef< BasicBlock * > Preds, BasicBlock *SplitBB, BasicBlock *DestBB)
When a loop exit edge is split, LCSSA form may require new PHIs in the new exit block.
LLVM_ABI void initializeBreakCriticalEdgesPass(PassRegistry &)
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Option class for critical edge splitting.