Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1 | //===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements PGO instrumentation using a minimum spanning tree based |
| 11 | // on the following paper: |
| 12 | // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points |
| 13 | // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13, |
| 14 | // Issue 3, pp 313-322 |
| 15 | // The idea of the algorithm based on the fact that for each node (except for |
| 16 | // the entry and exit), the sum of incoming edge counts equals the sum of |
| 17 | // outgoing edge counts. The count of edge on spanning tree can be derived from |
| 18 | // those edges not on the spanning tree. Knuth proves this method instruments |
| 19 | // the minimum number of edges. |
| 20 | // |
| 21 | // The minimal spanning tree here is actually a maximum weight tree -- on-tree |
| 22 | // edges have higher frequencies (more likely to execute). The idea is to |
| 23 | // instrument those less frequently executed edges to reduce the runtime |
| 24 | // overhead of instrumented binaries. |
| 25 | // |
| 26 | // This file contains two passes: |
| 27 | // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 28 | // count profile, and generates the instrumentation for indirect call |
| 29 | // profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 30 | // (2) Pass PGOInstrumentationUse which reads the edge count profile and |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 31 | // annotates the branch weights. It also reads the indirect call value |
| 32 | // profiling records and annotate the indirect call instructions. |
| 33 | // |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 34 | // To get the precise counter information, These two passes need to invoke at |
| 35 | // the same compilation point (so they see the same IR). For pass |
| 36 | // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For |
| 37 | // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and |
| 38 | // the profile is opened in module level and passed to each PGOUseFunc instance. |
| 39 | // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put |
| 40 | // in class FuncPGOInstrumentation. |
| 41 | // |
| 42 | // Class PGOEdge represents a CFG edge and some auxiliary information. Class |
| 43 | // BBInfo contains auxiliary information for each BB. These two classes are used |
| 44 | // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived |
| 45 | // class of PGOEdge and BBInfo, respectively. They contains extra data structure |
| 46 | // used in populating profile counters. |
| 47 | // The MST implementation is in Class CFGMST (CFGMST.h). |
| 48 | // |
| 49 | //===----------------------------------------------------------------------===// |
| 50 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 51 | #include "CFGMST.h" |
| 52 | #include "llvm/ADT/DenseMap.h" |
| 53 | #include "llvm/ADT/STLExtras.h" |
| 54 | #include "llvm/ADT/Statistic.h" |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 55 | #include "llvm/ADT/Triple.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 56 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 57 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 58 | #include "llvm/Analysis/CFG.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 59 | #include "llvm/IR/CallSite.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 60 | #include "llvm/IR/DiagnosticInfo.h" |
| 61 | #include "llvm/IR/IRBuilder.h" |
| 62 | #include "llvm/IR/InstIterator.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 63 | #include "llvm/IR/InstVisitor.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 64 | #include "llvm/IR/Instructions.h" |
| 65 | #include "llvm/IR/IntrinsicInst.h" |
| 66 | #include "llvm/IR/MDBuilder.h" |
| 67 | #include "llvm/IR/Module.h" |
| 68 | #include "llvm/Pass.h" |
| 69 | #include "llvm/ProfileData/InstrProfReader.h" |
| 70 | #include "llvm/Support/BranchProbability.h" |
| 71 | #include "llvm/Support/Debug.h" |
| 72 | #include "llvm/Support/JamCRC.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 73 | #include "llvm/Transforms/Instrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 74 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 75 | #include <string> |
| 76 | #include <utility> |
| 77 | #include <vector> |
| 78 | |
| 79 | using namespace llvm; |
| 80 | |
| 81 | #define DEBUG_TYPE "pgo-instrumentation" |
| 82 | |
| 83 | STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); |
| 84 | STATISTIC(NumOfPGOEdge, "Number of edges."); |
| 85 | STATISTIC(NumOfPGOBB, "Number of basic-blocks."); |
| 86 | STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); |
| 87 | STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); |
| 88 | STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); |
| 89 | STATISTIC(NumOfPGOMissing, "Number of functions without profile."); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 90 | STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 91 | |
| 92 | // Command line option to specify the file to read profile from. This is |
| 93 | // mainly used for testing. |
| 94 | static cl::opt<std::string> |
| 95 | PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, |
| 96 | cl::value_desc("filename"), |
| 97 | cl::desc("Specify the path of profile data file. This is" |
| 98 | "mainly for test purpose.")); |
| 99 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 100 | // Command line option to disable value profiling. The default is false: |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 101 | // i.e. value profiling is enabled by default. This is for debug purpose. |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 102 | static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), |
| 103 | cl::Hidden, |
| 104 | cl::desc("Disable Value Profiling")); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 105 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 106 | // Command line option to set the maximum number of VP annotations to write to |
| 107 | // the metada for a single indirect call callsite. |
| 108 | static cl::opt<unsigned> |
| 109 | MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, |
| 110 | cl::ZeroOrMore, |
| 111 | cl::desc("Max number of annotations for a single indirect " |
| 112 | "call callsite")); |
| 113 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 114 | namespace { |
| 115 | class PGOInstrumentationGen : public ModulePass { |
| 116 | public: |
| 117 | static char ID; |
| 118 | |
| 119 | PGOInstrumentationGen() : ModulePass(ID) { |
| 120 | initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry()); |
| 121 | } |
| 122 | |
| 123 | const char *getPassName() const override { |
| 124 | return "PGOInstrumentationGenPass"; |
| 125 | } |
| 126 | |
| 127 | private: |
| 128 | bool runOnModule(Module &M) override; |
| 129 | |
| 130 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 131 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 132 | } |
| 133 | }; |
| 134 | |
| 135 | class PGOInstrumentationUse : public ModulePass { |
| 136 | public: |
| 137 | static char ID; |
| 138 | |
| 139 | // Provide the profile filename as the parameter. |
| 140 | PGOInstrumentationUse(std::string Filename = "") |
| 141 | : ModulePass(ID), ProfileFileName(Filename) { |
| 142 | if (!PGOTestProfileFile.empty()) |
| 143 | ProfileFileName = PGOTestProfileFile; |
| 144 | initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry()); |
| 145 | } |
| 146 | |
| 147 | const char *getPassName() const override { |
| 148 | return "PGOInstrumentationUsePass"; |
| 149 | } |
| 150 | |
| 151 | private: |
| 152 | std::string ProfileFileName; |
| 153 | std::unique_ptr<IndexedInstrProfReader> PGOReader; |
| 154 | bool runOnModule(Module &M) override; |
| 155 | |
| 156 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 157 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 158 | } |
| 159 | }; |
| 160 | } // end anonymous namespace |
| 161 | |
| 162 | char PGOInstrumentationGen::ID = 0; |
| 163 | INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen", |
| 164 | "PGO instrumentation.", false, false) |
| 165 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 166 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
| 167 | INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen", |
| 168 | "PGO instrumentation.", false, false) |
| 169 | |
| 170 | ModulePass *llvm::createPGOInstrumentationGenPass() { |
| 171 | return new PGOInstrumentationGen(); |
| 172 | } |
| 173 | |
| 174 | char PGOInstrumentationUse::ID = 0; |
| 175 | INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use", |
| 176 | "Read PGO instrumentation profile.", false, false) |
| 177 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 178 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
| 179 | INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use", |
| 180 | "Read PGO instrumentation profile.", false, false) |
| 181 | |
| 182 | ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) { |
| 183 | return new PGOInstrumentationUse(Filename.str()); |
| 184 | } |
| 185 | |
| 186 | namespace { |
| 187 | /// \brief An MST based instrumentation for PGO |
| 188 | /// |
| 189 | /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO |
| 190 | /// in the function level. |
| 191 | struct PGOEdge { |
| 192 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 193 | // So there might be multiple edges with same SrcBB and DestBB. |
| 194 | const BasicBlock *SrcBB; |
| 195 | const BasicBlock *DestBB; |
| 196 | uint64_t Weight; |
| 197 | bool InMST; |
| 198 | bool Removed; |
| 199 | bool IsCritical; |
| 200 | PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 201 | : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), |
| 202 | IsCritical(false) {} |
| 203 | // Return the information string of an edge. |
| 204 | const std::string infoString() const { |
| 205 | return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + |
| 206 | (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); |
| 207 | } |
| 208 | }; |
| 209 | |
| 210 | // This class stores the auxiliary information for each BB. |
| 211 | struct BBInfo { |
| 212 | BBInfo *Group; |
| 213 | uint32_t Index; |
| 214 | uint32_t Rank; |
| 215 | |
| 216 | BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} |
| 217 | |
| 218 | // Return the information string of this object. |
| 219 | const std::string infoString() const { |
| 220 | return (Twine("Index=") + Twine(Index)).str(); |
| 221 | } |
| 222 | }; |
| 223 | |
| 224 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 225 | template <class Edge, class BBInfo> class FuncPGOInstrumentation { |
| 226 | private: |
| 227 | Function &F; |
| 228 | void computeCFGHash(); |
| 229 | |
| 230 | public: |
| 231 | std::string FuncName; |
| 232 | GlobalVariable *FuncNameVar; |
| 233 | // CFG hash value for this function. |
| 234 | uint64_t FunctionHash; |
| 235 | |
| 236 | // The Minimum Spanning Tree of function CFG. |
| 237 | CFGMST<Edge, BBInfo> MST; |
| 238 | |
| 239 | // Give an edge, find the BB that will be instrumented. |
| 240 | // Return nullptr if there is no BB to be instrumented. |
| 241 | BasicBlock *getInstrBB(Edge *E); |
| 242 | |
| 243 | // Return the auxiliary BB information. |
| 244 | BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } |
| 245 | |
| 246 | // Dump edges and BB information. |
| 247 | void dumpInfo(std::string Str = "") const { |
| 248 | MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 249 | Twine(FunctionHash) + "\t" + Str); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 250 | } |
| 251 | |
| 252 | FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false, |
| 253 | BranchProbabilityInfo *BPI = nullptr, |
| 254 | BlockFrequencyInfo *BFI = nullptr) |
| 255 | : F(Func), FunctionHash(0), MST(F, BPI, BFI) { |
| 256 | FuncName = getPGOFuncName(F); |
| 257 | computeCFGHash(); |
| 258 | DEBUG(dumpInfo("after CFGMST")); |
| 259 | |
| 260 | NumOfPGOBB += MST.BBInfos.size(); |
| 261 | for (auto &E : MST.AllEdges) { |
| 262 | if (E->Removed) |
| 263 | continue; |
| 264 | NumOfPGOEdge++; |
| 265 | if (!E->InMST) |
| 266 | NumOfPGOInstrument++; |
| 267 | } |
| 268 | |
| 269 | if (CreateGlobalVar) |
| 270 | FuncNameVar = createPGOFuncNameVar(F, FuncName); |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 271 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 272 | }; |
| 273 | |
| 274 | // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index |
| 275 | // value of each BB in the CFG. The higher 32 bits record the number of edges. |
| 276 | template <class Edge, class BBInfo> |
| 277 | void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { |
| 278 | std::vector<char> Indexes; |
| 279 | JamCRC JC; |
| 280 | for (auto &BB : F) { |
| 281 | const TerminatorInst *TI = BB.getTerminator(); |
| 282 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { |
| 283 | BasicBlock *Succ = TI->getSuccessor(I); |
| 284 | uint32_t Index = getBBInfo(Succ).Index; |
| 285 | for (int J = 0; J < 4; J++) |
| 286 | Indexes.push_back((char)(Index >> (J * 8))); |
| 287 | } |
| 288 | } |
| 289 | JC.update(Indexes); |
| 290 | FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); |
| 291 | } |
| 292 | |
| 293 | // Given a CFG E to be instrumented, find which BB to place the instrumented |
| 294 | // code. The function will split the critical edge if necessary. |
| 295 | template <class Edge, class BBInfo> |
| 296 | BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { |
| 297 | if (E->InMST || E->Removed) |
| 298 | return nullptr; |
| 299 | |
| 300 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 301 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 302 | // For a fake edge, instrument the real BB. |
| 303 | if (SrcBB == nullptr) |
| 304 | return DestBB; |
| 305 | if (DestBB == nullptr) |
| 306 | return SrcBB; |
| 307 | |
| 308 | // Instrument the SrcBB if it has a single successor, |
| 309 | // otherwise, the DestBB if this is not a critical edge. |
| 310 | TerminatorInst *TI = SrcBB->getTerminator(); |
| 311 | if (TI->getNumSuccessors() <= 1) |
| 312 | return SrcBB; |
| 313 | if (!E->IsCritical) |
| 314 | return DestBB; |
| 315 | |
| 316 | // For a critical edge, we have to split. Instrument the newly |
| 317 | // created BB. |
| 318 | NumOfPGOSplit++; |
| 319 | DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " |
| 320 | << getBBInfo(DestBB).Index << "\n"); |
| 321 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 322 | BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); |
| 323 | assert(InstrBB && "Critical edge is not split"); |
| 324 | |
| 325 | E->Removed = true; |
| 326 | return InstrBB; |
| 327 | } |
| 328 | |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 329 | // Visitor class that finds all indirect call sites. |
| 330 | struct PGOIndirectCallSiteVisitor |
| 331 | : public InstVisitor<PGOIndirectCallSiteVisitor> { |
Xinliang David Li | a55fd1a | 2016-03-30 02:16:07 +0000 | [diff] [blame] | 332 | std::vector<Instruction *> IndirectCallInsts; |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 333 | PGOIndirectCallSiteVisitor() {} |
| 334 | |
Xinliang David Li | a55fd1a | 2016-03-30 02:16:07 +0000 | [diff] [blame] | 335 | void visitCallSite(CallSite CS) { |
| 336 | Instruction *I = CS.getInstruction(); |
| 337 | CallInst *CI = dyn_cast<CallInst>(I); |
| 338 | if (CS.getCalledFunction() || !CS.getCalledValue() || |
| 339 | (CI && CI->isInlineAsm())) |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 340 | return; |
Xinliang David Li | a55fd1a | 2016-03-30 02:16:07 +0000 | [diff] [blame] | 341 | IndirectCallInsts.push_back(I); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 342 | } |
| 343 | }; |
| 344 | |
| 345 | // Visit all edge and instrument the edges not in MST, and do value profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 346 | // Critical edges will be split. |
| 347 | static void instrumentOneFunc(Function &F, Module *M, |
| 348 | BranchProbabilityInfo *BPI, |
| 349 | BlockFrequencyInfo *BFI) { |
| 350 | unsigned NumCounters = 0; |
| 351 | FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI); |
| 352 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 353 | if (!E->InMST && !E->Removed) |
| 354 | NumCounters++; |
| 355 | } |
| 356 | |
| 357 | uint32_t I = 0; |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 358 | Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 359 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 360 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); |
| 361 | if (!InstrBB) |
| 362 | continue; |
| 363 | |
| 364 | IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); |
| 365 | assert(Builder.GetInsertPoint() != InstrBB->end() && |
| 366 | "Cannot get the Instrumentation point"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 367 | Builder.CreateCall( |
| 368 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), |
| 369 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 370 | Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), |
| 371 | Builder.getInt32(I++)}); |
| 372 | } |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 373 | |
| 374 | if (DisableValueProfiling) |
| 375 | return; |
| 376 | |
| 377 | unsigned NumIndirectCallSites = 0; |
| 378 | PGOIndirectCallSiteVisitor ICV; |
| 379 | ICV.visit(F); |
| 380 | for (auto &I : ICV.IndirectCallInsts) { |
| 381 | CallSite CS(I); |
| 382 | Value *Callee = CS.getCalledValue(); |
| 383 | DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " |
| 384 | << NumIndirectCallSites << "\n"); |
| 385 | IRBuilder<> Builder(I); |
| 386 | assert(Builder.GetInsertPoint() != I->getParent()->end() && |
| 387 | "Cannot get the Instrumentation point"); |
| 388 | Builder.CreateCall( |
| 389 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), |
| 390 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 391 | Builder.getInt64(FuncInfo.FunctionHash), |
| 392 | Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), |
| 393 | Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget), |
| 394 | Builder.getInt32(NumIndirectCallSites++)}); |
| 395 | } |
| 396 | NumOfPGOICall += NumIndirectCallSites; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 397 | } |
| 398 | |
| 399 | // This class represents a CFG edge in profile use compilation. |
| 400 | struct PGOUseEdge : public PGOEdge { |
| 401 | bool CountValid; |
| 402 | uint64_t CountValue; |
| 403 | PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 404 | : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} |
| 405 | |
| 406 | // Set edge count value |
| 407 | void setEdgeCount(uint64_t Value) { |
| 408 | CountValue = Value; |
| 409 | CountValid = true; |
| 410 | } |
| 411 | |
| 412 | // Return the information string for this object. |
| 413 | const std::string infoString() const { |
| 414 | if (!CountValid) |
| 415 | return PGOEdge::infoString(); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 416 | return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) |
| 417 | .str(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 418 | } |
| 419 | }; |
| 420 | |
| 421 | typedef SmallVector<PGOUseEdge *, 2> DirectEdges; |
| 422 | |
| 423 | // This class stores the auxiliary information for each BB. |
| 424 | struct UseBBInfo : public BBInfo { |
| 425 | uint64_t CountValue; |
| 426 | bool CountValid; |
| 427 | int32_t UnknownCountInEdge; |
| 428 | int32_t UnknownCountOutEdge; |
| 429 | DirectEdges InEdges; |
| 430 | DirectEdges OutEdges; |
| 431 | UseBBInfo(unsigned IX) |
| 432 | : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), |
| 433 | UnknownCountOutEdge(0) {} |
| 434 | UseBBInfo(unsigned IX, uint64_t C) |
| 435 | : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), |
| 436 | UnknownCountOutEdge(0) {} |
| 437 | |
| 438 | // Set the profile count value for this BB. |
| 439 | void setBBInfoCount(uint64_t Value) { |
| 440 | CountValue = Value; |
| 441 | CountValid = true; |
| 442 | } |
| 443 | |
| 444 | // Return the information string of this object. |
| 445 | const std::string infoString() const { |
| 446 | if (!CountValid) |
| 447 | return BBInfo::infoString(); |
| 448 | return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); |
| 449 | } |
| 450 | }; |
| 451 | |
| 452 | // Sum up the count values for all the edges. |
| 453 | static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { |
| 454 | uint64_t Total = 0; |
| 455 | for (auto &E : Edges) { |
| 456 | if (E->Removed) |
| 457 | continue; |
| 458 | Total += E->CountValue; |
| 459 | } |
| 460 | return Total; |
| 461 | } |
| 462 | |
| 463 | class PGOUseFunc { |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 464 | public: |
| 465 | PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr, |
| 466 | BlockFrequencyInfo *BFI = nullptr) |
| 467 | : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI), |
| 468 | FreqAttr(FFA_Normal) {} |
| 469 | |
| 470 | // Read counts for the instrumented BB from profile. |
| 471 | bool readCounters(IndexedInstrProfReader *PGOReader); |
| 472 | |
| 473 | // Populate the counts for all BBs. |
| 474 | void populateCounters(); |
| 475 | |
| 476 | // Set the branch weights based on the count values. |
| 477 | void setBranchWeights(); |
| 478 | |
| 479 | // Annotate the indirect call sites. |
| 480 | void annotateIndirectCallSites(); |
| 481 | |
| 482 | // The hotness of the function from the profile count. |
| 483 | enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; |
| 484 | |
| 485 | // Return the funtion hotness from the profile. |
| 486 | FuncFreqAttr getFuncFreqAttr() const { |
| 487 | return FreqAttr; |
| 488 | } |
| 489 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 490 | private: |
| 491 | Function &F; |
| 492 | Module *M; |
| 493 | // This member stores the shared information with class PGOGenFunc. |
| 494 | FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; |
| 495 | |
| 496 | // Return the auxiliary BB information. |
| 497 | UseBBInfo &getBBInfo(const BasicBlock *BB) const { |
| 498 | return FuncInfo.getBBInfo(BB); |
| 499 | } |
| 500 | |
| 501 | // The maximum count value in the profile. This is only used in PGO use |
| 502 | // compilation. |
| 503 | uint64_t ProgramMaxCount; |
| 504 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 505 | // ProfileRecord for this function. |
| 506 | InstrProfRecord ProfileRecord; |
| 507 | |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 508 | // Function hotness info derived from profile. |
| 509 | FuncFreqAttr FreqAttr; |
| 510 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 511 | // Find the Instrumented BB and set the value. |
| 512 | void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); |
| 513 | |
| 514 | // Set the edge counter value for the unknown edge -- there should be only |
| 515 | // one unknown edge. |
| 516 | void setEdgeCount(DirectEdges &Edges, uint64_t Value); |
| 517 | |
| 518 | // Return FuncName string; |
| 519 | const std::string getFuncName() const { return FuncInfo.FuncName; } |
| 520 | |
| 521 | // Set the hot/cold inline hints based on the count values. |
| 522 | // FIXME: This function should be removed once the functionality in |
| 523 | // the inliner is implemented. |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 524 | void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 525 | if (ProgramMaxCount == 0) |
| 526 | return; |
| 527 | // Threshold of the hot functions. |
| 528 | const BranchProbability HotFunctionThreshold(1, 100); |
| 529 | // Threshold of the cold functions. |
| 530 | const BranchProbability ColdFunctionThreshold(2, 10000); |
| 531 | if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 532 | FreqAttr = FFA_Hot; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 533 | else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 534 | FreqAttr = FFA_Cold; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 535 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 536 | }; |
| 537 | |
| 538 | // Visit all the edges and assign the count value for the instrumented |
| 539 | // edges and the BB. |
| 540 | void PGOUseFunc::setInstrumentedCounts( |
| 541 | const std::vector<uint64_t> &CountFromProfile) { |
| 542 | |
| 543 | // Use a worklist as we will update the vector during the iteration. |
| 544 | std::vector<PGOUseEdge *> WorkList; |
| 545 | for (auto &E : FuncInfo.MST.AllEdges) |
| 546 | WorkList.push_back(E.get()); |
| 547 | |
| 548 | uint32_t I = 0; |
| 549 | for (auto &E : WorkList) { |
| 550 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E); |
| 551 | if (!InstrBB) |
| 552 | continue; |
| 553 | uint64_t CountValue = CountFromProfile[I++]; |
| 554 | if (!E->Removed) { |
| 555 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 556 | E->setEdgeCount(CountValue); |
| 557 | continue; |
| 558 | } |
| 559 | |
| 560 | // Need to add two new edges. |
| 561 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 562 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 563 | // Add new edge of SrcBB->InstrBB. |
| 564 | PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); |
| 565 | NewEdge.setEdgeCount(CountValue); |
| 566 | // Add new edge of InstrBB->DestBB. |
| 567 | PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); |
| 568 | NewEdge1.setEdgeCount(CountValue); |
| 569 | NewEdge1.InMST = true; |
| 570 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | // Set the count value for the unknown edge. There should be one and only one |
| 575 | // unknown edge in Edges vector. |
| 576 | void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { |
| 577 | for (auto &E : Edges) { |
| 578 | if (E->CountValid) |
| 579 | continue; |
| 580 | E->setEdgeCount(Value); |
| 581 | |
| 582 | getBBInfo(E->SrcBB).UnknownCountOutEdge--; |
| 583 | getBBInfo(E->DestBB).UnknownCountInEdge--; |
| 584 | return; |
| 585 | } |
| 586 | llvm_unreachable("Cannot find the unknown count edge"); |
| 587 | } |
| 588 | |
| 589 | // Read the profile from ProfileFileName and assign the value to the |
| 590 | // instrumented BB and the edges. This function also updates ProgramMaxCount. |
| 591 | // Return true if the profile are successfully read, and false on errors. |
| 592 | bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { |
| 593 | auto &Ctx = M->getContext(); |
| 594 | ErrorOr<InstrProfRecord> Result = |
| 595 | PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); |
| 596 | if (std::error_code EC = Result.getError()) { |
| 597 | if (EC == instrprof_error::unknown_function) |
| 598 | NumOfPGOMissing++; |
| 599 | else if (EC == instrprof_error::hash_mismatch || |
| 600 | EC == llvm::instrprof_error::malformed) |
| 601 | NumOfPGOMismatch++; |
| 602 | |
| 603 | std::string Msg = EC.message() + std::string(" ") + F.getName().str(); |
| 604 | Ctx.diagnose( |
| 605 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 606 | return false; |
| 607 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 608 | ProfileRecord = std::move(Result.get()); |
| 609 | std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 610 | |
| 611 | NumOfPGOFunc++; |
| 612 | DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); |
| 613 | uint64_t ValueSum = 0; |
| 614 | for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { |
| 615 | DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); |
| 616 | ValueSum += CountFromProfile[I]; |
| 617 | } |
| 618 | |
| 619 | DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); |
| 620 | |
| 621 | getBBInfo(nullptr).UnknownCountOutEdge = 2; |
| 622 | getBBInfo(nullptr).UnknownCountInEdge = 2; |
| 623 | |
| 624 | setInstrumentedCounts(CountFromProfile); |
| 625 | ProgramMaxCount = PGOReader->getMaximumFunctionCount(); |
| 626 | return true; |
| 627 | } |
| 628 | |
| 629 | // Populate the counters from instrumented BBs to all BBs. |
| 630 | // In the end of this operation, all BBs should have a valid count value. |
| 631 | void PGOUseFunc::populateCounters() { |
| 632 | // First set up Count variable for all BBs. |
| 633 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 634 | if (E->Removed) |
| 635 | continue; |
| 636 | |
| 637 | const BasicBlock *SrcBB = E->SrcBB; |
| 638 | const BasicBlock *DestBB = E->DestBB; |
| 639 | UseBBInfo &SrcInfo = getBBInfo(SrcBB); |
| 640 | UseBBInfo &DestInfo = getBBInfo(DestBB); |
| 641 | SrcInfo.OutEdges.push_back(E.get()); |
| 642 | DestInfo.InEdges.push_back(E.get()); |
| 643 | SrcInfo.UnknownCountOutEdge++; |
| 644 | DestInfo.UnknownCountInEdge++; |
| 645 | |
| 646 | if (!E->CountValid) |
| 647 | continue; |
| 648 | DestInfo.UnknownCountInEdge--; |
| 649 | SrcInfo.UnknownCountOutEdge--; |
| 650 | } |
| 651 | |
| 652 | bool Changes = true; |
| 653 | unsigned NumPasses = 0; |
| 654 | while (Changes) { |
| 655 | NumPasses++; |
| 656 | Changes = false; |
| 657 | |
| 658 | // For efficient traversal, it's better to start from the end as most |
| 659 | // of the instrumented edges are at the end. |
| 660 | for (auto &BB : reverse(F)) { |
| 661 | UseBBInfo &Count = getBBInfo(&BB); |
| 662 | if (!Count.CountValid) { |
| 663 | if (Count.UnknownCountOutEdge == 0) { |
| 664 | Count.CountValue = sumEdgeCount(Count.OutEdges); |
| 665 | Count.CountValid = true; |
| 666 | Changes = true; |
| 667 | } else if (Count.UnknownCountInEdge == 0) { |
| 668 | Count.CountValue = sumEdgeCount(Count.InEdges); |
| 669 | Count.CountValid = true; |
| 670 | Changes = true; |
| 671 | } |
| 672 | } |
| 673 | if (Count.CountValid) { |
| 674 | if (Count.UnknownCountOutEdge == 1) { |
| 675 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges); |
| 676 | setEdgeCount(Count.OutEdges, Total); |
| 677 | Changes = true; |
| 678 | } |
| 679 | if (Count.UnknownCountInEdge == 1) { |
| 680 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges); |
| 681 | setEdgeCount(Count.InEdges, Total); |
| 682 | Changes = true; |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); |
| 689 | // Assert every BB has a valid counter. |
| 690 | uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; |
| 691 | uint64_t FuncMaxCount = FuncEntryCount; |
| 692 | for (auto &BB : F) { |
| 693 | assert(getBBInfo(&BB).CountValid && "BB count is not valid"); |
| 694 | uint64_t Count = getBBInfo(&BB).CountValue; |
| 695 | if (Count > FuncMaxCount) |
| 696 | FuncMaxCount = Count; |
| 697 | } |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 698 | markFunctionAttributes(FuncEntryCount, FuncMaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 699 | |
| 700 | DEBUG(FuncInfo.dumpInfo("after reading profile.")); |
| 701 | } |
| 702 | |
| 703 | // Assign the scaled count values to the BB with multiple out edges. |
| 704 | void PGOUseFunc::setBranchWeights() { |
| 705 | // Generate MD_prof metadata for every branch instruction. |
| 706 | DEBUG(dbgs() << "\nSetting branch weights.\n"); |
| 707 | MDBuilder MDB(M->getContext()); |
| 708 | for (auto &BB : F) { |
| 709 | TerminatorInst *TI = BB.getTerminator(); |
| 710 | if (TI->getNumSuccessors() < 2) |
| 711 | continue; |
| 712 | if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) |
| 713 | continue; |
| 714 | if (getBBInfo(&BB).CountValue == 0) |
| 715 | continue; |
| 716 | |
| 717 | // We have a non-zero Branch BB. |
| 718 | const UseBBInfo &BBCountInfo = getBBInfo(&BB); |
| 719 | unsigned Size = BBCountInfo.OutEdges.size(); |
| 720 | SmallVector<unsigned, 2> EdgeCounts(Size, 0); |
| 721 | uint64_t MaxCount = 0; |
| 722 | for (unsigned s = 0; s < Size; s++) { |
| 723 | const PGOUseEdge *E = BBCountInfo.OutEdges[s]; |
| 724 | const BasicBlock *SrcBB = E->SrcBB; |
| 725 | const BasicBlock *DestBB = E->DestBB; |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 726 | if (DestBB == nullptr) |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 727 | continue; |
| 728 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 729 | uint64_t EdgeCount = E->CountValue; |
| 730 | if (EdgeCount > MaxCount) |
| 731 | MaxCount = EdgeCount; |
| 732 | EdgeCounts[SuccNum] = EdgeCount; |
| 733 | } |
| 734 | assert(MaxCount > 0 && "Bad max count"); |
| 735 | uint64_t Scale = calculateCountScale(MaxCount); |
| 736 | SmallVector<unsigned, 4> Weights; |
| 737 | for (const auto &ECI : EdgeCounts) |
| 738 | Weights.push_back(scaleBranchCount(ECI, Scale)); |
| 739 | |
| 740 | TI->setMetadata(llvm::LLVMContext::MD_prof, |
| 741 | MDB.createBranchWeights(Weights)); |
| 742 | DEBUG(dbgs() << "Weight is: "; |
| 743 | for (const auto &W : Weights) { dbgs() << W << " "; } |
| 744 | dbgs() << "\n";); |
| 745 | } |
| 746 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 747 | |
| 748 | // Traverse all the indirect callsites and annotate the instructions. |
| 749 | void PGOUseFunc::annotateIndirectCallSites() { |
| 750 | if (DisableValueProfiling) |
| 751 | return; |
| 752 | |
Rong Xu | b534166 | 2016-03-30 18:37:52 +0000 | [diff] [blame^] | 753 | // Write out the PGOFuncName if this is different from it's raw name. |
| 754 | // This should only apply to internal linkage functions only. |
| 755 | const std::string &FuncName = getPGOFuncName(F); |
| 756 | if (FuncName != F.getName()) { |
| 757 | LLVMContext &C = F.getContext(); |
| 758 | MDNode *N = MDNode::get(C, MDString::get(C, FuncName.c_str())); |
| 759 | F.setMetadata("PGOFuncName", N); |
| 760 | } |
| 761 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 762 | unsigned IndirectCallSiteIndex = 0; |
| 763 | PGOIndirectCallSiteVisitor ICV; |
| 764 | ICV.visit(F); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 765 | unsigned NumValueSites = |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 766 | ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget); |
| 767 | if (NumValueSites != ICV.IndirectCallInsts.size()) { |
| 768 | std::string Msg = |
| 769 | std::string("Inconsistent number of indirect call sites: ") + |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 770 | F.getName().str(); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 771 | auto &Ctx = M->getContext(); |
| 772 | Ctx.diagnose( |
| 773 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 774 | return; |
| 775 | } |
| 776 | |
| 777 | for (auto &I : ICV.IndirectCallInsts) { |
| 778 | DEBUG(dbgs() << "Read one indirect call instrumentation: Index=" |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 779 | << IndirectCallSiteIndex << " out of " << NumValueSites |
| 780 | << "\n"); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 781 | annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget, |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 782 | IndirectCallSiteIndex, MaxNumAnnotations); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 783 | IndirectCallSiteIndex++; |
| 784 | } |
| 785 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 786 | } // end anonymous namespace |
| 787 | |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 788 | // Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime |
| 789 | // aware this is an ir_level profile so it can set the version flag. |
| 790 | static void createIRLevelProfileFlagVariable(Module &M) { |
| 791 | Type *IntTy64 = Type::getInt64Ty(M.getContext()); |
| 792 | uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 793 | auto IRLevelVersionVariable = new GlobalVariable( |
| 794 | M, IntTy64, true, GlobalVariable::ExternalLinkage, |
| 795 | Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), |
| 796 | INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR)); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 797 | IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); |
| 798 | Triple TT(M.getTargetTriple()); |
| 799 | if (TT.isOSBinFormatMachO()) |
| 800 | IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage); |
| 801 | else |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 802 | IRLevelVersionVariable->setComdat(M.getOrInsertComdat( |
| 803 | StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR)))); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 804 | } |
| 805 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 806 | bool PGOInstrumentationGen::runOnModule(Module &M) { |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 807 | createIRLevelProfileFlagVariable(M); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 808 | for (auto &F : M) { |
| 809 | if (F.isDeclaration()) |
| 810 | continue; |
| 811 | BranchProbabilityInfo *BPI = |
| 812 | &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI()); |
| 813 | BlockFrequencyInfo *BFI = |
| 814 | &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI()); |
| 815 | instrumentOneFunc(F, &M, BPI, BFI); |
| 816 | } |
| 817 | return true; |
| 818 | } |
| 819 | |
| 820 | static void setPGOCountOnFunc(PGOUseFunc &Func, |
| 821 | IndexedInstrProfReader *PGOReader) { |
| 822 | if (Func.readCounters(PGOReader)) { |
| 823 | Func.populateCounters(); |
| 824 | Func.setBranchWeights(); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 825 | Func.annotateIndirectCallSites(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 826 | } |
| 827 | } |
| 828 | |
| 829 | bool PGOInstrumentationUse::runOnModule(Module &M) { |
| 830 | DEBUG(dbgs() << "Read in profile counters: "); |
| 831 | auto &Ctx = M.getContext(); |
| 832 | // Read the counter array from file. |
| 833 | auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); |
| 834 | if (std::error_code EC = ReaderOrErr.getError()) { |
| 835 | Ctx.diagnose( |
| 836 | DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message())); |
| 837 | return false; |
| 838 | } |
| 839 | |
| 840 | PGOReader = std::move(ReaderOrErr.get()); |
| 841 | if (!PGOReader) { |
| 842 | Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), |
| 843 | "Cannot get PGOReader")); |
| 844 | return false; |
| 845 | } |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 846 | // TODO: might need to change the warning once the clang option is finalized. |
| 847 | if (!PGOReader->isIRLevelProfile()) { |
| 848 | Ctx.diagnose(DiagnosticInfoPGOProfile( |
| 849 | ProfileFileName.data(), "Not an IR level instrumentation profile")); |
| 850 | return false; |
| 851 | } |
| 852 | |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 853 | std::vector<Function *> HotFunctions; |
| 854 | std::vector<Function *> ColdFunctions; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 855 | for (auto &F : M) { |
| 856 | if (F.isDeclaration()) |
| 857 | continue; |
| 858 | BranchProbabilityInfo *BPI = |
| 859 | &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI()); |
| 860 | BlockFrequencyInfo *BFI = |
| 861 | &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI()); |
| 862 | PGOUseFunc Func(F, &M, BPI, BFI); |
| 863 | setPGOCountOnFunc(Func, PGOReader.get()); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 864 | PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); |
| 865 | if (FreqAttr == PGOUseFunc::FFA_Cold) |
| 866 | ColdFunctions.push_back(&F); |
| 867 | else if (FreqAttr == PGOUseFunc::FFA_Hot) |
| 868 | HotFunctions.push_back(&F); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 869 | } |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 870 | |
| 871 | // Set function hotness attribute from the profile. |
| 872 | for (auto &F : HotFunctions) { |
| 873 | F->addFnAttr(llvm::Attribute::InlineHint); |
| 874 | DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() |
| 875 | << "\n"); |
| 876 | } |
| 877 | for (auto &F : ColdFunctions) { |
| 878 | F->addFnAttr(llvm::Attribute::Cold); |
| 879 | DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); |
| 880 | } |
| 881 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 882 | return true; |
| 883 | } |