blob: 1e30dbf6b55a86baff7a2ca86b101f6549cff71c [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- 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 Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// 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
Xinliang David Li8aebf442016-05-06 05:49:19 +000051#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000052#include "CFGMST.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000054#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000056#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/Analysis/BlockFrequencyInfo.h"
58#include "llvm/Analysis/BranchProbabilityInfo.h"
59#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000060#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000061#include "llvm/Analysis/LoopInfo.h"
Rong Xued9fec72016-01-21 18:11:44 +000062#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000063#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000064#include "llvm/IR/Dominators.h"
Rong Xu705f7772016-07-25 18:45:37 +000065#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000066#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/InstIterator.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/IntrinsicInst.h"
70#include "llvm/IR/MDBuilder.h"
71#include "llvm/IR/Module.h"
72#include "llvm/Pass.h"
73#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000074#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000075#include "llvm/Support/BranchProbability.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000076#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Support/Debug.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000078#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +000079#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000080#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000081#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000082#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000083#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000084#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000085#include <utility>
86#include <vector>
87
88using namespace llvm;
89
90#define DEBUG_TYPE "pgo-instrumentation"
91
92STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000093STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +000094STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000095STATISTIC(NumOfPGOEdge, "Number of edges.");
96STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
97STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
98STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
99STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
100STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000101STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000102
103// Command line option to specify the file to read profile from. This is
104// mainly used for testing.
105static cl::opt<std::string>
106 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
107 cl::value_desc("filename"),
108 cl::desc("Specify the path of profile data file. This is"
109 "mainly for test purpose."));
110
Rong Xuecdc98f2016-03-04 22:08:44 +0000111// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000112// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000113static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
114 cl::Hidden,
115 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000116
Rong Xuecdc98f2016-03-04 22:08:44 +0000117// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000118// the metadata for a single indirect call callsite.
119static cl::opt<unsigned> MaxNumAnnotations(
120 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
121 cl::desc("Max number of annotations for a single indirect "
122 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000123
Rong Xue60343d2017-03-17 18:07:26 +0000124// Command line option to set the maximum number of value annotations
125// to write to the metadata for a single memop intrinsic.
126static cl::opt<unsigned> MaxNumMemOPAnnotations(
127 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
128 cl::desc("Max number of preicise value annotations for a single memop"
129 "intrinsic"));
130
Rong Xu705f7772016-07-25 18:45:37 +0000131// Command line option to control appending FunctionHash to the name of a COMDAT
132// function. This is to avoid the hash mismatch caused by the preinliner.
133static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000134 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000135 cl::desc("Append function hash to the name of COMDAT function to avoid "
136 "function hash mismatch due to the preinliner"));
137
Rong Xu0698de92016-05-13 17:26:06 +0000138// Command line option to enable/disable the warning about missing profile
139// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000140static cl::opt<bool>
141 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
142 cl::desc("Use this option to turn on/off "
143 "warnings about missing profile data for "
144 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000145
146// Command line option to enable/disable the warning about a hash mismatch in
147// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000148static cl::opt<bool>
149 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
150 cl::desc("Use this option to turn off/on "
151 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000152
Rong Xu20f5df12017-01-11 20:19:41 +0000153// Command line option to enable/disable the warning about a hash mismatch in
154// the profile data for Comdat functions, which often turns out to be false
155// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000156static cl::opt<bool>
157 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
158 cl::Hidden,
159 cl::desc("The option is used to turn on/off "
160 "warnings about hash mismatch for comdat "
161 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000162
Xinliang David Li4ca17332016-09-18 18:34:07 +0000163// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000164static cl::opt<bool>
165 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
166 cl::desc("Use this option to turn on/off SELECT "
167 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000168
Xinliang David Lid289e452017-01-27 19:06:25 +0000169// Command line option to turn on CFG dot dump of raw profile counts
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000170static cl::opt<bool>
171 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
172 cl::desc("A boolean option to show CFG dag "
173 "with raw profile counts from "
174 "profile data. See also option "
175 "-pgo-view-counts. To limit graph "
176 "display to only one function, use "
177 "filtering option -view-bfi-func-name."));
Xinliang David Lid289e452017-01-27 19:06:25 +0000178
Rong Xu8e06e802017-03-17 20:51:44 +0000179// Command line option to enable/disable memop intrinsic call.size profiling.
180static cl::opt<bool>
181 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
182 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000183 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000184
Xinliang David Licb253ce2017-01-23 18:58:24 +0000185// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000186// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Xinliang David Licb253ce2017-01-23 18:58:24 +0000187extern cl::opt<bool> PGOViewCounts;
188
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000189// Command line option to specify the name of the function for CFG dump
190// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
191extern cl::opt<std::string> ViewBlockFreqFuncName;
192
Rong Xuf430ae42015-12-09 18:08:16 +0000193namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000194
195/// The select instruction visitor plays three roles specified
196/// by the mode. In \c VM_counting mode, it simply counts the number of
197/// select instructions. In \c VM_instrument mode, it inserts code to count
198/// the number times TrueValue of select is taken. In \c VM_annotate mode,
199/// it reads the profile data and annotate the select instruction with metadata.
200enum VisitMode { VM_counting, VM_instrument, VM_annotate };
201class PGOUseFunc;
202
203/// Instruction Visitor class to visit select instructions.
204struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
205 Function &F;
206 unsigned NSIs = 0; // Number of select instructions instrumented.
207 VisitMode Mode = VM_counting; // Visiting mode.
208 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
209 unsigned TotalNumCtrs = 0; // Total number of counters
210 GlobalVariable *FuncNameVar = nullptr;
211 uint64_t FuncHash = 0;
212 PGOUseFunc *UseFunc = nullptr;
213
214 SelectInstVisitor(Function &Func) : F(Func) {}
215
216 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000217 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000218 Mode = VM_counting;
219 visit(Func);
220 }
221 // Visit the IR stream and instrument all select instructions. \p
222 // Ind is a pointer to the counter index variable; \p TotalNC
223 // is the total number of counters; \p FNV is the pointer to the
224 // PGO function name var; \p FHash is the function hash.
225 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
226 GlobalVariable *FNV, uint64_t FHash) {
227 Mode = VM_instrument;
228 CurCtrIdx = Ind;
229 TotalNumCtrs = TotalNC;
230 FuncHash = FHash;
231 FuncNameVar = FNV;
232 visit(Func);
233 }
234
235 // Visit the IR stream and annotate all select instructions.
236 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
237 Mode = VM_annotate;
238 UseFunc = UF;
239 CurCtrIdx = Ind;
240 visit(Func);
241 }
242
243 void instrumentOneSelectInst(SelectInst &SI);
244 void annotateOneSelectInst(SelectInst &SI);
245 // Visit \p SI instruction and perform tasks according to visit mode.
246 void visitSelectInst(SelectInst &SI);
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000247 // Return the number of select instructions. This needs be called after
248 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000249 unsigned getNumOfSelectInsts() const { return NSIs; }
250};
251
Rong Xu60faea12017-03-16 21:15:48 +0000252/// Instruction Visitor class to visit memory intrinsic calls.
253struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
254 Function &F;
255 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
256 VisitMode Mode = VM_counting; // Visiting mode.
257 unsigned CurCtrId = 0; // Current counter index.
258 unsigned TotalNumCtrs = 0; // Total number of counters
259 GlobalVariable *FuncNameVar = nullptr;
260 uint64_t FuncHash = 0;
261 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000262 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000263
264 MemIntrinsicVisitor(Function &Func) : F(Func) {}
265
266 void countMemIntrinsics(Function &Func) {
267 NMemIs = 0;
268 Mode = VM_counting;
269 visit(Func);
270 }
Rong Xue60343d2017-03-17 18:07:26 +0000271
Rong Xu60faea12017-03-16 21:15:48 +0000272 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
273 GlobalVariable *FNV, uint64_t FHash) {
274 Mode = VM_instrument;
275 TotalNumCtrs = TotalNC;
276 FuncHash = FHash;
277 FuncNameVar = FNV;
278 visit(Func);
279 }
280
Rong Xue60343d2017-03-17 18:07:26 +0000281 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
282 Candidates.clear();
283 Mode = VM_annotate;
284 visit(Func);
285 return Candidates;
286 }
287
Rong Xu60faea12017-03-16 21:15:48 +0000288 // Visit the IR stream and annotate all mem intrinsic call instructions.
289 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
290 // Visit \p MI instruction and perform tasks according to visit mode.
291 void visitMemIntrinsic(MemIntrinsic &SI);
292 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
293};
294
Xinliang David Li8aebf442016-05-06 05:49:19 +0000295class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000296public:
297 static char ID;
298
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000299 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000300 initializePGOInstrumentationGenLegacyPassPass(
301 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000302 }
303
Mehdi Amini117296c2016-10-01 02:56:57 +0000304 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000305
306private:
307 bool runOnModule(Module &M) override;
308
309 void getAnalysisUsage(AnalysisUsage &AU) const override {
310 AU.addRequired<BlockFrequencyInfoWrapperPass>();
311 }
312};
313
Xinliang David Lid55827f2016-05-07 05:39:12 +0000314class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000315public:
316 static char ID;
317
318 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000319 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000320 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000321 if (!PGOTestProfileFile.empty())
322 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000323 initializePGOInstrumentationUseLegacyPassPass(
324 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000325 }
326
Mehdi Amini117296c2016-10-01 02:56:57 +0000327 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000328
329private:
330 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000331
Xinliang David Lida195582016-05-10 21:59:52 +0000332 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000333 void getAnalysisUsage(AnalysisUsage &AU) const override {
334 AU.addRequired<BlockFrequencyInfoWrapperPass>();
335 }
336};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000337
Rong Xuf430ae42015-12-09 18:08:16 +0000338} // end anonymous namespace
339
Xinliang David Li8aebf442016-05-06 05:49:19 +0000340char PGOInstrumentationGenLegacyPass::ID = 0;
341INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000342 "PGO instrumentation.", false, false)
343INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
344INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000345INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000346 "PGO instrumentation.", false, false)
347
Xinliang David Li8aebf442016-05-06 05:49:19 +0000348ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
349 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000350}
351
Xinliang David Lid55827f2016-05-07 05:39:12 +0000352char PGOInstrumentationUseLegacyPass::ID = 0;
353INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000354 "Read PGO instrumentation profile.", false, false)
355INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
356INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000357INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000358 "Read PGO instrumentation profile.", false, false)
359
Xinliang David Lid55827f2016-05-07 05:39:12 +0000360ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
361 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000362}
363
364namespace {
365/// \brief An MST based instrumentation for PGO
366///
367/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
368/// in the function level.
369struct PGOEdge {
370 // This class implements the CFG edges. Note the CFG can be a multi-graph.
371 // So there might be multiple edges with same SrcBB and DestBB.
372 const BasicBlock *SrcBB;
373 const BasicBlock *DestBB;
374 uint64_t Weight;
375 bool InMST;
376 bool Removed;
377 bool IsCritical;
378 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
379 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
380 IsCritical(false) {}
381 // Return the information string of an edge.
382 const std::string infoString() const {
383 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
384 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
385 }
386};
387
388// This class stores the auxiliary information for each BB.
389struct BBInfo {
390 BBInfo *Group;
391 uint32_t Index;
392 uint32_t Rank;
393
394 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
395
396 // Return the information string of this object.
397 const std::string infoString() const {
398 return (Twine("Index=") + Twine(Index)).str();
399 }
400};
401
402// This class implements the CFG edges. Note the CFG can be a multi-graph.
403template <class Edge, class BBInfo> class FuncPGOInstrumentation {
404private:
405 Function &F;
406 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000407 void renameComdatFunction();
408 // A map that stores the Comdat group in function F.
409 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000410
411public:
Rong Xua3bbf962017-03-15 18:23:39 +0000412 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000413 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000414 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000415 std::string FuncName;
416 GlobalVariable *FuncNameVar;
417 // CFG hash value for this function.
418 uint64_t FunctionHash;
419
420 // The Minimum Spanning Tree of function CFG.
421 CFGMST<Edge, BBInfo> MST;
422
423 // Give an edge, find the BB that will be instrumented.
424 // Return nullptr if there is no BB to be instrumented.
425 BasicBlock *getInstrBB(Edge *E);
426
427 // Return the auxiliary BB information.
428 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
429
Rong Xua5b57452016-12-02 19:10:29 +0000430 // Return the auxiliary BB information if available.
431 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
432
Rong Xuf430ae42015-12-09 18:08:16 +0000433 // Dump edges and BB information.
434 void dumpInfo(std::string Str = "") const {
435 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000436 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000437 }
438
Rong Xu705f7772016-07-25 18:45:37 +0000439 FuncPGOInstrumentation(
440 Function &Func,
441 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
442 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
443 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000444 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Rong Xu60faea12017-03-16 21:15:48 +0000445 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000446
447 // This should be done before CFG hash computation.
448 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000449 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000450 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000451 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000452 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000453 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000454
Rong Xuf430ae42015-12-09 18:08:16 +0000455 FuncName = getPGOFuncName(F);
456 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000457 if (ComdatMembers.size())
458 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000459 DEBUG(dumpInfo("after CFGMST"));
460
461 NumOfPGOBB += MST.BBInfos.size();
462 for (auto &E : MST.AllEdges) {
463 if (E->Removed)
464 continue;
465 NumOfPGOEdge++;
466 if (!E->InMST)
467 NumOfPGOInstrument++;
468 }
469
470 if (CreateGlobalVar)
471 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000472 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000473
474 // Return the number of profile counters needed for the function.
475 unsigned getNumCounters() {
476 unsigned NumCounters = 0;
477 for (auto &E : this->MST.AllEdges) {
478 if (!E->InMST && !E->Removed)
479 NumCounters++;
480 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000481 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000482 }
Rong Xuf430ae42015-12-09 18:08:16 +0000483};
484
485// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
486// value of each BB in the CFG. The higher 32 bits record the number of edges.
487template <class Edge, class BBInfo>
488void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
489 std::vector<char> Indexes;
490 JamCRC JC;
491 for (auto &BB : F) {
492 const TerminatorInst *TI = BB.getTerminator();
493 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
494 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000495 auto BI = findBBInfo(Succ);
496 if (BI == nullptr)
497 continue;
498 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000499 for (int J = 0; J < 4; J++)
500 Indexes.push_back((char)(Index >> (J * 8)));
501 }
502 }
503 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000504 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000505 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000506 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
507}
508
509// Check if we can safely rename this Comdat function.
510static bool canRenameComdat(
511 Function &F,
512 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000513 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000514 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000515
516 // FIXME: Current only handle those Comdat groups that only containing one
517 // function and function aliases.
518 // (1) For a Comdat group containing multiple functions, we need to have a
519 // unique postfix based on the hashes for each function. There is a
520 // non-trivial code refactoring to do this efficiently.
521 // (2) Variables can not be renamed, so we can not rename Comdat function in a
522 // group including global vars.
523 Comdat *C = F.getComdat();
524 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
525 if (dyn_cast<GlobalAlias>(CM.second))
526 continue;
527 Function *FM = dyn_cast<Function>(CM.second);
528 if (FM != &F)
529 return false;
530 }
531 return true;
532}
533
534// Append the CFGHash to the Comdat function name.
535template <class Edge, class BBInfo>
536void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
537 if (!canRenameComdat(F, ComdatMembers))
538 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000539 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000540 std::string NewFuncName =
541 Twine(F.getName() + "." + Twine(FunctionHash)).str();
542 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000543 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000544 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
545 Comdat *NewComdat;
546 Module *M = F.getParent();
547 // For AvailableExternallyLinkage functions, change the linkage to
548 // LinkOnceODR and put them into comdat. This is because after renaming, there
549 // is no backup external copy available for the function.
550 if (!F.hasComdat()) {
551 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
552 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
553 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
554 F.setComdat(NewComdat);
555 return;
556 }
557
558 // This function belongs to a single function Comdat group.
559 Comdat *OrigComdat = F.getComdat();
560 std::string NewComdatName =
561 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
562 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
563 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
564
565 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
566 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
567 // For aliases, change the name directly.
568 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000569 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000570 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000571 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000572 continue;
573 }
574 // Must be a function.
575 Function *CF = dyn_cast<Function>(CM.second);
576 assert(CF);
577 CF->setComdat(NewComdat);
578 }
Rong Xuf430ae42015-12-09 18:08:16 +0000579}
580
581// Given a CFG E to be instrumented, find which BB to place the instrumented
582// code. The function will split the critical edge if necessary.
583template <class Edge, class BBInfo>
584BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
585 if (E->InMST || E->Removed)
586 return nullptr;
587
588 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
589 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
590 // For a fake edge, instrument the real BB.
591 if (SrcBB == nullptr)
592 return DestBB;
593 if (DestBB == nullptr)
594 return SrcBB;
595
596 // Instrument the SrcBB if it has a single successor,
597 // otherwise, the DestBB if this is not a critical edge.
598 TerminatorInst *TI = SrcBB->getTerminator();
599 if (TI->getNumSuccessors() <= 1)
600 return SrcBB;
601 if (!E->IsCritical)
602 return DestBB;
603
604 // For a critical edge, we have to split. Instrument the newly
605 // created BB.
606 NumOfPGOSplit++;
607 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
608 << getBBInfo(DestBB).Index << "\n");
609 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
610 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
611 assert(InstrBB && "Critical edge is not split");
612
613 E->Removed = true;
614 return InstrBB;
615}
616
Rong Xued9fec72016-01-21 18:11:44 +0000617// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000618// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000619static void instrumentOneFunc(
620 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
621 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000622 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
623 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000624 unsigned NumCounters = FuncInfo.getNumCounters();
625
Rong Xuf430ae42015-12-09 18:08:16 +0000626 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000627 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000628 for (auto &E : FuncInfo.MST.AllEdges) {
629 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
630 if (!InstrBB)
631 continue;
632
633 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
634 assert(Builder.GetInsertPoint() != InstrBB->end() &&
635 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000636 Builder.CreateCall(
637 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
638 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
639 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
640 Builder.getInt32(I++)});
641 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000642
643 // Now instrument select instructions:
644 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
645 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000646 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000647
648 if (DisableValueProfiling)
649 return;
650
651 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000652 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000653 CallSite CS(I);
654 Value *Callee = CS.getCalledValue();
655 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
656 << NumIndirectCallSites << "\n");
657 IRBuilder<> Builder(I);
658 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
659 "Cannot get the Instrumentation point");
660 Builder.CreateCall(
661 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
662 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
663 Builder.getInt64(FuncInfo.FunctionHash),
664 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000665 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000666 Builder.getInt32(NumIndirectCallSites++)});
667 }
668 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000669
670 // Now instrument memop intrinsic calls.
671 FuncInfo.MIVisitor.instrumentMemIntrinsics(
672 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000673}
674
675// This class represents a CFG edge in profile use compilation.
676struct PGOUseEdge : public PGOEdge {
677 bool CountValid;
678 uint64_t CountValue;
679 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
680 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
681
682 // Set edge count value
683 void setEdgeCount(uint64_t Value) {
684 CountValue = Value;
685 CountValid = true;
686 }
687
688 // Return the information string for this object.
689 const std::string infoString() const {
690 if (!CountValid)
691 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000692 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
693 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000694 }
695};
696
697typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
698
699// This class stores the auxiliary information for each BB.
700struct UseBBInfo : public BBInfo {
701 uint64_t CountValue;
702 bool CountValid;
703 int32_t UnknownCountInEdge;
704 int32_t UnknownCountOutEdge;
705 DirectEdges InEdges;
706 DirectEdges OutEdges;
707 UseBBInfo(unsigned IX)
708 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
709 UnknownCountOutEdge(0) {}
710 UseBBInfo(unsigned IX, uint64_t C)
711 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
712 UnknownCountOutEdge(0) {}
713
714 // Set the profile count value for this BB.
715 void setBBInfoCount(uint64_t Value) {
716 CountValue = Value;
717 CountValid = true;
718 }
719
720 // Return the information string of this object.
721 const std::string infoString() const {
722 if (!CountValid)
723 return BBInfo::infoString();
724 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
725 }
726};
727
728// Sum up the count values for all the edges.
729static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
730 uint64_t Total = 0;
731 for (auto &E : Edges) {
732 if (E->Removed)
733 continue;
734 Total += E->CountValue;
735 }
736 return Total;
737}
738
739class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000740public:
Rong Xu705f7772016-07-25 18:45:37 +0000741 PGOUseFunc(Function &Func, Module *Modu,
742 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
743 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000744 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000745 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000746 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000747
748 // Read counts for the instrumented BB from profile.
749 bool readCounters(IndexedInstrProfReader *PGOReader);
750
751 // Populate the counts for all BBs.
752 void populateCounters();
753
754 // Set the branch weights based on the count values.
755 void setBranchWeights();
756
Rong Xua3bbf962017-03-15 18:23:39 +0000757 // Annotate the value profile call sites all all value kind.
758 void annotateValueSites();
759
760 // Annotate the value profile call sites for one value kind.
761 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000762
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000763 // The hotness of the function from the profile count.
764 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
765
766 // Return the function hotness from the profile.
767 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
768
Rong Xu705f7772016-07-25 18:45:37 +0000769 // Return the function hash.
770 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000771 // Return the profile record for this function;
772 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
773
Xinliang David Li4ca17332016-09-18 18:34:07 +0000774 // Return the auxiliary BB information.
775 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
776 return FuncInfo.getBBInfo(BB);
777 }
778
Rong Xua5b57452016-12-02 19:10:29 +0000779 // Return the auxiliary BB information if available.
780 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
781 return FuncInfo.findBBInfo(BB);
782 }
783
Xinliang David Lid289e452017-01-27 19:06:25 +0000784 Function &getFunc() const { return F; }
785
Rong Xuf430ae42015-12-09 18:08:16 +0000786private:
787 Function &F;
788 Module *M;
789 // This member stores the shared information with class PGOGenFunc.
790 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
791
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000792 // The maximum count value in the profile. This is only used in PGO use
793 // compilation.
794 uint64_t ProgramMaxCount;
795
Rong Xu33308f92016-10-25 21:47:24 +0000796 // Position of counter that remains to be read.
797 uint32_t CountPosition;
798
799 // Total size of the profile count for this function.
800 uint32_t ProfileCountSize;
801
Rong Xu13b01dc2016-02-10 18:24:45 +0000802 // ProfileRecord for this function.
803 InstrProfRecord ProfileRecord;
804
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000805 // Function hotness info derived from profile.
806 FuncFreqAttr FreqAttr;
807
Rong Xuf430ae42015-12-09 18:08:16 +0000808 // Find the Instrumented BB and set the value.
809 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
810
811 // Set the edge counter value for the unknown edge -- there should be only
812 // one unknown edge.
813 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
814
815 // Return FuncName string;
816 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000817
818 // Set the hot/cold inline hints based on the count values.
819 // FIXME: This function should be removed once the functionality in
820 // the inliner is implemented.
821 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
822 if (ProgramMaxCount == 0)
823 return;
824 // Threshold of the hot functions.
825 const BranchProbability HotFunctionThreshold(1, 100);
826 // Threshold of the cold functions.
827 const BranchProbability ColdFunctionThreshold(2, 10000);
828 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
829 FreqAttr = FFA_Hot;
830 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
831 FreqAttr = FFA_Cold;
832 }
Rong Xuf430ae42015-12-09 18:08:16 +0000833};
834
835// Visit all the edges and assign the count value for the instrumented
836// edges and the BB.
837void PGOUseFunc::setInstrumentedCounts(
838 const std::vector<uint64_t> &CountFromProfile) {
839
Xinliang David Lid1197612016-08-01 20:25:06 +0000840 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000841 // Use a worklist as we will update the vector during the iteration.
842 std::vector<PGOUseEdge *> WorkList;
843 for (auto &E : FuncInfo.MST.AllEdges)
844 WorkList.push_back(E.get());
845
846 uint32_t I = 0;
847 for (auto &E : WorkList) {
848 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
849 if (!InstrBB)
850 continue;
851 uint64_t CountValue = CountFromProfile[I++];
852 if (!E->Removed) {
853 getBBInfo(InstrBB).setBBInfoCount(CountValue);
854 E->setEdgeCount(CountValue);
855 continue;
856 }
857
858 // Need to add two new edges.
859 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
860 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
861 // Add new edge of SrcBB->InstrBB.
862 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
863 NewEdge.setEdgeCount(CountValue);
864 // Add new edge of InstrBB->DestBB.
865 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
866 NewEdge1.setEdgeCount(CountValue);
867 NewEdge1.InMST = true;
868 getBBInfo(InstrBB).setBBInfoCount(CountValue);
869 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000870 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000871 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000872}
873
874// Set the count value for the unknown edge. There should be one and only one
875// unknown edge in Edges vector.
876void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
877 for (auto &E : Edges) {
878 if (E->CountValid)
879 continue;
880 E->setEdgeCount(Value);
881
882 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
883 getBBInfo(E->DestBB).UnknownCountInEdge--;
884 return;
885 }
886 llvm_unreachable("Cannot find the unknown count edge");
887}
888
889// Read the profile from ProfileFileName and assign the value to the
890// instrumented BB and the edges. This function also updates ProgramMaxCount.
891// Return true if the profile are successfully read, and false on errors.
892bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
893 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000894 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000895 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000896 if (Error E = Result.takeError()) {
897 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
898 auto Err = IPE.get();
899 bool SkipWarning = false;
900 if (Err == instrprof_error::unknown_function) {
901 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000902 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000903 } else if (Err == instrprof_error::hash_mismatch ||
904 Err == instrprof_error::malformed) {
905 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000906 SkipWarning =
907 NoPGOWarnMismatch ||
908 (NoPGOWarnMismatchComdat &&
909 (F.hasComdat() ||
910 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000911 }
Rong Xuf430ae42015-12-09 18:08:16 +0000912
Vedant Kumar9152fd12016-05-19 03:54:45 +0000913 if (SkipWarning)
914 return;
915
916 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
917 Ctx.diagnose(
918 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
919 });
Rong Xuf430ae42015-12-09 18:08:16 +0000920 return false;
921 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000922 ProfileRecord = std::move(Result.get());
923 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000924
925 NumOfPGOFunc++;
926 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
927 uint64_t ValueSum = 0;
928 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
929 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
930 ValueSum += CountFromProfile[I];
931 }
932
933 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
934
935 getBBInfo(nullptr).UnknownCountOutEdge = 2;
936 getBBInfo(nullptr).UnknownCountInEdge = 2;
937
938 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000939 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000940 return true;
941}
942
943// Populate the counters from instrumented BBs to all BBs.
944// In the end of this operation, all BBs should have a valid count value.
945void PGOUseFunc::populateCounters() {
946 // First set up Count variable for all BBs.
947 for (auto &E : FuncInfo.MST.AllEdges) {
948 if (E->Removed)
949 continue;
950
951 const BasicBlock *SrcBB = E->SrcBB;
952 const BasicBlock *DestBB = E->DestBB;
953 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
954 UseBBInfo &DestInfo = getBBInfo(DestBB);
955 SrcInfo.OutEdges.push_back(E.get());
956 DestInfo.InEdges.push_back(E.get());
957 SrcInfo.UnknownCountOutEdge++;
958 DestInfo.UnknownCountInEdge++;
959
960 if (!E->CountValid)
961 continue;
962 DestInfo.UnknownCountInEdge--;
963 SrcInfo.UnknownCountOutEdge--;
964 }
965
966 bool Changes = true;
967 unsigned NumPasses = 0;
968 while (Changes) {
969 NumPasses++;
970 Changes = false;
971
972 // For efficient traversal, it's better to start from the end as most
973 // of the instrumented edges are at the end.
974 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000975 UseBBInfo *Count = findBBInfo(&BB);
976 if (Count == nullptr)
977 continue;
978 if (!Count->CountValid) {
979 if (Count->UnknownCountOutEdge == 0) {
980 Count->CountValue = sumEdgeCount(Count->OutEdges);
981 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000982 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000983 } else if (Count->UnknownCountInEdge == 0) {
984 Count->CountValue = sumEdgeCount(Count->InEdges);
985 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000986 Changes = true;
987 }
988 }
Rong Xua5b57452016-12-02 19:10:29 +0000989 if (Count->CountValid) {
990 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000991 uint64_t Total = 0;
992 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
993 // If the one of the successor block can early terminate (no-return),
994 // we can end up with situation where out edge sum count is larger as
995 // the source BB's count is collected by a post-dominated block.
996 if (Count->CountValue > OutSum)
997 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000998 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000999 Changes = true;
1000 }
Rong Xua5b57452016-12-02 19:10:29 +00001001 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001002 uint64_t Total = 0;
1003 uint64_t InSum = sumEdgeCount(Count->InEdges);
1004 if (Count->CountValue > InSum)
1005 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001006 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001007 Changes = true;
1008 }
1009 }
1010 }
1011 }
1012
1013 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001014#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001015 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001016 for (auto &BB : F) {
1017 auto BI = findBBInfo(&BB);
1018 if (BI == nullptr)
1019 continue;
1020 assert(BI->CountValid && "BB count is not valid");
1021 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001022#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001023 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001024 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001025 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001026 for (auto &BB : F) {
1027 auto BI = findBBInfo(&BB);
1028 if (BI == nullptr)
1029 continue;
1030 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1031 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001032 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001033
Rong Xu33308f92016-10-25 21:47:24 +00001034 // Now annotate select instructions
1035 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1036 assert(CountPosition == ProfileCountSize);
1037
Rong Xuf430ae42015-12-09 18:08:16 +00001038 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1039}
1040
1041// Assign the scaled count values to the BB with multiple out edges.
1042void PGOUseFunc::setBranchWeights() {
1043 // Generate MD_prof metadata for every branch instruction.
1044 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001045 for (auto &BB : F) {
1046 TerminatorInst *TI = BB.getTerminator();
1047 if (TI->getNumSuccessors() < 2)
1048 continue;
1049 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1050 continue;
1051 if (getBBInfo(&BB).CountValue == 0)
1052 continue;
1053
1054 // We have a non-zero Branch BB.
1055 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1056 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001057 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001058 uint64_t MaxCount = 0;
1059 for (unsigned s = 0; s < Size; s++) {
1060 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1061 const BasicBlock *SrcBB = E->SrcBB;
1062 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001063 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001064 continue;
1065 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1066 uint64_t EdgeCount = E->CountValue;
1067 if (EdgeCount > MaxCount)
1068 MaxCount = EdgeCount;
1069 EdgeCounts[SuccNum] = EdgeCount;
1070 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001071 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001072 }
1073}
Rong Xu13b01dc2016-02-10 18:24:45 +00001074
Xinliang David Li4ca17332016-09-18 18:34:07 +00001075void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1076 Module *M = F.getParent();
1077 IRBuilder<> Builder(&SI);
1078 Type *Int64Ty = Builder.getInt64Ty();
1079 Type *I8PtrTy = Builder.getInt8PtrTy();
1080 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1081 Builder.CreateCall(
1082 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1083 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001084 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1085 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001086 ++(*CurCtrIdx);
1087}
1088
1089void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1090 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1091 assert(*CurCtrIdx < CountFromProfile.size() &&
1092 "Out of bound access of counters");
1093 uint64_t SCounts[2];
1094 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1095 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001096 uint64_t TotalCount = 0;
1097 auto BI = UseFunc->findBBInfo(SI.getParent());
1098 if (BI != nullptr)
1099 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001100 // False Count
1101 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1102 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001103 if (MaxCount)
1104 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001105}
1106
1107void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1108 if (!PGOInstrSelect)
1109 return;
1110 // FIXME: do not handle this yet.
1111 if (SI.getCondition()->getType()->isVectorTy())
1112 return;
1113
Xinliang David Li4ca17332016-09-18 18:34:07 +00001114 switch (Mode) {
1115 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001116 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001117 return;
1118 case VM_instrument:
1119 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001120 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001121 case VM_annotate:
1122 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001123 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001124 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001125
1126 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001127}
1128
Rong Xu60faea12017-03-16 21:15:48 +00001129void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1130 Module *M = F.getParent();
1131 IRBuilder<> Builder(&MI);
1132 Type *Int64Ty = Builder.getInt64Ty();
1133 Type *I8PtrTy = Builder.getInt8PtrTy();
1134 Value *Length = MI.getLength();
1135 assert(!dyn_cast<ConstantInt>(Length));
1136 Builder.CreateCall(
1137 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1138 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1139 Builder.getInt64(FuncHash), Builder.CreatePtrToInt(Length, Int64Ty),
1140 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1141 ++CurCtrId;
1142}
1143
1144void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1145 if (!PGOInstrMemOP)
1146 return;
1147 Value *Length = MI.getLength();
1148 // Not instrument constant length calls.
1149 if (dyn_cast<ConstantInt>(Length))
1150 return;
1151
1152 switch (Mode) {
1153 case VM_counting:
1154 NMemIs++;
1155 return;
1156 case VM_instrument:
1157 instrumentOneMemIntrinsic(MI);
1158 return;
1159 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001160 Candidates.push_back(&MI);
1161 return;
Rong Xu60faea12017-03-16 21:15:48 +00001162 }
1163 llvm_unreachable("Unknown visiting mode");
1164}
1165
Rong Xua3bbf962017-03-15 18:23:39 +00001166// Traverse all valuesites and annotate the instructions for all value kind.
1167void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001168 if (DisableValueProfiling)
1169 return;
1170
Rong Xu8e8fe852016-04-01 16:43:30 +00001171 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001172 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001173
Rong Xua3bbf962017-03-15 18:23:39 +00001174 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001175 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001176}
1177
1178// Annotate the instructions for a specific value kind.
1179void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1180 unsigned ValueSiteIndex = 0;
1181 auto &ValueSites = FuncInfo.ValueSites[Kind];
1182 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1183 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001184 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001185 Ctx.diagnose(DiagnosticInfoPGOProfile(
1186 M->getName().data(),
1187 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1188 " in " + F.getName().str(),
1189 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001190 return;
1191 }
1192
Rong Xua3bbf962017-03-15 18:23:39 +00001193 for (auto &I : ValueSites) {
1194 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1195 << "): Index = " << ValueSiteIndex << " out of "
1196 << NumValueSites << "\n");
1197 annotateValueSite(*M, *I, ProfileRecord,
1198 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001199 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1200 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001201 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001202 }
1203}
Rong Xuf430ae42015-12-09 18:08:16 +00001204} // end anonymous namespace
1205
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001206// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001207// aware this is an ir_level profile so it can set the version flag.
1208static void createIRLevelProfileFlagVariable(Module &M) {
1209 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1210 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001211 auto IRLevelVersionVariable = new GlobalVariable(
1212 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1213 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001214 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001215 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1216 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001217 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001218 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001219 else
Rong Xu9e926e82016-02-29 19:16:04 +00001220 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001221 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001222}
1223
Rong Xu705f7772016-07-25 18:45:37 +00001224// Collect the set of members for each Comdat in module M and store
1225// in ComdatMembers.
1226static void collectComdatMembers(
1227 Module &M,
1228 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1229 if (!DoComdatRenaming)
1230 return;
1231 for (Function &F : M)
1232 if (Comdat *C = F.getComdat())
1233 ComdatMembers.insert(std::make_pair(C, &F));
1234 for (GlobalVariable &GV : M.globals())
1235 if (Comdat *C = GV.getComdat())
1236 ComdatMembers.insert(std::make_pair(C, &GV));
1237 for (GlobalAlias &GA : M.aliases())
1238 if (Comdat *C = GA.getComdat())
1239 ComdatMembers.insert(std::make_pair(C, &GA));
1240}
1241
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001242static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001243 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1244 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001245 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001246 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1247 collectComdatMembers(M, ComdatMembers);
1248
Rong Xuf430ae42015-12-09 18:08:16 +00001249 for (auto &F : M) {
1250 if (F.isDeclaration())
1251 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001252 auto *BPI = LookupBPI(F);
1253 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001254 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001255 }
1256 return true;
1257}
1258
Xinliang David Li8aebf442016-05-06 05:49:19 +00001259bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001260 if (skipModule(M))
1261 return false;
1262
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001263 auto LookupBPI = [this](Function &F) {
1264 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001265 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001266 auto LookupBFI = [this](Function &F) {
1267 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001268 };
1269 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1270}
1271
Xinliang David Li8aebf442016-05-06 05:49:19 +00001272PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001273 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001274
1275 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001276 auto LookupBPI = [&FAM](Function &F) {
1277 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001278 };
1279
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001280 auto LookupBFI = [&FAM](Function &F) {
1281 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001282 };
1283
1284 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1285 return PreservedAnalyses::all();
1286
1287 return PreservedAnalyses::none();
1288}
1289
Xinliang David Lida195582016-05-10 21:59:52 +00001290static bool annotateAllFunctions(
1291 Module &M, StringRef ProfileFileName,
1292 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001293 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001294 DEBUG(dbgs() << "Read in profile counters: ");
1295 auto &Ctx = M.getContext();
1296 // Read the counter array from file.
1297 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001298 if (Error E = ReaderOrErr.takeError()) {
1299 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1300 Ctx.diagnose(
1301 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1302 });
Rong Xuf430ae42015-12-09 18:08:16 +00001303 return false;
1304 }
1305
Xinliang David Lida195582016-05-10 21:59:52 +00001306 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1307 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001308 if (!PGOReader) {
1309 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001310 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001311 return false;
1312 }
Rong Xu33c76c02016-02-10 17:18:30 +00001313 // TODO: might need to change the warning once the clang option is finalized.
1314 if (!PGOReader->isIRLevelProfile()) {
1315 Ctx.diagnose(DiagnosticInfoPGOProfile(
1316 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1317 return false;
1318 }
1319
Rong Xu705f7772016-07-25 18:45:37 +00001320 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1321 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001322 std::vector<Function *> HotFunctions;
1323 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001324 for (auto &F : M) {
1325 if (F.isDeclaration())
1326 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001327 auto *BPI = LookupBPI(F);
1328 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001329 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001330 if (!Func.readCounters(PGOReader.get()))
1331 continue;
1332 Func.populateCounters();
1333 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001334 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001335 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1336 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001337 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001338 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1339 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001340 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1341 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001342 LoopInfo LI{DominatorTree(F)};
1343 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1344 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1345 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1346 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1347
1348 NewBFI->view();
1349 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001350 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1351 F.getName().equals(ViewBlockFreqFuncName))) {
1352 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001353 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1354 else
1355 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1356 }
Rong Xuf430ae42015-12-09 18:08:16 +00001357 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001358 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001359 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001360 // We have to apply these attributes at the end because their presence
1361 // can affect the BranchProbabilityInfo of any callers, resulting in an
1362 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001363 for (auto &F : HotFunctions) {
1364 F->addFnAttr(llvm::Attribute::InlineHint);
1365 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1366 << "\n");
1367 }
1368 for (auto &F : ColdFunctions) {
1369 F->addFnAttr(llvm::Attribute::Cold);
1370 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1371 }
Rong Xuf430ae42015-12-09 18:08:16 +00001372 return true;
1373}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001374
Xinliang David Lida195582016-05-10 21:59:52 +00001375PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001376 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001377 if (!PGOTestProfileFile.empty())
1378 ProfileFileName = PGOTestProfileFile;
1379}
1380
1381PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001382 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001383
1384 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1385 auto LookupBPI = [&FAM](Function &F) {
1386 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1387 };
1388
1389 auto LookupBFI = [&FAM](Function &F) {
1390 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1391 };
1392
1393 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1394 return PreservedAnalyses::all();
1395
1396 return PreservedAnalyses::none();
1397}
1398
Xinliang David Lid55827f2016-05-07 05:39:12 +00001399bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1400 if (skipModule(M))
1401 return false;
1402
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001403 auto LookupBPI = [this](Function &F) {
1404 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001405 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001406 auto LookupBFI = [this](Function &F) {
1407 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001408 };
1409
Xinliang David Lida195582016-05-10 21:59:52 +00001410 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001411}
Xinliang David Lid289e452017-01-27 19:06:25 +00001412
1413namespace llvm {
Rong Xu48596b62017-04-04 16:42:20 +00001414void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1415 uint64_t MaxCount) {
1416 MDBuilder MDB(M->getContext());
1417 assert(MaxCount > 0 && "Bad max count");
1418 uint64_t Scale = calculateCountScale(MaxCount);
1419 SmallVector<unsigned, 4> Weights;
1420 for (const auto &ECI : EdgeCounts)
1421 Weights.push_back(scaleBranchCount(ECI, Scale));
1422
1423 DEBUG(dbgs() << "Weight is: ";
1424 for (const auto &W : Weights) { dbgs() << W << " "; }
1425 dbgs() << "\n";);
1426 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1427}
1428
Xinliang David Lid289e452017-01-27 19:06:25 +00001429template <> struct GraphTraits<PGOUseFunc *> {
1430 typedef const BasicBlock *NodeRef;
1431 typedef succ_const_iterator ChildIteratorType;
1432 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1433
1434 static NodeRef getEntryNode(const PGOUseFunc *G) {
1435 return &G->getFunc().front();
1436 }
1437 static ChildIteratorType child_begin(const NodeRef N) {
1438 return succ_begin(N);
1439 }
1440 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1441 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1442 return nodes_iterator(G->getFunc().begin());
1443 }
1444 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1445 return nodes_iterator(G->getFunc().end());
1446 }
1447};
1448
Xinliang David Li6144a592017-02-03 21:57:51 +00001449static std::string getSimpleNodeName(const BasicBlock *Node) {
1450 if (!Node->getName().empty())
1451 return Node->getName();
1452
1453 std::string SimpleNodeName;
1454 raw_string_ostream OS(SimpleNodeName);
1455 Node->printAsOperand(OS, false);
1456 return OS.str();
1457}
1458
Xinliang David Lid289e452017-01-27 19:06:25 +00001459template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1460 explicit DOTGraphTraits(bool isSimple = false)
1461 : DefaultDOTGraphTraits(isSimple) {}
1462
1463 static std::string getGraphName(const PGOUseFunc *G) {
1464 return G->getFunc().getName();
1465 }
1466
1467 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1468 std::string Result;
1469 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001470
1471 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001472 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001473 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001474 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001475 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001476 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001477 OS << "Unknown\\l";
1478
1479 if (!PGOInstrSelect)
1480 return Result;
1481
1482 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1483 auto *I = &*BI;
1484 if (!isa<SelectInst>(I))
1485 continue;
1486 // Display scaled counts for SELECT instruction:
1487 OS << "SELECT : { T = ";
1488 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001489 bool HasProf = I->extractProfMetadata(TC, FC);
1490 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001491 OS << "Unknown, F = Unknown }\\l";
1492 else
1493 OS << TC << ", F = " << FC << " }\\l";
1494 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001495 return Result;
1496 }
1497};
Rong Xu0a2a1312017-03-09 19:08:55 +00001498} // namespace llvm