<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_1, i32 0, i32 0), i64 25571299074, i32 2, i32 0)<br>
> +<br>
> +  // Set the hot/cold inline hints based on the count values.<br>
> +  void applyFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {<br>
> +    if (ProgramMaxCount == 0)<br>
> +      return;<br>
> +    // Threshold of the hot functions.<br>
> +    const BranchProbability HotFunctionThreshold(1, 100);<br>
> +    // Threshold of the cold functions.<br>
> +    const BranchProbability ColdFunctionThreshold(2, 10000);<br>
> +    if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))<br>
> +      F.addFnAttr(llvm::Attribute::InlineHint);<br>
> +    else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))<br>
> +      F.addFnAttr(llvm::Attribute::Cold);<br>
<br>
This is more or less a workaround for limitations of the inliner and<br>
should eventually be removed in favour of making the inliner smarter,<br>
correct?<br>
<br></blockquote><div><br></div><div>yes. Easwaran is working on making the logic migrated to the inliner. Once the inliner change is ready, this code together with similar/duplicated code in FE and SampleFDO will be removed.</div><div><br></div><div><br></div><div>David</div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
> +  }<br>
> +<br>
> +public:<br>
> +  PGOUseFunc(Function &Func, Module *Modu,<br>
> +             BranchProbabilityInfo *BPI_ = nullptr,<br>
> +             BlockFrequencyInfo *BFI_ = nullptr)<br>
> +      : F(Func), M(Modu), FuncInfo(Func, false, BPI_, BFI_) {}<br>
> +<br>
> +  // Read counts for the instrumented BB from profile.<br>
> +  bool readCounters(IndexedInstrProfReader *PGOReader);<br>
> +<br>
> +  // Populate the counts for all BBs.<br>
> +  void populateCounters();<br>
> +<br>
> +  // Set the branch weights based on the count values.<br>
> +  void setBranchWeights();<br>
> +};<br>
> +<br>
> +// Visit all the edges and assign the count value for the instrumented<br>
> +// edges and the BB.<br>
> +void PGOUseFunc::setInstrumentedCounts(<br>
> +    const std::vector<uint64_t> &CountFromProfile) {<br>
> +<br>
> +  // Use a worklist as we will update the vector during the iteration.<br>
> +  std::vector<PGOUseEdge *> WorkList;<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges)<br>
> +    WorkList.push_back(Ei.get());<br>
> +<br>
> +  uint32_t j = 0;<br>
> +  for (auto &Ei : WorkList) {<br>
<br>
Same as before: j->J, Ei->E.<br>
<br>
> +    BasicBlock *InstrBB = FuncInfo.getInstrBB(Ei);<br>
> +    if (!InstrBB)<br>
> +      continue;<br>
> +    uint64_t CountValue = CountFromProfile[j++];<br>
> +    if (!Ei->Removed) {<br>
> +      getBBInfo(InstrBB).setBBInfoCount(CountValue);<br>
> +      Ei->setEdgeCount(CountValue);<br>
> +      continue;<br>
> +    }<br>
> +<br>
> +    // Need to add two new edges.<br>
> +    BasicBlock *SrcBB = const_cast<BasicBlock *>(Ei->SrcBB);<br>
> +    BasicBlock *DestBB = const_cast<BasicBlock *>(Ei->DestBB);<br>
> +    // Add new edge of SrcBB->InstrBB.<br>
> +    PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);<br>
> +    NewEdge.setEdgeCount(CountValue);<br>
> +    // Add new edge of InstrBB->DestBB.<br>
> +    PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);<br>
<br>
Why not just reuse the NewEdge variable here?<br>
<br>
> +    NewEdge1.setEdgeCount(CountValue);<br>
> +    NewEdge1.InMST = true;<br>
> +    getBBInfo(InstrBB).setBBInfoCount(CountValue);<br>
> +  }<br>
> +}<br>
> +<br>
> +// Set the count value for the unknown edge. There should be one and only one<br>
<span class="">> +// unknown edge in Edges vector.<br>
</span>> +void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {<br>
> +  for (auto &Ei : Edges) {<br>
> +    if (Ei->CountValid)<br>
> +      continue;<br>
> +    Ei->setEdgeCount(Value);<br>
> +<br>
> +    getBBInfo(Ei->SrcBB).UnknownCountOutEdge--;<br>
> +    getBBInfo(Ei->DestBB).UnknownCountInEdge--;<br>
> +    return;<br>
> +  }<br>
> +  llvm_unreachable("Cannot find the unknown count edge");<br>
> +}<br>
> +<br>
> +// Read the profile from ProfileFileName and assign the value to the<br>
> +// instrumented BB and the edges. This function also updates ProgramMaxCount.<br>
> +// Return true if the profile are successfully read, and false on errors.<br>
> +bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {<br>
> +  auto &Ctx = M->getContext();<br>
> +  ErrorOr<InstrProfRecord> Result =<br>
> +      PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);<br>
> +  if (std::error_code EC = Result.getError()) {<br>
> +    if (EC == instrprof_error::unknown_function)<br>
> +      NumOfPGOMissing++;<br>
> +    else if (EC == instrprof_error::hash_mismatch ||<br>
> +             EC == llvm::instrprof_error::malformed)<br>
> +      NumOfPGOMismatch++;<br>
> +<br>
> +    std::string Msg = EC.message() + std::string(" ") + F.getName().str();<br>
> +    Ctx.diagnose(<br>
> +        DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));<br>
> +    return false;<br>
> +  }<br>
> +  std::vector<uint64_t> &CountFromProfile = Result.get().Counts;<br>
> +<br>
> +  NumOfPGOFunc++;<br>
> +  DEBUG(dbgs() << CountFromProfile.size() << " counts\n");<br>
> +  uint64_t ValueSum = 0;<br>
> +  for (unsigned i = 0, e = CountFromProfile.size(); i < e; i++) {<br>
> +    DEBUG(dbgs() << "  " << i << ": " << CountFromProfile[i] << "\n");<br>
> +    ValueSum += CountFromProfile[i];<br>
> +  }<br>
> +<br>
> +  DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");<br>
> +<br>
> +  getBBInfo(nullptr).UnknownCountOutEdge = 2;<br>
> +  getBBInfo(nullptr).UnknownCountInEdge = 2;<br>
> +<br>
> +  setInstrumentedCounts(CountFromProfile);<br>
> +  ProgramMaxCount = PGOReader->getMaximumFunctionCount();<br>
> +  return true;<br>
> +}<br>
> +<br>
> +// Populate the counters from instrumented BBs to all BBs.<br>
> +// In the end of this operation, all BBs should have a valid count value.<br>
> +void PGOUseFunc::populateCounters() {<br>
> +  // First set up Count variable for all BBs.<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges) {<br>
> +    if (Ei->Removed)<br>
> +      continue;<br>
> +<br>
> +    const BasicBlock *SrcBB = Ei->SrcBB;<br>
> +    const BasicBlock *DestBB = Ei->DestBB;<br>
> +    UseBBInfo &SrcInfo = getBBInfo(SrcBB);<br>
> +    UseBBInfo &DestInfo = getBBInfo(DestBB);<br>
> +    SrcInfo.OutEdges.push_back(Ei.get());<br>
> +    DestInfo.InEdges.push_back(Ei.get());<br>
> +    SrcInfo.UnknownCountOutEdge++;<br>
> +    DestInfo.UnknownCountInEdge++;<br>
> +<br>
> +    if (!Ei->CountValid)<br>
> +      continue;<br>
> +    DestInfo.UnknownCountInEdge--;<br>
> +    SrcInfo.UnknownCountOutEdge--;<br>
> +  }<br>
> +<br>
> +  bool Changes = true;<br>
> +  unsigned NumPasses = 0;<br>
> +  while (Changes) {<br>
> +    NumPasses++;<br>
> +    Changes = false;<br>
> +<br>
> +    // For efficient traversal, it's better to start from the end as most<br>
> +    // of the instrumented edges are at the end.<br>
> +    for (auto &BB : reverse(F)) {<br>
> +      UseBBInfo &Count = getBBInfo(&BB);<br>
> +      if (!Count.CountValid) {<br>
> +        if (Count.UnknownCountOutEdge == 0) {<br>
> +          Count.CountValue = sumEdgeCount(Count.OutEdges);<br>
> +          Count.CountValid = true;<br>
> +          Changes = true;<br>
> +        } else if (Count.UnknownCountInEdge == 0) {<br>
> +          Count.CountValue = sumEdgeCount(Count.InEdges);<br>
> +          Count.CountValid = true;<br>
> +          Changes = true;<br>
> +        }<br>
> +      }<br>
> +      if (Count.CountValid) {<br>
> +        if (Count.UnknownCountOutEdge == 1) {<br>
> +          uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);<br>
> +          setEdgeCount(Count.OutEdges, Total);<br>
> +          Changes = true;<br>
> +        }<br>
> +        if (Count.UnknownCountInEdge == 1) {<br>
> +          uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);<br>
> +          setEdgeCount(Count.InEdges, Total);<br>
> +          Changes = true;<br>
> +        }<br>
> +      }<br>
> +    }<br>
> +  }<br>
> +<br>
> +  DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");<br>
> +  // Assert every BB has a valid counter.<br>
> +  uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;<br>
> +  uint64_t FuncMaxCount = FuncEntryCount;<br>
> +  for (auto &BB : F) {<br>
> +    assert(getBBInfo(&BB).CountValid && "BB count is not valid");<br>
> +    uint64_t Count = getBBInfo(&BB).CountValue;<br>
> +    if (Count > FuncMaxCount)<br>
> +      FuncMaxCount = Count;<br>
> +  }<br>
> +  applyFunctionAttributes(FuncEntryCount, FuncMaxCount);<br>
> +<br>
> +  DEBUG(FuncInfo.dumpInfo("after reading profile."));<br>
> +}<br>
> +<br>
> +// Assign the scaled count values to the BB with multiple out edges.<br>
> +void PGOUseFunc::setBranchWeights() {<br>
> +  // Generate MD_prof metadata for every branch instruction.<br>
> +  DEBUG(dbgs() << "\nSetting branch weights.\n");<br>
> +  MDBuilder MDB(M->getContext());<br>
> +  for (auto &BB : F) {<br>
> +    TerminatorInst *TI = BB.getTerminator();<br>
> +    if (TI->getNumSuccessors() < 2)<br>
> +      continue;<br>
> +    if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))<br>
> +      continue;<br>
> +    if (getBBInfo(&BB).CountValue == 0)<br>
> +      continue;<br>
> +<br>
> +    // We have a non-zero Branch BB.<br>
> +    const UseBBInfo &BBCountInfo = getBBInfo(&BB);<br>
> +    unsigned Size = BBCountInfo.OutEdges.size();<br>
> +    SmallVector<unsigned, 2> EdgeCounts(Size, 0);<br>
> +    uint64_t MaxCount = 0;<br>
> +    for (unsigned s = 0; s < Size; s++) {<br>
> +      const PGOUseEdge *E = BBCountInfo.OutEdges[s];<br>
> +      const BasicBlock *SrcBB = E->SrcBB;<br>
> +      const BasicBlock *DestBB = E->DestBB;<br>
> +      if (DestBB == 0)<br>
> +        continue;<br>
> +      unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);<br>
> +      uint64_t EdgeCount = E->CountValue;<br>
> +      if (EdgeCount > MaxCount)<br>
> +        MaxCount = EdgeCount;<br>
> +      EdgeCounts[SuccNum] = EdgeCount;<br>
> +    }<br>
> +    assert(MaxCount > 0 && "Bad max count");<br>
> +    uint64_t Scale = calculateCountScale(MaxCount);<br>
> +    SmallVector<unsigned, 4> Weights;<br>
> +    for (const auto &ECI : EdgeCounts)<br>
> +      Weights.push_back(scaleBranchCount(ECI, Scale));<br>
> +<br>
> +    TI->setMetadata(llvm::LLVMContext::MD_prof,<br>
> +                    MDB.createBranchWeights(Weights));<br>
> +    DEBUG(dbgs() << "Weight is: "; for (const auto &W<br>
> +                                        : Weights) dbgs()<br>
> +                                   << W << " ";<br>
> +          dbgs() << "\n";);<br>
<br>
This is formatted really strangely. It's possible that clang-format<br>
doesn't know how to deal with this code-in-DEBUG() stuff and you just<br>
need to format this manually (or file a bug on clang-format ;)<br>
<br>
> +  }<br>
> +}<br>
> +} // end anonymous namespace<br>
> +<br>
> +bool PGOInstrumentationGen::runOnModule(Module &M) {<br>
> +  for (auto &F : M) {<br>
> +    if (F.isDeclaration())<br>
> +      continue;<br>
> +    BranchProbabilityInfo *BPI =<br>
> +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());<br>
> +    BlockFrequencyInfo *BFI =<br>
> +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());<br>
> +    instrumentOneFunc(F, &M, BPI, BFI);<br>
> +  }<br>
> +  return true;<br>
> +}<br>
> +<br>
> +static void setPGOCountOnFunc(PGOUseFunc &Func,<br>
> +                              IndexedInstrProfReader *PGOReader) {<br>
> +  if (Func.readCounters(PGOReader)) {<br>
> +    Func.populateCounters();<br>
> +    Func.setBranchWeights();<br>
> +  }<br>
> +}<br>
> +<br>
> +bool PGOInstrumentationUse::runOnModule(Module &M) {<br>
> +  DEBUG(dbgs() << "Read in profile counters: ");<br>
> +  auto &Ctx = M.getContext();<br>
> +  // Read the counter array from file.<br>
> +  auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);<br>
> +  if (std::error_code EC = ReaderOrErr.getError()) {<br>
> +    Ctx.diagnose(<br>
> +        DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));<br>
> +    return false;<br>
> +  }<br>
> +<br>
> +  PGOReader = std::move(ReaderOrErr.get());<br>
> +  if (!PGOReader) {<br>
> +    Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),<br>
> +                                          "Cannot get PGOReader"));<br>
> +    return false;<br>
> +  }<br>
> +<br>
> +  for (auto &F : M) {<br>
> +    if (F.isDeclaration())<br>
> +      continue;<br>
> +    BranchProbabilityInfo *BPI =<br>
> +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());<br>
> +    BlockFrequencyInfo *BFI =<br>
> +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());<br>
> +    PGOUseFunc Func(F, &M, BPI, BFI);<br>
> +    setPGOCountOnFunc(Func, PGOReader.get());<br>
> +  }<br>
> +  return true;<br>
> +}<br>
> Index: lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> +++ lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> @@ -19,4 +19,4 @@<br>
>  type = Library<br>
>  name = Instrumentation<br>
>  parent = Transforms<br>
> -required_libraries = Analysis Core MC Support TransformUtils<br>
> +required_libraries = Analysis Core MC Support TransformUtils ProfileData<br>
> Index: lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> +++ lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> @@ -60,6 +60,8 @@<br>
>    initializeAddressSanitizerModulePass(Registry);<br>
>    initializeBoundsCheckingPass(Registry);<br>
>    initializeGCOVProfilerPass(Registry);<br>
> +  initializePGOInstrumentationGenPass(Registry);<br>
> +  initializePGOInstrumentationUsePass(Registry);<br>
>    initializeInstrProfilingPass(Registry);<br>
>    initializeMemorySanitizerPass(Registry);<br>
>    initializeThreadSanitizerPass(Registry);<br>
> Index: lib/Transforms/Instrumentation/CMakeLists.txt<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/CMakeLists.txt<br>
> +++ lib/Transforms/Instrumentation/CMakeLists.txt<br>
> @@ -6,6 +6,7 @@<br>
>    MemorySanitizer.cpp<br>
>    Instrumentation.cpp<br>
>    InstrProfiling.cpp<br>
> +  PGOInstrumentation.cpp<br>
>    SafeStack.cpp<br>
>    SanitizerCoverage.cpp<br>
>    ThreadSanitizer.cpp<br>
> Index: lib/Transforms/Instrumentation/CFGMST.h<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ lib/Transforms/Instrumentation/CFGMST.h<br>
> @@ -0,0 +1,211 @@<br>
> +//===-- CFGMST.h - Minimum Spanning Tree for CFG -------*- C++ -*-===//<br>
> +//<br>
> +//                      The LLVM Compiler Infrastructure<br>
> +//<br>
> +// This file is distributed under the University of Illinois Open Source<br>
> +// License. See LICENSE.TXT for details.<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +//<br>
> +// This file implements Union-find algorithm to compute Minimum Spanning Tree<br>
> +// for a given CFG.<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +<br>
> +#include "llvm/ADT/DenseMap.h"<br>
> +#include "llvm/ADT/STLExtras.h"<br>
> +#include "llvm/Analysis/BlockFrequencyInfo.h"<br>
> +#include "llvm/Analysis/BranchProbabilityInfo.h"<br>
> +#include "llvm/Analysis/CFG.h"<br>
> +#include "llvm/Support/BranchProbability.h"<br>
> +#include "llvm/Support/Debug.h"<br>
> +#include "llvm/Support/raw_ostream.h"<br>
> +#include "llvm/Transforms/Utils/BasicBlockUtils.h"<br>
> +#include <string><br>
> +#include <utility><br>
> +#include <vector><br>
> +<br>
> +namespace llvm {<br>
> +<br>
> +#define DEBUG_TYPE "cfgmst"<br>
> +<br>
> +template <class Edge, class BBInfo> class CFGMST {<br>
> +public:<br>
> +  Function &F;<br>
> +<br>
> +  // Store all the edges in CFG. It may contain some stale edges<br>
> +  // when Removed is set.<br>
<br>
Might as well use doc comments here.<br>
<br>
> +  std::vector<std::unique_ptr<Edge>> AllEdges;<br>
> +<br>
> +  // This map records the auxiliary information for each BB.<br>
> +  DenseMap<const BasicBlock *, std::unique_ptr<BBInfo>> BBInfos;<br>
> +<br>
> +  // Find the root group of the G and compress the path from G to the root.<br>
> +  BBInfo *findAndCompressGroup(BBInfo *G) {<br>
> +    if (G->Group != G)<br>
> +      G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));<br>
> +    return static_cast<BBInfo *>(G->Group);<br>
> +  }<br>
> +<br>
> +  // Union BB1 and BB2 into the same group and return true.<br>
> +  // Returns false if BB1 and BB2 are already in the same group.<br>
> +  bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {<br>
> +    BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));<br>
> +    BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));<br>
> +<br>
> +    if (BB1G == BB2G)<br>
> +      return false;<br>
> +<br>
> +    // Make the smaller rank tree a direct child or the root of high rank tree.<br>
> +    if (BB1G->Rank < BB2G->Rank)<br>
> +      BB1G->Group = BB2G;<br>
> +    else {<br>
> +      BB2G->Group = BB1G;<br>
> +      // If the ranks are the same, increment root of one tree by one.<br>
> +      if (BB1G->Rank == BB2G->Rank)<br>
> +        BB1G->Rank++;<br>
> +    }<br>
> +    return true;<br>
> +  }<br>
> +<br>
> +  // Give BB, return the auxiliary information.<br>
> +  BBInfo &getBBInfo(const BasicBlock *BB) const {<br>
> +    auto It = BBInfos.find(BB);<br>
> +    assert(It->second.get() != nullptr);<br>
> +    return *It->second.get();<br>
> +  }<br>
> +<br>
> +  // Traverse the CFG using a stack. Find all the edges and assign the weight.<br>
> +  // Edges with large weight will be put into MST first so they are less likely<br>
> +  // to be instrumented.<br>
> +  void buildEdges() {<br>
> +    DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");<br>
> +<br>
> +    const BasicBlock *BB = &(F.getEntryBlock());<br>
> +    // Add a fake edge to the entry.<br>
> +    addEdge(nullptr, BB, BFI->getEntryFreq());<br>
> +<br>
> +    // Special handling for single BB functions.<br>
> +    if (succ_empty(BB)) {<br>
> +      addEdge(BB, nullptr, BFI->getEntryFreq());<br>
> +      return;<br>
> +    }<br>
> +<br>
> +    static const uint32_t CriticalEdgeMultiplier = 1000;<br>
> +<br>
> +    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {<br>
> +      TerminatorInst *TI = BB->getTerminator();<br>
> +      uint64_t BBWeight = BFI->getBlockFreq(&*BB).getFrequency();<br>
> +      uint64_t Weight;<br>
> +      if (int successors = TI->getNumSuccessors()) {<br>
> +        for (int i = 0; i != successors; ++i) {<br>
> +          BasicBlock *TargetBB = TI->getSuccessor(i);<br>
> +          bool Critical = isCriticalEdge(TI, i);<br>
> +          uint64_t scaleFactor = BBWeight;<br>
> +          if (Critical) {<br>
> +            if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)<br>
> +              scaleFactor *= CriticalEdgeMultiplier;<br>
> +            else<br>
> +              scaleFactor = UINT64_MAX;<br>
> +          }<br>
> +          Weight = BPI->getEdgeProbability(&*BB, TargetBB).scale(scaleFactor);<br>
> +          addEdge(&*BB, TargetBB, Weight).IsCritical = Critical;<br>
> +          DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to "<br>
> +                       << TargetBB->getName() << "  w=" << Weight << "\n");<br>
> +        }<br>
> +      } else {<br>
> +        addEdge(&*BB, nullptr, BBWeight);<br>
> +        DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to exit"<br>
> +                     << " w = " << BBWeight << "\n");<br>
> +      }<br>
> +    }<br>
> +  }<br>
> +<br>
> +  // Sort CFG edges based on its weight.<br>
> +  void sortEdgesByWeight() {<br>
> +    std::stable_sort(<br>
> +        AllEdges.begin(), AllEdges.end(),<br>
> +        [](const std::unique_ptr<Edge> &Edge1, const std::unique_ptr<Edge> &Edge2) {<br>
> +          return Edge1->Weight > Edge2->Weight;<br>
> +        });<br>
> +  }<br>
> +<br>
> +  // Traverse all the edges and compute the Minimum Weight Spanning Tree<br>
> +  // using union-find algorithm.<br>
> +  void computeMinimumSpanningTree() {<br>
> +    // First, put all the critical edge with landing-pad as the Dest to MST.<br>
> +    // This works around the insufficient support of critical edges split<br>
> +    // when destination BB is a landing pad.<br>
> +    for (auto &Ei : AllEdges) {<br>
> +      if (Ei->Removed)<br>
> +        continue;<br>
> +      if (Ei->IsCritical) {<br>
> +        if (Ei->DestBB && Ei->DestBB->isLandingPad()) {<br>
> +          if (unionGroups(Ei->SrcBB, Ei->DestBB))<br>
> +            Ei->InMST = true;<br>
> +        }<br>
> +      }<br>
> +    }<br>
> +<br>
> +    for (auto &Ei : AllEdges) {<br>
> +      if (Ei->Removed)<br>
> +        continue;<br>
> +      if (unionGroups(Ei->SrcBB, Ei->DestBB))<br>
> +        Ei->InMST = true;<br>
> +    }<br>
> +  }<br>
> +<br>
> +  // Dump the Debug information about the instrumentation.<br>
> +  void dumpEdges(raw_ostream &OS, const StringRef Message = StringRef()) const {<br>
> +    if (!Message.empty())<br>
> +      OS << Message << "\n";<br>
> +    OS << "  Number of Basic Blocks: " << BBInfos.size() << "\n";<br>
> +    for (auto &BI : BBInfos) {<br>
> +      const BasicBlock *BB = BI.first;<br>
> +      OS << "  BB: " << (BB == nullptr ? "FakeNode" : BB->getName()) << "  "<br>
> +         << BI.second->infoString() << "\n";<br>
> +    }<br>
> +<br>
> +    OS << "  Number of Edges: " << AllEdges.size()<br>
> +       << " (*: Instrument, C: CriticalEdge, -: Removed)\n";<br>
> +    uint32_t Count = 0;<br>
> +    for (auto &EI : AllEdges) {<br>
> +      OS << "  Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index << "-->"<br>
> +         << getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";<br>
> +    };<br>
> +  }<br>
> +<br>
> +  // Add an edge to AllEdges with weight W.<br>
> +  Edge &addEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W) {<br>
> +    uint32_t Index = BBInfos.size();<br>
> +    auto Iter = BBInfos.end();<br>
> +    bool Inserted;<br>
> +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Src, nullptr));<br>
> +    if (Inserted) {<br>
> +      // Newly inserted, update the real info.<br>
> +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));<br>
> +      Index++;<br>
> +    }<br>
> +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Dest, nullptr));<br>
> +    if (Inserted)<br>
> +      // Newly inserted, update the real info.<br>
> +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));<br>
> +    AllEdges.emplace_back(new Edge(Src, Dest, W));<br>
> +    return *AllEdges.back();<br>
> +  }<br>
> +<br>
> +  BranchProbabilityInfo *BPI;<br>
> +  BlockFrequencyInfo *BFI;<br>
> +<br>
> +public:<br>
> +  CFGMST(Function &Func, BranchProbabilityInfo *BPI_ = nullptr,<br>
> +         BlockFrequencyInfo *BFI_ = nullptr)<br>
> +      : F(Func), BPI(BPI_), BFI(BFI_) {<br>
> +    buildEdges();<br>
> +    sortEdgesByWeight();<br>
> +    computeMinimumSpanningTree();<br>
> +  }<br>
> +};<br>
> +<br>
> +#undef DEBUG_TYPE // "cfgmst"<br>
> +} // end namespace llvm<br>
> Index: lib/IR/DiagnosticInfo.cpp<br>
> ===================================================================<br>
> --- lib/IR/DiagnosticInfo.cpp<br>
> +++ lib/IR/DiagnosticInfo.cpp<br>
> @@ -132,6 +132,12 @@<br>
>    DP << getMsg();<br>
>  }<br>
><br>
> +void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const {<br>
> +  if (getFileName())<br>
> +    DP << getFileName() << ": ";<br>
> +  DP << getMsg();<br>
> +}<br>
> +<br>
>  bool DiagnosticInfoOptimizationBase::isLocationAvailable() const {<br>
>    return getDebugLoc();<br>
>  }<br>
> Index: include/llvm/Transforms/Instrumentation.h<br>
> ===================================================================<br>
> --- include/llvm/Transforms/Instrumentation.h<br>
> +++ include/llvm/Transforms/Instrumentation.h<br>
> @@ -79,6 +79,11 @@<br>
>  ModulePass *createGCOVProfilerPass(const GCOVOptions &Options =<br>
>                                     GCOVOptions::getDefault());<br>
><br>
> +// PGO Instrumention<br>
> +ModulePass *createPGOInstrumentationGenPass();<br>
> +ModulePass *<br>
> +createPGOInstrumentationUsePass(StringRef Filename = StringRef(""));<br>
> +<br>
>  /// Options for the frontend instrumentation based profiling pass.<br>
>  struct InstrProfOptions {<br>
>    InstrProfOptions() : NoRedZone(false) {}<br>
> @@ -149,6 +154,24 @@<br>
>  /// protect against stack-based overflow vulnerabilities.<br>
>  FunctionPass *createSafeStackPass(const TargetMachine *TM = nullptr);<br>
><br>
> +/// \brief Calculate what to divide by to scale counts.<br>
> +///<br>
> +/// Given the maximum count, calculate a divisor that will scale all the<br>
> +/// weights to strictly less than UINT32_MAX.<br>
> +static inline uint64_t calculateCountScale(uint64_t MaxCount) {<br>
> +  return MaxCount < UINT32_MAX ? 1 : MaxCount / UINT32_MAX + 1;<br>
> +}<br>
> +<br>
> +/// \brief Scale an individual branch count.<br>
> +///<br>
> +/// Scale a 64-bit weight down to 32-bits using \c Scale.<br>
> +///<br>
> +static inline uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale) {<br>
> +  uint64_t Scaled = Count / Scale;<br>
> +  assert(Scaled <= UINT32_MAX && "overflow 32-bits");<br>
> +  return Scaled;<br>
> +}<br>
> +<br>
>  } // End llvm namespace<br>
><br>
>  #endif<br>
> Index: include/llvm/LinkAllPasses.h<br>
> ===================================================================<br>
> --- include/llvm/LinkAllPasses.h<br>
> +++ include/llvm/LinkAllPasses.h<br>
> @@ -85,6 +85,8 @@<br>
>        (void) llvm::createDomOnlyViewerPass();<br>
>        (void) llvm::createDomViewerPass();<br>
>        (void) llvm::createGCOVProfilerPass();<br>
> +      (void) llvm::createPGOInstrumentationGenPass();<br>
> +      (void) llvm::createPGOInstrumentationUsePass();<br>
>        (void) llvm::createInstrProfilingPass();<br>
>        (void) llvm::createFunctionInliningPass();<br>
>        (void) llvm::createAlwaysInlinerPass();<br>
> Index: include/llvm/InitializePasses.h<br>
> ===================================================================<br>
> --- include/llvm/InitializePasses.h<br>
> +++ include/llvm/InitializePasses.h<br>
> @@ -117,6 +117,8 @@<br>
>  void initializeExpandPostRAPass(PassRegistry&);<br>
>  void initializeAAResultsWrapperPassPass(PassRegistry &);<br>
>  void initializeGCOVProfilerPass(PassRegistry&);<br>
> +void initializePGOInstrumentationGenPass(PassRegistry&);<br>
> +void initializePGOInstrumentationUsePass(PassRegistry&);<br>
>  void initializeInstrProfilingPass(PassRegistry&);<br>
>  void initializeAddressSanitizerPass(PassRegistry&);<br>
>  void initializeAddressSanitizerModulePass(PassRegistry&);<br>
> Index: include/llvm/IR/DiagnosticInfo.h<br>
> ===================================================================<br>
> --- include/llvm/IR/DiagnosticInfo.h<br>
> +++ include/llvm/IR/DiagnosticInfo.h<br>
> @@ -60,6 +60,7 @@<br>
>    DK_OptimizationRemarkAnalysisAliasing,<br>
>    DK_OptimizationFailure,<br>
>    DK_MIRParser,<br>
> +  DK_PGOProfile,<br>
>    DK_FirstPluginKind<br>
>  };<br>
><br>
> @@ -250,6 +251,31 @@<br>
>    const Twine &Msg;<br>
>  };<br>
><br>
> +/// Diagnostic information for the PGO profiler.<br>
> +class DiagnosticInfoPGOProfile : public DiagnosticInfo {<br>
> +public:<br>
> +  DiagnosticInfoPGOProfile(const char *FileName, const Twine &Msg,<br>
> +                           DiagnosticSeverity Severity = DS_Error)<br>
> +      : DiagnosticInfo(DK_PGOProfile, Severity), FileName(FileName), Msg(Msg) {}<br>
> +<br>
> +  /// \see DiagnosticInfo::print.<br>
> +  void print(DiagnosticPrinter &DP) const override;<br>
> +<br>
> +  static bool classof(const DiagnosticInfo *DI) {<br>
> +    return DI->getKind() == DK_PGOProfile;<br>
> +  }<br>
> +<br>
> +  const char *getFileName() const { return FileName; }<br>
> +  const Twine &getMsg() const { return Msg; }<br>
> +<br>
> +private:<br>
> +  /// Name of the input file associated with this diagnostic.<br>
> +  const char *FileName;<br>
> +<br>
> +  /// Message to report.<br>
> +  const Twine &Msg;<br>
> +};<br>
> +<br>
>  /// Common features for diagnostics dealing with optimization remarks.<br>
>  class DiagnosticInfoOptimizationBase : public DiagnosticInfo {<br>
>  public:<br>
</blockquote></div><br></div></div>