#ifndef LLVM_LIB_TRANSFORMS_INSTRUMENTATION_CFGMST_H
#define LLVM_LIB_TRANSFORMS_INSTRUMENTATION_CFGMST_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <utility>
#include <vector>
#define DEBUG_TYPE "cfgmst"
using namespace llvm;
namespace llvm {
template <class Edge, class BBInfo> class CFGMST {
public:
Function &F;
std::vector<std::unique_ptr<Edge>> AllEdges;
DenseMap<const BasicBlock *, std::unique_ptr<BBInfo>> BBInfos;
bool ExitBlockFound = false;
BBInfo *findAndCompressGroup(BBInfo *G) {
if (G->Group != G)
G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));
return static_cast<BBInfo *>(G->Group);
}
bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {
BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));
BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));
if (BB1G == BB2G)
return false;
if (BB1G->Rank < BB2G->Rank)
BB1G->Group = BB2G;
else {
BB2G->Group = BB1G;
if (BB1G->Rank == BB2G->Rank)
BB1G->Rank++;
}
return true;
}
BBInfo &getBBInfo(const BasicBlock *BB) const {
auto It = BBInfos.find(BB);
assert(It->second.get() != nullptr);
return *It->second.get();
}
BBInfo *findBBInfo(const BasicBlock *BB) const {
auto It = BBInfos.find(BB);
if (It == BBInfos.end())
return nullptr;
return It->second.get();
}
void buildEdges() {
LLVM_DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");
const BasicBlock *Entry = &(F.getEntryBlock());
uint64_t EntryWeight = (BFI != nullptr ? BFI->getEntryFreq() : 2);
if (InstrumentFuncEntry)
EntryWeight = 0;
Edge *EntryIncoming = nullptr, *EntryOutgoing = nullptr,
*ExitOutgoing = nullptr, *ExitIncoming = nullptr;
uint64_t MaxEntryOutWeight = 0, MaxExitOutWeight = 0, MaxExitInWeight = 0;
EntryIncoming = &addEdge(nullptr, Entry, EntryWeight);
LLVM_DEBUG(dbgs() << " Edge: from fake node to " << Entry->getName()
<< " w = " << EntryWeight << "\n");
if (succ_empty(Entry)) {
addEdge(Entry, nullptr, EntryWeight);
return;
}
static const uint32_t CriticalEdgeMultiplier = 1000;
for (BasicBlock &BB : F) {
Instruction *TI = BB.getTerminator();
uint64_t BBWeight =
(BFI != nullptr ? BFI->getBlockFreq(&BB).getFrequency() : 2);
uint64_t Weight = 2;
if (int successors = TI->getNumSuccessors()) {
for (int i = 0; i != successors; ++i) {
BasicBlock *TargetBB = TI->getSuccessor(i);
bool Critical = isCriticalEdge(TI, i);
uint64_t scaleFactor = BBWeight;
if (Critical) {
if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)
scaleFactor *= CriticalEdgeMultiplier;
else
scaleFactor = UINT64_MAX;
}
if (BPI != nullptr)
Weight = BPI->getEdgeProbability(&BB, TargetBB).scale(scaleFactor);
if (Weight == 0)
Weight++;
auto *E = &addEdge(&BB, TargetBB, Weight);
E->IsCritical = Critical;
LLVM_DEBUG(dbgs() << " Edge: from " << BB.getName() << " to "
<< TargetBB->getName() << " w=" << Weight << "\n");
if (&BB == Entry) {
if (Weight > MaxEntryOutWeight) {
MaxEntryOutWeight = Weight;
EntryOutgoing = E;
}
}
auto *TargetTI = TargetBB->getTerminator();
if (TargetTI && !TargetTI->getNumSuccessors()) {
if (Weight > MaxExitInWeight) {
MaxExitInWeight = Weight;
ExitIncoming = E;
}
}
}
} else {
ExitBlockFound = true;
Edge *ExitO = &addEdge(&BB, nullptr, BBWeight);
if (BBWeight > MaxExitOutWeight) {
MaxExitOutWeight = BBWeight;
ExitOutgoing = ExitO;
}
LLVM_DEBUG(dbgs() << " Edge: from " << BB.getName() << " to fake exit"
<< " w = " << BBWeight << "\n");
}
}
uint64_t EntryInWeight = EntryWeight;
if (EntryInWeight >= MaxExitOutWeight &&
EntryInWeight * 2 < MaxExitOutWeight * 3) {
EntryIncoming->Weight = MaxExitOutWeight;
ExitOutgoing->Weight = EntryInWeight + 1;
}
if (MaxEntryOutWeight >= MaxExitInWeight &&
MaxEntryOutWeight * 2 < MaxExitInWeight * 3) {
EntryOutgoing->Weight = MaxExitInWeight;
ExitIncoming->Weight = MaxEntryOutWeight + 1;
}
}
void sortEdgesByWeight() {
llvm::stable_sort(AllEdges, [](const std::unique_ptr<Edge> &Edge1,
const std::unique_ptr<Edge> &Edge2) {
return Edge1->Weight > Edge2->Weight;
});
}
void computeMinimumSpanningTree() {
for (auto &Ei : AllEdges) {
if (Ei->Removed)
continue;
if (Ei->IsCritical) {
if (Ei->DestBB && Ei->DestBB->isLandingPad()) {
if (unionGroups(Ei->SrcBB, Ei->DestBB))
Ei->InMST = true;
}
}
}
for (auto &Ei : AllEdges) {
if (Ei->Removed)
continue;
if (!ExitBlockFound && Ei->SrcBB == nullptr)
continue;
if (unionGroups(Ei->SrcBB, Ei->DestBB))
Ei->InMST = true;
}
}
void dumpEdges(raw_ostream &OS, const Twine &Message) const {
if (!Message.str().empty())
OS << Message << "\n";
OS << " Number of Basic Blocks: " << BBInfos.size() << "\n";
for (auto &BI : BBInfos) {
const BasicBlock *BB = BI.first;
OS << " BB: " << (BB == nullptr ? "FakeNode" : BB->getName()) << " "
<< BI.second->infoString() << "\n";
}
OS << " Number of Edges: " << AllEdges.size()
<< " (*: Instrument, C: CriticalEdge, -: Removed)\n";
uint32_t Count = 0;
for (auto &EI : AllEdges)
OS << " Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index << "-->"
<< getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";
}
Edge &addEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W) {
uint32_t Index = BBInfos.size();
auto Iter = BBInfos.end();
bool Inserted;
std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Src, nullptr));
if (Inserted) {
Iter->second = std::move(std::make_unique<BBInfo>(Index));
Index++;
}
std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Dest, nullptr));
if (Inserted)
Iter->second = std::move(std::make_unique<BBInfo>(Index));
AllEdges.emplace_back(new Edge(Src, Dest, W));
return *AllEdges.back();
}
BranchProbabilityInfo *BPI;
BlockFrequencyInfo *BFI;
bool InstrumentFuncEntry;
public:
CFGMST(Function &Func, bool InstrumentFuncEntry_,
BranchProbabilityInfo *BPI_ = nullptr,
BlockFrequencyInfo *BFI_ = nullptr)
: F(Func), BPI(BPI_), BFI(BFI_),
InstrumentFuncEntry(InstrumentFuncEntry_) {
buildEdges();
sortEdgesByWeight();
computeMinimumSpanningTree();
if (AllEdges.size() > 1 && InstrumentFuncEntry)
std::iter_swap(std::move(AllEdges.begin()),
std::move(AllEdges.begin() + AllEdges.size() - 1));
}
};
}
#undef DEBUG_TYPE
#endif