#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <cassert>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "basicblock-utils"
static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
"max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
cl::desc("Set the maximum path length when checking whether a basic block "
"is followed by a block that either has a terminating "
"deoptimizing call or is terminated with an unreachable"));
void llvm::detachDeadBlocks(
ArrayRef<BasicBlock *> BBs,
SmallVectorImpl<DominatorTree::UpdateType> *Updates,
bool KeepOneInputPHIs) {
for (auto *BB : BBs) {
SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
for (BasicBlock *Succ : successors(BB)) {
Succ->removePredecessor(BB, KeepOneInputPHIs);
if (Updates && UniqueSuccessors.insert(Succ).second)
Updates->push_back({DominatorTree::Delete, BB, Succ});
}
while (!BB->empty()) {
Instruction &I = BB->back();
if (!I.use_empty())
I.replaceAllUsesWith(PoisonValue::get(I.getType()));
BB->getInstList().pop_back();
}
new UnreachableInst(BB->getContext(), BB);
assert(BB->getInstList().size() == 1 &&
isa<UnreachableInst>(BB->getTerminator()) &&
"The successor list of BB isn't empty before "
"applying corresponding DTU updates.");
}
}
void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
bool KeepOneInputPHIs) {
DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
}
void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
bool KeepOneInputPHIs) {
#ifndef NDEBUG
SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
assert(Dead.size() == BBs.size() && "Duplicating blocks?");
for (auto *BB : Dead)
for (BasicBlock *Pred : predecessors(BB))
assert(Dead.count(Pred) && "All predecessors must be dead!");
#endif
SmallVector<DominatorTree::UpdateType, 4> Updates;
detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
if (DTU)
DTU->applyUpdates(Updates);
for (BasicBlock *BB : BBs)
if (DTU)
DTU->deleteBB(BB);
else
BB->eraseFromParent();
}
bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
bool KeepOneInputPHIs) {
df_iterator_default_set<BasicBlock*> Reachable;
for (BasicBlock *BB : depth_first_ext(&F, Reachable))
(void)BB;
std::vector<BasicBlock*> DeadBlocks;
for (BasicBlock &BB : F)
if (!Reachable.count(&BB))
DeadBlocks.push_back(&BB);
DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
return !DeadBlocks.empty();
}
bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
MemoryDependenceResults *MemDep) {
if (!isa<PHINode>(BB->begin()))
return false;
while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
if (PN->getIncomingValue(0) != PN)
PN->replaceAllUsesWith(PN->getIncomingValue(0));
else
PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
if (MemDep)
MemDep->removeInstruction(PN);
PN->eraseFromParent();
}
return true;
}
bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
MemorySSAUpdater *MSSAU) {
SmallVector<WeakTrackingVH, 8> PHIs;
for (PHINode &PN : BB->phis())
PHIs.push_back(&PN);
bool Changed = false;
for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
return Changed;
}
bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
LoopInfo *LI, MemorySSAUpdater *MSSAU,
MemoryDependenceResults *MemDep,
bool PredecessorWithTwoSuccessors) {
if (BB->hasAddressTaken())
return false;
BasicBlock *PredBB = BB->getUniquePredecessor();
if (!PredBB) return false;
if (PredBB == BB) return false;
Instruction *PTI = PredBB->getTerminator();
if (PTI->isExceptionalTerminator() || PTI->mayHaveSideEffects())
return false;
if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
return false;
BranchInst *PredBB_BI;
BasicBlock *NewSucc = nullptr;
unsigned FallThruPath;
if (PredecessorWithTwoSuccessors) {
if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
return false;
BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
if (!BB_JmpI || !BB_JmpI->isUnconditional())
return false;
NewSucc = BB_JmpI->getSuccessor(0);
FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
}
for (PHINode &PN : BB->phis())
if (llvm::is_contained(PN.incoming_values(), &PN))
return false;
LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
<< PredBB->getName() << "\n");
SmallVector<AssertingVH<Value>, 4> IncomingValues;
if (isa<PHINode>(BB->front())) {
for (PHINode &PN : BB->phis())
if (!isa<PHINode>(PN.getIncomingValue(0)) ||
cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
IncomingValues.push_back(PN.getIncomingValue(0));
FoldSingleEntryPHINodes(BB, MemDep);
}
std::vector<DominatorTree::UpdateType> Updates;
if (DTU) {
SmallPtrSet<BasicBlock *, 8> SeenSuccs;
SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
succ_end(PredBB));
Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
for (BasicBlock *SuccOfBB : successors(BB))
if (!SuccsOfPredBB.contains(SuccOfBB))
if (SeenSuccs.insert(SuccOfBB).second)
Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
SeenSuccs.clear();
for (BasicBlock *SuccOfBB : successors(BB))
if (SeenSuccs.insert(SuccOfBB).second)
Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
Updates.push_back({DominatorTree::Delete, PredBB, BB});
}
Instruction *STI = BB->getTerminator();
Instruction *Start = &*BB->begin();
if (Start == STI)
Start = PTI;
PredBB->getInstList().splice(PTI->getIterator(), BB->getInstList(),
BB->begin(), STI->getIterator());
if (MSSAU)
MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
BB->replaceAllUsesWith(PredBB);
if (PredecessorWithTwoSuccessors) {
BB->getInstList().pop_back();
PredBB_BI->setSuccessor(FallThruPath, NewSucc);
} else {
PredBB->getInstList().pop_back();
PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
if (MSSAU)
if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
}
new UnreachableInst(BB->getContext(), BB);
if (!PredBB->hasName())
PredBB->takeName(BB);
if (LI)
LI->removeBlock(BB);
if (MemDep)
MemDep->invalidateCachedPredecessors();
if (DTU)
DTU->applyUpdates(Updates);
DeleteDeadBlock(BB, DTU);
return true;
}
bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
LoopInfo *LI) {
assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
bool BlocksHaveBeenMerged = false;
while (!MergeBlocks.empty()) {
BasicBlock *BB = *MergeBlocks.begin();
BasicBlock *Dest = BB->getSingleSuccessor();
if (Dest && (!L || L->contains(Dest))) {
BasicBlock *Fold = Dest->getUniquePredecessor();
(void)Fold;
if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
assert(Fold == BB &&
"Expecting BB to be unique predecessor of the Dest block");
MergeBlocks.erase(Dest);
BlocksHaveBeenMerged = true;
} else
MergeBlocks.erase(BB);
} else
MergeBlocks.erase(BB);
}
return BlocksHaveBeenMerged;
}
static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
SmallVector<DbgValueInst *, 8> ToBeRemoved;
SmallDenseSet<DebugVariable> VariableSet;
for (auto &I : reverse(*BB)) {
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
DebugVariable Key(DVI->getVariable(),
DVI->getExpression(),
DVI->getDebugLoc()->getInlinedAt());
auto R = VariableSet.insert(Key);
if (!R.second)
ToBeRemoved.push_back(DVI);
continue;
}
VariableSet.clear();
}
for (auto &Instr : ToBeRemoved)
Instr->eraseFromParent();
return !ToBeRemoved.empty();
}
static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
SmallVector<DbgValueInst *, 8> ToBeRemoved;
DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
VariableMap;
for (auto &I : *BB) {
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
DebugVariable Key(DVI->getVariable(),
NoneType(),
DVI->getDebugLoc()->getInlinedAt());
auto VMI = VariableMap.find(Key);
SmallVector<Value *, 4> Values(DVI->getValues());
if (VMI == VariableMap.end() || VMI->second.first != Values ||
VMI->second.second != DVI->getExpression()) {
VariableMap[Key] = {Values, DVI->getExpression()};
continue;
}
ToBeRemoved.push_back(DVI);
}
}
for (auto &Instr : ToBeRemoved)
Instr->eraseFromParent();
return !ToBeRemoved.empty();
}
bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
bool MadeChanges = false;
MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
if (MadeChanges)
LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
<< BB->getName() << "\n");
return MadeChanges;
}
void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
BasicBlock::iterator &BI, Value *V) {
Instruction &I = *BI;
I.replaceAllUsesWith(V);
if (I.hasName() && !V->hasName())
V->takeName(&I);
BI = BIL.erase(BI);
}
void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
BasicBlock::iterator &BI, Instruction *I) {
assert(I->getParent() == nullptr &&
"ReplaceInstWithInst: Instruction already inserted into basic block!");
if (!I->getDebugLoc())
I->setDebugLoc(BI->getDebugLoc());
BasicBlock::iterator New = BIL.insert(BI, I);
ReplaceInstWithValue(BIL, BI, I);
BI = New;
}
bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
unsigned Depth = 0;
while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
VisitedBlocks.insert(BB).second) {
if (BB->getTerminatingDeoptimizeCall() ||
isa<UnreachableInst>(BB->getTerminator()))
return true;
BB = BB->getUniqueSuccessor();
}
return false;
}
void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
BasicBlock::iterator BI(From);
ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
}
BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
LoopInfo *LI, MemorySSAUpdater *MSSAU,
const Twine &BBName) {
unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Instruction *LatchTerm = BB->getTerminator();
CriticalEdgeSplittingOptions Options =
CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
if (Succ->isEHPad())
return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
}
if (BasicBlock *SP = Succ->getSinglePredecessor()) {
assert(SP == BB && "CFG broken");
SP = nullptr;
return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
true);
}
assert(BB->getTerminator()->getNumSuccessors() == 1 &&
"Should have a single succ!");
return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
}
void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
if (auto *II = dyn_cast<InvokeInst>(TI))
II->setUnwindDest(Succ);
else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
CS->setUnwindDest(Succ);
else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
CR->setUnwindDest(Succ);
else
llvm_unreachable("unexpected terminator instruction");
}
void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
BasicBlock *NewPred, PHINode *Until) {
int BBIdx = 0;
for (PHINode &PN : DestBB->phis()) {
if (Until == &PN)
break;
if (PN.getIncomingBlock(BBIdx) != OldPred)
BBIdx = PN.getBasicBlockIndex(OldPred);
assert(BBIdx != -1 && "Invalid PHI Index!");
PN.setIncomingBlock(BBIdx, NewPred);
}
}
BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
LandingPadInst *OriginalPad,
PHINode *LandingPadReplacement,
const CriticalEdgeSplittingOptions &Options,
const Twine &BBName) {
auto *PadInst = Succ->getFirstNonPHI();
if (!LandingPadReplacement && !PadInst->isEHPad())
return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
auto *LI = Options.LI;
SmallVector<BasicBlock *, 4> LoopPreds;
if (Options.PreserveLoopSimplify && LI) {
if (Loop *BBLoop = LI->getLoopFor(BB)) {
for (BasicBlock *P : predecessors(Succ)) {
if (P == BB)
continue; if (LI->getLoopFor(P) != BBLoop) {
LoopPreds.clear();
break;
}
LoopPreds.push_back(P);
}
if (any_of(LoopPreds, [](BasicBlock *Pred) {
return isa<IndirectBrInst>(Pred->getTerminator());
})) {
return nullptr;
}
}
}
auto *NewBB =
BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
setUnwindEdgeTo(BB->getTerminator(), NewBB);
updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
if (LandingPadReplacement) {
auto *NewLP = OriginalPad->clone();
auto *Terminator = BranchInst::Create(Succ, NewBB);
NewLP->insertBefore(Terminator);
LandingPadReplacement->addIncoming(NewLP, NewBB);
} else {
Value *ParentPad = nullptr;
if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
ParentPad = FuncletPad->getParentPad();
else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
ParentPad = CatchSwitch->getParentPad();
else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
ParentPad = CleanupPad->getParentPad();
else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
ParentPad = LandingPad->getParent();
else
llvm_unreachable("handling for other EHPads not implemented yet");
auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
}
auto *DT = Options.DT;
auto *MSSAU = Options.MSSAU;
if (!DT && !LI)
return NewBB;
if (DT) {
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
SmallVector<DominatorTree::UpdateType, 3> Updates;
Updates.push_back({DominatorTree::Insert, BB, NewBB});
Updates.push_back({DominatorTree::Insert, NewBB, Succ});
Updates.push_back({DominatorTree::Delete, BB, Succ});
DTU.applyUpdates(Updates);
DTU.flush();
if (MSSAU) {
MSSAU->applyUpdates(Updates, *DT);
if (VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
}
}
if (LI) {
if (Loop *BBLoop = LI->getLoopFor(BB)) {
if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
if (BBLoop == SuccLoop) {
SuccLoop->addBasicBlockToLoop(NewBB, *LI);
} else if (BBLoop->contains(SuccLoop)) {
BBLoop->addBasicBlockToLoop(NewBB, *LI);
} else if (SuccLoop->contains(BBLoop)) {
SuccLoop->addBasicBlockToLoop(NewBB, *LI);
} else {
assert(SuccLoop->getHeader() == Succ &&
"Should not create irreducible loops!");
if (Loop *P = SuccLoop->getParentLoop())
P->addBasicBlockToLoop(NewBB, *LI);
}
}
if (!BBLoop->contains(Succ)) {
assert(!BBLoop->contains(NewBB) &&
"Split point for loop exit is contained in loop!");
if (Options.PreserveLCSSA) {
createPHIsForSplitLoopExit(BB, NewBB, Succ);
}
if (!LoopPreds.empty()) {
BasicBlock *NewExitBB = SplitBlockPredecessors(
Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
if (Options.PreserveLCSSA)
createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
}
}
}
}
return NewBB;
}
void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
BasicBlock *SplitBB, BasicBlock *DestBB) {
assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
SplitBB->isLandingPad()) &&
"SplitBB has non-PHI nodes!");
for (PHINode &PN : DestBB->phis()) {
int Idx = PN.getBasicBlockIndex(SplitBB);
assert(Idx >= 0 && "Invalid Block Index");
Value *V = PN.getIncomingValue(Idx);
if (const PHINode *VP = dyn_cast<PHINode>(V))
if (VP->getParent() == SplitBB)
continue;
PHINode *NewPN = PHINode::Create(
PN.getType(), Preds.size(), "split",
SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
for (BasicBlock *BB : Preds)
NewPN->addIncoming(V, BB);
PN.setIncomingValue(Idx, NewPN);
}
}
unsigned
llvm::SplitAllCriticalEdges(Function &F,
const CriticalEdgeSplittingOptions &Options) {
unsigned NumBroken = 0;
for (BasicBlock &BB : F) {
Instruction *TI = BB.getTerminator();
if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
if (SplitCriticalEdge(TI, i, Options))
++NumBroken;
}
return NumBroken;
}
static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt,
DomTreeUpdater *DTU, DominatorTree *DT,
LoopInfo *LI, MemorySSAUpdater *MSSAU,
const Twine &BBName, bool Before) {
if (Before) {
DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
return splitBlockBefore(Old, SplitPt,
DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
BBName);
}
BasicBlock::iterator SplitIt = SplitPt->getIterator();
while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
++SplitIt;
assert(SplitIt != SplitPt->getParent()->end());
}
std::string Name = BBName.str();
BasicBlock *New = Old->splitBasicBlock(
SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
if (LI)
if (Loop *L = LI->getLoopFor(Old))
L->addBasicBlockToLoop(New, *LI);
if (DTU) {
SmallVector<DominatorTree::UpdateType, 8> Updates;
SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
Updates.push_back({DominatorTree::Insert, Old, New});
Updates.reserve(Updates.size() + 2 * succ_size(New));
for (BasicBlock *SuccessorOfOld : successors(New))
if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
}
DTU->applyUpdates(Updates);
} else if (DT)
if (DomTreeNode *OldNode = DT->getNode(Old)) {
std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
DomTreeNode *NewNode = DT->addNewBlock(New, Old);
for (DomTreeNode *I : Children)
DT->changeImmediateDominator(I, NewNode);
}
if (MSSAU)
MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
return New;
}
BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
DominatorTree *DT, LoopInfo *LI,
MemorySSAUpdater *MSSAU, const Twine &BBName,
bool Before) {
return SplitBlockImpl(Old, SplitPt, nullptr, DT, LI, MSSAU, BBName,
Before);
}
BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
DomTreeUpdater *DTU, LoopInfo *LI,
MemorySSAUpdater *MSSAU, const Twine &BBName,
bool Before) {
return SplitBlockImpl(Old, SplitPt, DTU, nullptr, LI, MSSAU, BBName,
Before);
}
BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
DomTreeUpdater *DTU, LoopInfo *LI,
MemorySSAUpdater *MSSAU,
const Twine &BBName) {
BasicBlock::iterator SplitIt = SplitPt->getIterator();
while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
++SplitIt;
std::string Name = BBName.str();
BasicBlock *New = Old->splitBasicBlock(
SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
true);
if (LI)
if (Loop *L = LI->getLoopFor(Old))
L->addBasicBlockToLoop(New, *LI);
if (DTU) {
SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
DTUpdates.push_back({DominatorTree::Insert, New, Old});
DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
for (BasicBlock *PredecessorOfOld : predecessors(New))
if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
}
DTU->applyUpdates(DTUpdates);
if (MSSAU) {
MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
if (VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
}
}
return New;
}
static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
ArrayRef<BasicBlock *> Preds,
DomTreeUpdater *DTU, DominatorTree *DT,
LoopInfo *LI, MemorySSAUpdater *MSSAU,
bool PreserveLCSSA, bool &HasLoopExit) {
if (DTU) {
if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
DTU->recalculate(*NewBB->getParent());
} else {
SmallVector<DominatorTree::UpdateType, 8> Updates;
SmallPtrSet<BasicBlock *, 8> UniquePreds;
Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
Updates.reserve(Updates.size() + 2 * Preds.size());
for (auto *Pred : Preds)
if (UniquePreds.insert(Pred).second) {
Updates.push_back({DominatorTree::Insert, Pred, NewBB});
Updates.push_back({DominatorTree::Delete, Pred, OldBB});
}
DTU->applyUpdates(Updates);
}
} else if (DT) {
if (OldBB == DT->getRootNode()->getBlock()) {
assert(NewBB->isEntryBlock());
DT->setNewRoot(NewBB);
} else {
DT->splitBlock(NewBB);
}
}
if (MSSAU)
MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
if (!LI)
return;
if (DTU && DTU->hasDomTree())
DT = &DTU->getDomTree();
assert(DT && "DT should be available to update LoopInfo!");
Loop *L = LI->getLoopFor(OldBB);
bool IsLoopEntry = !!L;
bool SplitMakesNewLoopHeader = false;
for (BasicBlock *Pred : Preds) {
if (!DT->isReachableFromEntry(Pred))
continue;
if (PreserveLCSSA)
if (Loop *PL = LI->getLoopFor(Pred))
if (!PL->contains(OldBB))
HasLoopExit = true;
if (!L)
continue;
if (L->contains(Pred))
IsLoopEntry = false;
else
SplitMakesNewLoopHeader = true;
}
if (!L)
return;
if (IsLoopEntry) {
Loop *InnermostPredLoop = nullptr;
for (BasicBlock *Pred : Preds) {
if (Loop *PredLoop = LI->getLoopFor(Pred)) {
while (PredLoop && !PredLoop->contains(OldBB))
PredLoop = PredLoop->getParentLoop();
if (PredLoop && PredLoop->contains(OldBB) &&
(!InnermostPredLoop ||
InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
InnermostPredLoop = PredLoop;
}
}
if (InnermostPredLoop)
InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
} else {
L->addBasicBlockToLoop(NewBB, *LI);
if (SplitMakesNewLoopHeader)
L->moveToHeader(NewBB);
}
}
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
ArrayRef<BasicBlock *> Preds, BranchInst *BI,
bool HasLoopExit) {
SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
PHINode *PN = cast<PHINode>(I++);
Value *InVal = nullptr;
if (!HasLoopExit) {
InVal = PN->getIncomingValueForBlock(Preds[0]);
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
if (!PredSet.count(PN->getIncomingBlock(i)))
continue;
if (!InVal)
InVal = PN->getIncomingValue(i);
else if (InVal != PN->getIncomingValue(i)) {
InVal = nullptr;
break;
}
}
}
if (InVal) {
for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
if (PredSet.count(PN->getIncomingBlock(i)))
PN->removeIncomingValue(i, false);
PN->addIncoming(InVal, NewBB);
continue;
}
PHINode *NewPHI =
PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
BasicBlock *IncomingBB = PN->getIncomingBlock(i);
if (PredSet.count(IncomingBB)) {
Value *V = PN->removeIncomingValue(i, false);
NewPHI->addIncoming(V, IncomingBB);
}
}
PN->addIncoming(NewPHI, NewBB);
}
}
static void SplitLandingPadPredecessorsImpl(
BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
static BasicBlock *
SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
const char *Suffix, DomTreeUpdater *DTU,
DominatorTree *DT, LoopInfo *LI,
MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
if (!BB->canSplitPredecessors())
return nullptr;
if (BB->isLandingPad()) {
SmallVector<BasicBlock*, 2> NewBBs;
std::string NewName = std::string(Suffix) + ".split-lp";
SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
DTU, DT, LI, MSSAU, PreserveLCSSA);
return NewBBs[0];
}
BasicBlock *NewBB = BasicBlock::Create(
BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
BranchInst *BI = BranchInst::Create(BB, NewBB);
Loop *L = nullptr;
BasicBlock *OldLatch = nullptr;
if (LI && LI->isLoopHeader(BB)) {
L = LI->getLoopFor(BB);
BI->setDebugLoc(L->getStartLoc());
OldLatch = L->getLoopLatch();
} else
BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
"Cannot split an edge from an IndirectBrInst");
Preds[i]->getTerminator()->replaceSuccessorWith(BB, NewBB);
}
if (Preds.empty()) {
for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
}
bool HasLoopExit = false;
UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
HasLoopExit);
if (!Preds.empty()) {
UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
}
if (OldLatch) {
BasicBlock *NewLatch = L->getLoopLatch();
if (NewLatch != OldLatch) {
MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
Loop *IL = LI->getLoopFor(OldLatch);
if (IL && IL->getLoopLatch() != OldLatch)
OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
}
}
return NewBB;
}
BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
ArrayRef<BasicBlock *> Preds,
const char *Suffix, DominatorTree *DT,
LoopInfo *LI, MemorySSAUpdater *MSSAU,
bool PreserveLCSSA) {
return SplitBlockPredecessorsImpl(BB, Preds, Suffix, nullptr, DT, LI,
MSSAU, PreserveLCSSA);
}
BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
ArrayRef<BasicBlock *> Preds,
const char *Suffix,
DomTreeUpdater *DTU, LoopInfo *LI,
MemorySSAUpdater *MSSAU,
bool PreserveLCSSA) {
return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
nullptr, LI, MSSAU, PreserveLCSSA);
}
static void SplitLandingPadPredecessorsImpl(
BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
OrigBB->getName() + Suffix1,
OrigBB->getParent(), OrigBB);
NewBBs.push_back(NewBB1);
BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
"Cannot split an edge from an IndirectBrInst");
Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
}
bool HasLoopExit = false;
UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
PreserveLCSSA, HasLoopExit);
UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
SmallVector<BasicBlock*, 8> NewBB2Preds;
for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
i != e; ) {
BasicBlock *Pred = *i++;
if (Pred == NewBB1) continue;
assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
"Cannot split an edge from an IndirectBrInst");
NewBB2Preds.push_back(Pred);
e = pred_end(OrigBB);
}
BasicBlock *NewBB2 = nullptr;
if (!NewBB2Preds.empty()) {
NewBB2 = BasicBlock::Create(OrigBB->getContext(),
OrigBB->getName() + Suffix2,
OrigBB->getParent(), OrigBB);
NewBBs.push_back(NewBB2);
BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
for (BasicBlock *NewBB2Pred : NewBB2Preds)
NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
HasLoopExit = false;
UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
PreserveLCSSA, HasLoopExit);
UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
}
LandingPadInst *LPad = OrigBB->getLandingPadInst();
Instruction *Clone1 = LPad->clone();
Clone1->setName(Twine("lpad") + Suffix1);
NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
if (NewBB2) {
Instruction *Clone2 = LPad->clone();
Clone2->setName(Twine("lpad") + Suffix2);
NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
if (!LPad->use_empty()) {
assert(!LPad->getType()->isTokenTy() &&
"Split cannot be applied if LPad is token type. Otherwise an "
"invalid PHINode of token type would be created.");
PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
PN->addIncoming(Clone1, NewBB1);
PN->addIncoming(Clone2, NewBB2);
LPad->replaceAllUsesWith(PN);
}
LPad->eraseFromParent();
} else {
LPad->replaceAllUsesWith(Clone1);
LPad->eraseFromParent();
}
}
void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
ArrayRef<BasicBlock *> Preds,
const char *Suffix1, const char *Suffix2,
SmallVectorImpl<BasicBlock *> &NewBBs,
DominatorTree *DT, LoopInfo *LI,
MemorySSAUpdater *MSSAU,
bool PreserveLCSSA) {
return SplitLandingPadPredecessorsImpl(
OrigBB, Preds, Suffix1, Suffix2, NewBBs,
nullptr, DT, LI, MSSAU, PreserveLCSSA);
}
void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
ArrayRef<BasicBlock *> Preds,
const char *Suffix1, const char *Suffix2,
SmallVectorImpl<BasicBlock *> &NewBBs,
DomTreeUpdater *DTU, LoopInfo *LI,
MemorySSAUpdater *MSSAU,
bool PreserveLCSSA) {
return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
NewBBs, DTU, nullptr, LI, MSSAU,
PreserveLCSSA);
}
ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
BasicBlock *Pred,
DomTreeUpdater *DTU) {
Instruction *UncondBranch = Pred->getTerminator();
Instruction *NewRet = RI->clone();
Pred->getInstList().push_back(NewRet);
for (Use &Op : NewRet->operands()) {
Value *V = Op;
Instruction *NewBC = nullptr;
if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
V = BCI->getOperand(0);
NewBC = BCI->clone();
Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Op = NewBC;
}
Instruction *NewEV = nullptr;
if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
V = EVI->getOperand(0);
NewEV = EVI->clone();
if (NewBC) {
NewBC->setOperand(0, NewEV);
Pred->getInstList().insert(NewBC->getIterator(), NewEV);
} else {
Pred->getInstList().insert(NewRet->getIterator(), NewEV);
Op = NewEV;
}
}
if (PHINode *PN = dyn_cast<PHINode>(V)) {
if (PN->getParent() == BB) {
if (NewEV) {
NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
} else if (NewBC)
NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
else
Op = PN->getIncomingValueForBlock(Pred);
}
}
}
BB->removePredecessor(Pred);
UncondBranch->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
return cast<ReturnInst>(NewRet);
}
static Instruction *
SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore,
bool Unreachable, MDNode *BranchWeights,
DomTreeUpdater *DTU, DominatorTree *DT,
LoopInfo *LI, BasicBlock *ThenBlock) {
SmallVector<DominatorTree::UpdateType, 8> Updates;
BasicBlock *Head = SplitBefore->getParent();
BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
if (DTU) {
SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfHead;
Updates.push_back({DominatorTree::Insert, Head, Tail});
Updates.reserve(Updates.size() + 2 * succ_size(Tail));
for (BasicBlock *SuccessorOfHead : successors(Tail))
if (UniqueSuccessorsOfHead.insert(SuccessorOfHead).second) {
Updates.push_back({DominatorTree::Insert, Tail, SuccessorOfHead});
Updates.push_back({DominatorTree::Delete, Head, SuccessorOfHead});
}
}
Instruction *HeadOldTerm = Head->getTerminator();
LLVMContext &C = Head->getContext();
Instruction *CheckTerm;
bool CreateThenBlock = (ThenBlock == nullptr);
if (CreateThenBlock) {
ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
if (Unreachable)
CheckTerm = new UnreachableInst(C, ThenBlock);
else {
CheckTerm = BranchInst::Create(Tail, ThenBlock);
if (DTU)
Updates.push_back({DominatorTree::Insert, ThenBlock, Tail});
}
CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
} else
CheckTerm = ThenBlock->getTerminator();
BranchInst *HeadNewTerm =
BranchInst::Create( ThenBlock, Tail, Cond);
if (DTU)
Updates.push_back({DominatorTree::Insert, Head, ThenBlock});
HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
if (DTU)
DTU->applyUpdates(Updates);
else if (DT) {
if (DomTreeNode *OldNode = DT->getNode(Head)) {
std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
for (DomTreeNode *Child : Children)
DT->changeImmediateDominator(Child, NewNode);
if (CreateThenBlock)
DT->addNewBlock(ThenBlock, Head);
else
DT->changeImmediateDominator(ThenBlock, Head);
}
}
if (LI) {
if (Loop *L = LI->getLoopFor(Head)) {
L->addBasicBlockToLoop(ThenBlock, *LI);
L->addBasicBlockToLoop(Tail, *LI);
}
}
return CheckTerm;
}
Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
Instruction *SplitBefore,
bool Unreachable,
MDNode *BranchWeights,
DominatorTree *DT, LoopInfo *LI,
BasicBlock *ThenBlock) {
return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
BranchWeights,
nullptr, DT, LI, ThenBlock);
}
Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
Instruction *SplitBefore,
bool Unreachable,
MDNode *BranchWeights,
DomTreeUpdater *DTU, LoopInfo *LI,
BasicBlock *ThenBlock) {
return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
BranchWeights, DTU, nullptr, LI,
ThenBlock);
}
void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
Instruction **ThenTerm,
Instruction **ElseTerm,
MDNode *BranchWeights) {
BasicBlock *Head = SplitBefore->getParent();
BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Instruction *HeadOldTerm = Head->getTerminator();
LLVMContext &C = Head->getContext();
BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
*ThenTerm = BranchInst::Create(Tail, ThenBlock);
(*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
*ElseTerm = BranchInst::Create(Tail, ElseBlock);
(*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
BranchInst *HeadNewTerm =
BranchInst::Create(ThenBlock, ElseBlock, Cond);
HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
}
BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
BasicBlock *&IfFalse) {
PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
BasicBlock *Pred1 = nullptr;
BasicBlock *Pred2 = nullptr;
if (SomePHI) {
if (SomePHI->getNumIncomingValues() != 2)
return nullptr;
Pred1 = SomePHI->getIncomingBlock(0);
Pred2 = SomePHI->getIncomingBlock(1);
} else {
pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
if (PI == PE) return nullptr;
Pred1 = *PI++;
if (PI == PE) return nullptr;
Pred2 = *PI++;
if (PI != PE) return nullptr;
}
BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
if (!Pred1Br || !Pred2Br)
return nullptr;
if (Pred2Br->isConditional()) {
if (Pred1Br->isConditional())
return nullptr;
std::swap(Pred1, Pred2);
std::swap(Pred1Br, Pred2Br);
}
if (Pred1Br->isConditional()) {
if (!Pred2->getSinglePredecessor())
return nullptr;
if (Pred1Br->getSuccessor(0) == BB &&
Pred1Br->getSuccessor(1) == Pred2) {
IfTrue = Pred1;
IfFalse = Pred2;
} else if (Pred1Br->getSuccessor(0) == Pred2 &&
Pred1Br->getSuccessor(1) == BB) {
IfTrue = Pred2;
IfFalse = Pred1;
} else {
return nullptr;
}
return Pred1Br;
}
BasicBlock *CommonPred = Pred1->getSinglePredecessor();
if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
return nullptr;
BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
if (!BI) return nullptr;
assert(BI->isConditional() && "Two successors but not conditional?");
if (BI->getSuccessor(0) == Pred1) {
IfTrue = Pred1;
IfFalse = Pred2;
} else {
IfTrue = Pred2;
IfFalse = Pred1;
}
return BI;
}
static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
const SetVector<BasicBlock *> &Incoming,
BasicBlock *FirstGuardBlock) {
auto I = Out->begin();
while (I != Out->end() && isa<PHINode>(I)) {
auto Phi = cast<PHINode>(I);
auto NewPhi =
PHINode::Create(Phi->getType(), Incoming.size(),
Phi->getName() + ".moved", &FirstGuardBlock->back());
for (auto In : Incoming) {
Value *V = UndefValue::get(Phi->getType());
if (In == Out) {
V = NewPhi;
} else if (Phi->getBasicBlockIndex(In) != -1) {
V = Phi->removeIncomingValue(In, false);
}
NewPhi->addIncoming(V, In);
}
assert(NewPhi->getNumIncomingValues() == Incoming.size());
if (Phi->getNumOperands() == 0) {
Phi->replaceAllUsesWith(NewPhi);
I = Phi->eraseFromParent();
continue;
}
Phi->addIncoming(NewPhi, GuardBlock);
++I;
}
}
using BBPredicates = DenseMap<BasicBlock *, PHINode *>;
using BBSetVector = SetVector<BasicBlock *>;
static std::tuple<Value *, BasicBlock *, BasicBlock *>
redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
const BBSetVector &Outgoing) {
auto Branch = cast<BranchInst>(BB->getTerminator());
auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
BasicBlock *Succ0 = Branch->getSuccessor(0);
BasicBlock *Succ1 = nullptr;
Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
if (Branch->isUnconditional()) {
Branch->setSuccessor(0, FirstGuardBlock);
assert(Succ0);
} else {
Succ1 = Branch->getSuccessor(1);
Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
assert(Succ0 || Succ1);
if (Succ0 && !Succ1) {
Branch->setSuccessor(0, FirstGuardBlock);
} else if (Succ1 && !Succ0) {
Branch->setSuccessor(1, FirstGuardBlock);
} else {
Branch->eraseFromParent();
BranchInst::Create(FirstGuardBlock, BB);
}
}
assert(Succ0 || Succ1);
return std::make_tuple(Condition, Succ0, Succ1);
}
static void convertToGuardPredicates(
BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates,
SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming,
const BBSetVector &Outgoing) {
auto &Context = Incoming.front()->getContext();
auto BoolTrue = ConstantInt::getTrue(Context);
auto BoolFalse = ConstantInt::getFalse(Context);
for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
auto Out = Outgoing[i];
LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
auto Phi =
PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
StringRef("Guard.") + Out->getName(), FirstGuardBlock);
GuardPredicates[Out] = Phi;
}
for (auto In : Incoming) {
Value *Condition;
BasicBlock *Succ0;
BasicBlock *Succ1;
std::tie(Condition, Succ0, Succ1) =
redirectToHub(In, FirstGuardBlock, Outgoing);
bool OneSuccessorDone = false;
for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
auto Out = Outgoing[i];
auto Phi = GuardPredicates[Out];
if (Out != Succ0 && Out != Succ1) {
Phi->addIncoming(BoolFalse, In);
continue;
}
if (!Succ0 || !Succ1 || OneSuccessorDone) {
Phi->addIncoming(BoolTrue, In);
continue;
}
assert(Succ0 && Succ1);
OneSuccessorDone = true;
if (Out == Succ0) {
Phi->addIncoming(Condition, In);
continue;
}
auto Inverted = invertCondition(Condition);
DeletionCandidates.push_back(Condition);
Phi->addIncoming(Inverted, In);
}
}
}
static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks,
Function *F, const BBSetVector &Outgoing,
BBPredicates &GuardPredicates, StringRef Prefix) {
for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) {
GuardBlocks.push_back(
BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
}
assert(GuardBlocks.size() == GuardPredicates.size());
GuardBlocks.push_back(Outgoing.back());
for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
auto Out = Outgoing[i];
assert(GuardPredicates.count(Out));
BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
GuardBlocks[i]);
}
GuardBlocks.pop_back();
}
BasicBlock *llvm::CreateControlFlowHub(
DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
const BBSetVector &Incoming, const BBSetVector &Outgoing,
const StringRef Prefix) {
auto F = Incoming.front()->getParent();
auto FirstGuardBlock =
BasicBlock::Create(F->getContext(), Prefix + ".guard", F);
SmallVector<DominatorTree::UpdateType, 16> Updates;
if (DTU) {
for (auto In : Incoming) {
Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
for (auto Succ : successors(In)) {
if (Outgoing.count(Succ))
Updates.push_back({DominatorTree::Delete, In, Succ});
}
}
}
BBPredicates GuardPredicates;
SmallVector<WeakVH, 8> DeletionCandidates;
convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates,
Incoming, Outgoing);
GuardBlocks.push_back(FirstGuardBlock);
createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix);
for (int i = 0, e = GuardBlocks.size(); i != e; ++i) {
reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
}
reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
if (DTU) {
int NumGuards = GuardBlocks.size();
assert((int)Outgoing.size() == NumGuards + 1);
for (int i = 0; i != NumGuards - 1; ++i) {
Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
Updates.push_back(
{DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
}
Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
Outgoing[NumGuards - 1]});
Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
Outgoing[NumGuards]});
DTU->applyUpdates(Updates);
}
for (auto I : DeletionCandidates) {
if (I->use_empty())
if (auto Inst = dyn_cast_or_null<Instruction>(I))
Inst->eraseFromParent();
}
return FirstGuardBlock;
}