blob: 087ba4d8040409f2409e8c5abddf2c7c121a5a45 [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"
Davide Italiano0c8d26c2017-07-20 20:43:05 +000062#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Rong Xued9fec72016-01-21 18:11:44 +000063#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000065#include "llvm/IR/Dominators.h"
Rong Xu705f7772016-07-25 18:45:37 +000066#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000067#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/InstIterator.h"
69#include "llvm/IR/Instructions.h"
70#include "llvm/IR/IntrinsicInst.h"
71#include "llvm/IR/MDBuilder.h"
72#include "llvm/IR/Module.h"
73#include "llvm/Pass.h"
74#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000075#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000076#include "llvm/Support/BranchProbability.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000077#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +000078#include "llvm/Support/Debug.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000079#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +000080#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000081#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000082#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000083#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000084#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000085#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000086#include <utility>
87#include <vector>
88
89using namespace llvm;
90
91#define DEBUG_TYPE "pgo-instrumentation"
92
93STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000094STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +000095STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000096STATISTIC(NumOfPGOEdge, "Number of edges.");
97STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
98STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
99STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
100STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
101STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000102STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000103
104// Command line option to specify the file to read profile from. This is
105// mainly used for testing.
106static cl::opt<std::string>
107 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
108 cl::value_desc("filename"),
109 cl::desc("Specify the path of profile data file. This is"
110 "mainly for test purpose."));
111
Rong Xuecdc98f2016-03-04 22:08:44 +0000112// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000113// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000114static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
115 cl::Hidden,
116 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000117
Rong Xuecdc98f2016-03-04 22:08:44 +0000118// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000119// the metadata for a single indirect call callsite.
120static cl::opt<unsigned> MaxNumAnnotations(
121 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
122 cl::desc("Max number of annotations for a single indirect "
123 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000124
Rong Xue60343d2017-03-17 18:07:26 +0000125// Command line option to set the maximum number of value annotations
126// to write to the metadata for a single memop intrinsic.
127static cl::opt<unsigned> MaxNumMemOPAnnotations(
128 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
129 cl::desc("Max number of preicise value annotations for a single memop"
130 "intrinsic"));
131
Rong Xu705f7772016-07-25 18:45:37 +0000132// Command line option to control appending FunctionHash to the name of a COMDAT
133// function. This is to avoid the hash mismatch caused by the preinliner.
134static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000135 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000136 cl::desc("Append function hash to the name of COMDAT function to avoid "
137 "function hash mismatch due to the preinliner"));
138
Rong Xu0698de92016-05-13 17:26:06 +0000139// Command line option to enable/disable the warning about missing profile
140// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000141static cl::opt<bool>
142 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
143 cl::desc("Use this option to turn on/off "
144 "warnings about missing profile data for "
145 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000146
147// Command line option to enable/disable the warning about a hash mismatch in
148// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000149static cl::opt<bool>
150 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
151 cl::desc("Use this option to turn off/on "
152 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000153
Rong Xu20f5df12017-01-11 20:19:41 +0000154// Command line option to enable/disable the warning about a hash mismatch in
155// the profile data for Comdat functions, which often turns out to be false
156// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000157static cl::opt<bool>
158 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
159 cl::Hidden,
160 cl::desc("The option is used to turn on/off "
161 "warnings about hash mismatch for comdat "
162 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000163
Xinliang David Li4ca17332016-09-18 18:34:07 +0000164// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000165static cl::opt<bool>
166 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
167 cl::desc("Use this option to turn on/off SELECT "
168 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000169
Xinliang David Lid289e452017-01-27 19:06:25 +0000170// Command line option to turn on CFG dot dump of raw profile counts
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000171static cl::opt<bool>
172 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
173 cl::desc("A boolean option to show CFG dag "
174 "with raw profile counts from "
175 "profile data. See also option "
176 "-pgo-view-counts. To limit graph "
177 "display to only one function, use "
178 "filtering option -view-bfi-func-name."));
Xinliang David Lid289e452017-01-27 19:06:25 +0000179
Rong Xu8e06e802017-03-17 20:51:44 +0000180// Command line option to enable/disable memop intrinsic call.size profiling.
181static cl::opt<bool>
182 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
183 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000184 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000185
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000186// Emit branch probability as optimization remarks.
187static cl::opt<bool>
188 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
189 cl::desc("When this option is on, the annotated "
190 "branch probability will be emitted as "
191 " optimization remarks: -Rpass-analysis="
192 "pgo-instr-use"));
193
Xinliang David Licb253ce2017-01-23 18:58:24 +0000194// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000195// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Xinliang David Licb253ce2017-01-23 18:58:24 +0000196extern cl::opt<bool> PGOViewCounts;
197
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000198// Command line option to specify the name of the function for CFG dump
199// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
200extern cl::opt<std::string> ViewBlockFreqFuncName;
201
Rong Xuf430ae42015-12-09 18:08:16 +0000202namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000203
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000204// Return a string describing the branch condition that can be
205// used in static branch probability heuristics:
206std::string getBranchCondString(Instruction *TI) {
207 BranchInst *BI = dyn_cast<BranchInst>(TI);
208 if (!BI || !BI->isConditional())
209 return std::string();
210
211 Value *Cond = BI->getCondition();
212 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
213 if (!CI)
214 return std::string();
215
216 std::string result;
217 raw_string_ostream OS(result);
218 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
219 CI->getOperand(0)->getType()->print(OS, true);
220
221 Value *RHS = CI->getOperand(1);
222 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
223 if (CV) {
224 if (CV->isZero())
225 OS << "_Zero";
226 else if (CV->isOne())
227 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000228 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000229 OS << "_MinusOne";
230 else
231 OS << "_Const";
232 }
233 OS.flush();
234 return result;
235}
236
Xinliang David Li4ca17332016-09-18 18:34:07 +0000237/// The select instruction visitor plays three roles specified
238/// by the mode. In \c VM_counting mode, it simply counts the number of
239/// select instructions. In \c VM_instrument mode, it inserts code to count
240/// the number times TrueValue of select is taken. In \c VM_annotate mode,
241/// it reads the profile data and annotate the select instruction with metadata.
242enum VisitMode { VM_counting, VM_instrument, VM_annotate };
243class PGOUseFunc;
244
245/// Instruction Visitor class to visit select instructions.
246struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
247 Function &F;
248 unsigned NSIs = 0; // Number of select instructions instrumented.
249 VisitMode Mode = VM_counting; // Visiting mode.
250 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
251 unsigned TotalNumCtrs = 0; // Total number of counters
252 GlobalVariable *FuncNameVar = nullptr;
253 uint64_t FuncHash = 0;
254 PGOUseFunc *UseFunc = nullptr;
255
256 SelectInstVisitor(Function &Func) : F(Func) {}
257
258 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000259 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000260 Mode = VM_counting;
261 visit(Func);
262 }
263 // Visit the IR stream and instrument all select instructions. \p
264 // Ind is a pointer to the counter index variable; \p TotalNC
265 // is the total number of counters; \p FNV is the pointer to the
266 // PGO function name var; \p FHash is the function hash.
267 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
268 GlobalVariable *FNV, uint64_t FHash) {
269 Mode = VM_instrument;
270 CurCtrIdx = Ind;
271 TotalNumCtrs = TotalNC;
272 FuncHash = FHash;
273 FuncNameVar = FNV;
274 visit(Func);
275 }
276
277 // Visit the IR stream and annotate all select instructions.
278 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
279 Mode = VM_annotate;
280 UseFunc = UF;
281 CurCtrIdx = Ind;
282 visit(Func);
283 }
284
285 void instrumentOneSelectInst(SelectInst &SI);
286 void annotateOneSelectInst(SelectInst &SI);
287 // Visit \p SI instruction and perform tasks according to visit mode.
288 void visitSelectInst(SelectInst &SI);
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000289 // Return the number of select instructions. This needs be called after
290 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000291 unsigned getNumOfSelectInsts() const { return NSIs; }
292};
293
Rong Xu60faea12017-03-16 21:15:48 +0000294/// Instruction Visitor class to visit memory intrinsic calls.
295struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
296 Function &F;
297 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
298 VisitMode Mode = VM_counting; // Visiting mode.
299 unsigned CurCtrId = 0; // Current counter index.
300 unsigned TotalNumCtrs = 0; // Total number of counters
301 GlobalVariable *FuncNameVar = nullptr;
302 uint64_t FuncHash = 0;
303 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000304 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000305
306 MemIntrinsicVisitor(Function &Func) : F(Func) {}
307
308 void countMemIntrinsics(Function &Func) {
309 NMemIs = 0;
310 Mode = VM_counting;
311 visit(Func);
312 }
Rong Xue60343d2017-03-17 18:07:26 +0000313
Rong Xu60faea12017-03-16 21:15:48 +0000314 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
315 GlobalVariable *FNV, uint64_t FHash) {
316 Mode = VM_instrument;
317 TotalNumCtrs = TotalNC;
318 FuncHash = FHash;
319 FuncNameVar = FNV;
320 visit(Func);
321 }
322
Rong Xue60343d2017-03-17 18:07:26 +0000323 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
324 Candidates.clear();
325 Mode = VM_annotate;
326 visit(Func);
327 return Candidates;
328 }
329
Rong Xu60faea12017-03-16 21:15:48 +0000330 // Visit the IR stream and annotate all mem intrinsic call instructions.
331 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
332 // Visit \p MI instruction and perform tasks according to visit mode.
333 void visitMemIntrinsic(MemIntrinsic &SI);
334 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
335};
336
Xinliang David Li8aebf442016-05-06 05:49:19 +0000337class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000338public:
339 static char ID;
340
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000341 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000342 initializePGOInstrumentationGenLegacyPassPass(
343 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000344 }
345
Mehdi Amini117296c2016-10-01 02:56:57 +0000346 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000347
348private:
349 bool runOnModule(Module &M) override;
350
351 void getAnalysisUsage(AnalysisUsage &AU) const override {
352 AU.addRequired<BlockFrequencyInfoWrapperPass>();
353 }
354};
355
Xinliang David Lid55827f2016-05-07 05:39:12 +0000356class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000357public:
358 static char ID;
359
360 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000361 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000362 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000363 if (!PGOTestProfileFile.empty())
364 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000365 initializePGOInstrumentationUseLegacyPassPass(
366 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000367 }
368
Mehdi Amini117296c2016-10-01 02:56:57 +0000369 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000370
371private:
372 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000373
Xinliang David Lida195582016-05-10 21:59:52 +0000374 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000375 void getAnalysisUsage(AnalysisUsage &AU) const override {
376 AU.addRequired<BlockFrequencyInfoWrapperPass>();
377 }
378};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000379
Rong Xuf430ae42015-12-09 18:08:16 +0000380} // end anonymous namespace
381
Xinliang David Li8aebf442016-05-06 05:49:19 +0000382char PGOInstrumentationGenLegacyPass::ID = 0;
383INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000384 "PGO instrumentation.", false, false)
385INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000387INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000388 "PGO instrumentation.", false, false)
389
Xinliang David Li8aebf442016-05-06 05:49:19 +0000390ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
391 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000392}
393
Xinliang David Lid55827f2016-05-07 05:39:12 +0000394char PGOInstrumentationUseLegacyPass::ID = 0;
395INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000396 "Read PGO instrumentation profile.", false, false)
397INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
398INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000399INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000400 "Read PGO instrumentation profile.", false, false)
401
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
403 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000404}
405
406namespace {
407/// \brief An MST based instrumentation for PGO
408///
409/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
410/// in the function level.
411struct PGOEdge {
412 // This class implements the CFG edges. Note the CFG can be a multi-graph.
413 // So there might be multiple edges with same SrcBB and DestBB.
414 const BasicBlock *SrcBB;
415 const BasicBlock *DestBB;
416 uint64_t Weight;
417 bool InMST;
418 bool Removed;
419 bool IsCritical;
420 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
421 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
422 IsCritical(false) {}
423 // Return the information string of an edge.
424 const std::string infoString() const {
425 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
426 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
427 }
428};
429
430// This class stores the auxiliary information for each BB.
431struct BBInfo {
432 BBInfo *Group;
433 uint32_t Index;
434 uint32_t Rank;
435
436 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
437
438 // Return the information string of this object.
439 const std::string infoString() const {
440 return (Twine("Index=") + Twine(Index)).str();
441 }
442};
443
444// This class implements the CFG edges. Note the CFG can be a multi-graph.
445template <class Edge, class BBInfo> class FuncPGOInstrumentation {
446private:
447 Function &F;
448 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000449 void renameComdatFunction();
450 // A map that stores the Comdat group in function F.
451 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000452
453public:
Rong Xua3bbf962017-03-15 18:23:39 +0000454 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000455 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000456 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000457 std::string FuncName;
458 GlobalVariable *FuncNameVar;
459 // CFG hash value for this function.
460 uint64_t FunctionHash;
461
462 // The Minimum Spanning Tree of function CFG.
463 CFGMST<Edge, BBInfo> MST;
464
465 // Give an edge, find the BB that will be instrumented.
466 // Return nullptr if there is no BB to be instrumented.
467 BasicBlock *getInstrBB(Edge *E);
468
469 // Return the auxiliary BB information.
470 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
471
Rong Xua5b57452016-12-02 19:10:29 +0000472 // Return the auxiliary BB information if available.
473 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
474
Rong Xuf430ae42015-12-09 18:08:16 +0000475 // Dump edges and BB information.
476 void dumpInfo(std::string Str = "") const {
477 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000478 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000479 }
480
Rong Xu705f7772016-07-25 18:45:37 +0000481 FuncPGOInstrumentation(
482 Function &Func,
483 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
484 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
485 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000486 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Rong Xu60faea12017-03-16 21:15:48 +0000487 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000488
489 // This should be done before CFG hash computation.
490 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000491 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000492 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000493 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000494 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000495 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000496
Rong Xuf430ae42015-12-09 18:08:16 +0000497 FuncName = getPGOFuncName(F);
498 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000499 if (ComdatMembers.size())
500 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000501 DEBUG(dumpInfo("after CFGMST"));
502
503 NumOfPGOBB += MST.BBInfos.size();
504 for (auto &E : MST.AllEdges) {
505 if (E->Removed)
506 continue;
507 NumOfPGOEdge++;
508 if (!E->InMST)
509 NumOfPGOInstrument++;
510 }
511
512 if (CreateGlobalVar)
513 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000514 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000515
516 // Return the number of profile counters needed for the function.
517 unsigned getNumCounters() {
518 unsigned NumCounters = 0;
519 for (auto &E : this->MST.AllEdges) {
520 if (!E->InMST && !E->Removed)
521 NumCounters++;
522 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000523 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000524 }
Rong Xuf430ae42015-12-09 18:08:16 +0000525};
526
527// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
528// value of each BB in the CFG. The higher 32 bits record the number of edges.
529template <class Edge, class BBInfo>
530void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
531 std::vector<char> Indexes;
532 JamCRC JC;
533 for (auto &BB : F) {
534 const TerminatorInst *TI = BB.getTerminator();
535 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
536 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000537 auto BI = findBBInfo(Succ);
538 if (BI == nullptr)
539 continue;
540 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000541 for (int J = 0; J < 4; J++)
542 Indexes.push_back((char)(Index >> (J * 8)));
543 }
544 }
545 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000546 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000547 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000548 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
549}
550
551// Check if we can safely rename this Comdat function.
552static bool canRenameComdat(
553 Function &F,
554 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000555 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000556 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000557
558 // FIXME: Current only handle those Comdat groups that only containing one
559 // function and function aliases.
560 // (1) For a Comdat group containing multiple functions, we need to have a
561 // unique postfix based on the hashes for each function. There is a
562 // non-trivial code refactoring to do this efficiently.
563 // (2) Variables can not be renamed, so we can not rename Comdat function in a
564 // group including global vars.
565 Comdat *C = F.getComdat();
566 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
567 if (dyn_cast<GlobalAlias>(CM.second))
568 continue;
569 Function *FM = dyn_cast<Function>(CM.second);
570 if (FM != &F)
571 return false;
572 }
573 return true;
574}
575
576// Append the CFGHash to the Comdat function name.
577template <class Edge, class BBInfo>
578void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
579 if (!canRenameComdat(F, ComdatMembers))
580 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000581 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000582 std::string NewFuncName =
583 Twine(F.getName() + "." + Twine(FunctionHash)).str();
584 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000585 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000586 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
587 Comdat *NewComdat;
588 Module *M = F.getParent();
589 // For AvailableExternallyLinkage functions, change the linkage to
590 // LinkOnceODR and put them into comdat. This is because after renaming, there
591 // is no backup external copy available for the function.
592 if (!F.hasComdat()) {
593 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
594 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
595 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
596 F.setComdat(NewComdat);
597 return;
598 }
599
600 // This function belongs to a single function Comdat group.
601 Comdat *OrigComdat = F.getComdat();
602 std::string NewComdatName =
603 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
604 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
605 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
606
607 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
608 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
609 // For aliases, change the name directly.
610 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000611 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000612 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000613 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000614 continue;
615 }
616 // Must be a function.
617 Function *CF = dyn_cast<Function>(CM.second);
618 assert(CF);
619 CF->setComdat(NewComdat);
620 }
Rong Xuf430ae42015-12-09 18:08:16 +0000621}
622
623// Given a CFG E to be instrumented, find which BB to place the instrumented
624// code. The function will split the critical edge if necessary.
625template <class Edge, class BBInfo>
626BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
627 if (E->InMST || E->Removed)
628 return nullptr;
629
630 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
631 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
632 // For a fake edge, instrument the real BB.
633 if (SrcBB == nullptr)
634 return DestBB;
635 if (DestBB == nullptr)
636 return SrcBB;
637
638 // Instrument the SrcBB if it has a single successor,
639 // otherwise, the DestBB if this is not a critical edge.
640 TerminatorInst *TI = SrcBB->getTerminator();
641 if (TI->getNumSuccessors() <= 1)
642 return SrcBB;
643 if (!E->IsCritical)
644 return DestBB;
645
646 // For a critical edge, we have to split. Instrument the newly
647 // created BB.
648 NumOfPGOSplit++;
649 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
650 << getBBInfo(DestBB).Index << "\n");
651 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
652 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
653 assert(InstrBB && "Critical edge is not split");
654
655 E->Removed = true;
656 return InstrBB;
657}
658
Rong Xued9fec72016-01-21 18:11:44 +0000659// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000660// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000661static void instrumentOneFunc(
662 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
663 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000664 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
665 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000666 unsigned NumCounters = FuncInfo.getNumCounters();
667
Rong Xuf430ae42015-12-09 18:08:16 +0000668 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000669 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000670 for (auto &E : FuncInfo.MST.AllEdges) {
671 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
672 if (!InstrBB)
673 continue;
674
675 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
676 assert(Builder.GetInsertPoint() != InstrBB->end() &&
677 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000678 Builder.CreateCall(
679 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
680 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
681 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
682 Builder.getInt32(I++)});
683 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000684
685 // Now instrument select instructions:
686 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
687 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000688 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000689
690 if (DisableValueProfiling)
691 return;
692
693 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000694 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000695 CallSite CS(I);
696 Value *Callee = CS.getCalledValue();
697 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
698 << NumIndirectCallSites << "\n");
699 IRBuilder<> Builder(I);
700 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
701 "Cannot get the Instrumentation point");
702 Builder.CreateCall(
703 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
704 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
705 Builder.getInt64(FuncInfo.FunctionHash),
706 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000707 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000708 Builder.getInt32(NumIndirectCallSites++)});
709 }
710 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000711
712 // Now instrument memop intrinsic calls.
713 FuncInfo.MIVisitor.instrumentMemIntrinsics(
714 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000715}
716
717// This class represents a CFG edge in profile use compilation.
718struct PGOUseEdge : public PGOEdge {
719 bool CountValid;
720 uint64_t CountValue;
721 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
722 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
723
724 // Set edge count value
725 void setEdgeCount(uint64_t Value) {
726 CountValue = Value;
727 CountValid = true;
728 }
729
730 // Return the information string for this object.
731 const std::string infoString() const {
732 if (!CountValid)
733 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000734 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
735 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000736 }
737};
738
739typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
740
741// This class stores the auxiliary information for each BB.
742struct UseBBInfo : public BBInfo {
743 uint64_t CountValue;
744 bool CountValid;
745 int32_t UnknownCountInEdge;
746 int32_t UnknownCountOutEdge;
747 DirectEdges InEdges;
748 DirectEdges OutEdges;
749 UseBBInfo(unsigned IX)
750 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
751 UnknownCountOutEdge(0) {}
752 UseBBInfo(unsigned IX, uint64_t C)
753 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
754 UnknownCountOutEdge(0) {}
755
756 // Set the profile count value for this BB.
757 void setBBInfoCount(uint64_t Value) {
758 CountValue = Value;
759 CountValid = true;
760 }
761
762 // Return the information string of this object.
763 const std::string infoString() const {
764 if (!CountValid)
765 return BBInfo::infoString();
766 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
767 }
768};
769
770// Sum up the count values for all the edges.
771static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
772 uint64_t Total = 0;
773 for (auto &E : Edges) {
774 if (E->Removed)
775 continue;
776 Total += E->CountValue;
777 }
778 return Total;
779}
780
781class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000782public:
Rong Xu705f7772016-07-25 18:45:37 +0000783 PGOUseFunc(Function &Func, Module *Modu,
784 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
785 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000786 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000787 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000788 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000789
790 // Read counts for the instrumented BB from profile.
791 bool readCounters(IndexedInstrProfReader *PGOReader);
792
793 // Populate the counts for all BBs.
794 void populateCounters();
795
796 // Set the branch weights based on the count values.
797 void setBranchWeights();
798
Rong Xua3bbf962017-03-15 18:23:39 +0000799 // Annotate the value profile call sites all all value kind.
800 void annotateValueSites();
801
802 // Annotate the value profile call sites for one value kind.
803 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000804
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000805 // The hotness of the function from the profile count.
806 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
807
808 // Return the function hotness from the profile.
809 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
810
Rong Xu705f7772016-07-25 18:45:37 +0000811 // Return the function hash.
812 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000813 // Return the profile record for this function;
814 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
815
Xinliang David Li4ca17332016-09-18 18:34:07 +0000816 // Return the auxiliary BB information.
817 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
818 return FuncInfo.getBBInfo(BB);
819 }
820
Rong Xua5b57452016-12-02 19:10:29 +0000821 // Return the auxiliary BB information if available.
822 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
823 return FuncInfo.findBBInfo(BB);
824 }
825
Xinliang David Lid289e452017-01-27 19:06:25 +0000826 Function &getFunc() const { return F; }
827
Rong Xuf430ae42015-12-09 18:08:16 +0000828private:
829 Function &F;
830 Module *M;
831 // This member stores the shared information with class PGOGenFunc.
832 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
833
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000834 // The maximum count value in the profile. This is only used in PGO use
835 // compilation.
836 uint64_t ProgramMaxCount;
837
Rong Xu33308f92016-10-25 21:47:24 +0000838 // Position of counter that remains to be read.
839 uint32_t CountPosition;
840
841 // Total size of the profile count for this function.
842 uint32_t ProfileCountSize;
843
Rong Xu13b01dc2016-02-10 18:24:45 +0000844 // ProfileRecord for this function.
845 InstrProfRecord ProfileRecord;
846
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000847 // Function hotness info derived from profile.
848 FuncFreqAttr FreqAttr;
849
Rong Xuf430ae42015-12-09 18:08:16 +0000850 // Find the Instrumented BB and set the value.
851 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
852
853 // Set the edge counter value for the unknown edge -- there should be only
854 // one unknown edge.
855 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
856
857 // Return FuncName string;
858 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000859
860 // Set the hot/cold inline hints based on the count values.
861 // FIXME: This function should be removed once the functionality in
862 // the inliner is implemented.
863 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
864 if (ProgramMaxCount == 0)
865 return;
866 // Threshold of the hot functions.
867 const BranchProbability HotFunctionThreshold(1, 100);
868 // Threshold of the cold functions.
869 const BranchProbability ColdFunctionThreshold(2, 10000);
870 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
871 FreqAttr = FFA_Hot;
872 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
873 FreqAttr = FFA_Cold;
874 }
Rong Xuf430ae42015-12-09 18:08:16 +0000875};
876
877// Visit all the edges and assign the count value for the instrumented
878// edges and the BB.
879void PGOUseFunc::setInstrumentedCounts(
880 const std::vector<uint64_t> &CountFromProfile) {
881
Xinliang David Lid1197612016-08-01 20:25:06 +0000882 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000883 // Use a worklist as we will update the vector during the iteration.
884 std::vector<PGOUseEdge *> WorkList;
885 for (auto &E : FuncInfo.MST.AllEdges)
886 WorkList.push_back(E.get());
887
888 uint32_t I = 0;
889 for (auto &E : WorkList) {
890 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
891 if (!InstrBB)
892 continue;
893 uint64_t CountValue = CountFromProfile[I++];
894 if (!E->Removed) {
895 getBBInfo(InstrBB).setBBInfoCount(CountValue);
896 E->setEdgeCount(CountValue);
897 continue;
898 }
899
900 // Need to add two new edges.
901 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
902 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
903 // Add new edge of SrcBB->InstrBB.
904 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
905 NewEdge.setEdgeCount(CountValue);
906 // Add new edge of InstrBB->DestBB.
907 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
908 NewEdge1.setEdgeCount(CountValue);
909 NewEdge1.InMST = true;
910 getBBInfo(InstrBB).setBBInfoCount(CountValue);
911 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000912 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000913 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000914}
915
916// Set the count value for the unknown edge. There should be one and only one
917// unknown edge in Edges vector.
918void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
919 for (auto &E : Edges) {
920 if (E->CountValid)
921 continue;
922 E->setEdgeCount(Value);
923
924 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
925 getBBInfo(E->DestBB).UnknownCountInEdge--;
926 return;
927 }
928 llvm_unreachable("Cannot find the unknown count edge");
929}
930
931// Read the profile from ProfileFileName and assign the value to the
932// instrumented BB and the edges. This function also updates ProgramMaxCount.
933// Return true if the profile are successfully read, and false on errors.
934bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
935 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000936 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000937 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000938 if (Error E = Result.takeError()) {
939 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
940 auto Err = IPE.get();
941 bool SkipWarning = false;
942 if (Err == instrprof_error::unknown_function) {
943 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000944 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000945 } else if (Err == instrprof_error::hash_mismatch ||
946 Err == instrprof_error::malformed) {
947 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000948 SkipWarning =
949 NoPGOWarnMismatch ||
950 (NoPGOWarnMismatchComdat &&
951 (F.hasComdat() ||
952 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000953 }
Rong Xuf430ae42015-12-09 18:08:16 +0000954
Vedant Kumar9152fd12016-05-19 03:54:45 +0000955 if (SkipWarning)
956 return;
957
958 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
959 Ctx.diagnose(
960 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
961 });
Rong Xuf430ae42015-12-09 18:08:16 +0000962 return false;
963 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000964 ProfileRecord = std::move(Result.get());
965 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000966
967 NumOfPGOFunc++;
968 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
969 uint64_t ValueSum = 0;
970 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
971 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
972 ValueSum += CountFromProfile[I];
973 }
974
975 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
976
977 getBBInfo(nullptr).UnknownCountOutEdge = 2;
978 getBBInfo(nullptr).UnknownCountInEdge = 2;
979
980 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000981 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000982 return true;
983}
984
985// Populate the counters from instrumented BBs to all BBs.
986// In the end of this operation, all BBs should have a valid count value.
987void PGOUseFunc::populateCounters() {
988 // First set up Count variable for all BBs.
989 for (auto &E : FuncInfo.MST.AllEdges) {
990 if (E->Removed)
991 continue;
992
993 const BasicBlock *SrcBB = E->SrcBB;
994 const BasicBlock *DestBB = E->DestBB;
995 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
996 UseBBInfo &DestInfo = getBBInfo(DestBB);
997 SrcInfo.OutEdges.push_back(E.get());
998 DestInfo.InEdges.push_back(E.get());
999 SrcInfo.UnknownCountOutEdge++;
1000 DestInfo.UnknownCountInEdge++;
1001
1002 if (!E->CountValid)
1003 continue;
1004 DestInfo.UnknownCountInEdge--;
1005 SrcInfo.UnknownCountOutEdge--;
1006 }
1007
1008 bool Changes = true;
1009 unsigned NumPasses = 0;
1010 while (Changes) {
1011 NumPasses++;
1012 Changes = false;
1013
1014 // For efficient traversal, it's better to start from the end as most
1015 // of the instrumented edges are at the end.
1016 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001017 UseBBInfo *Count = findBBInfo(&BB);
1018 if (Count == nullptr)
1019 continue;
1020 if (!Count->CountValid) {
1021 if (Count->UnknownCountOutEdge == 0) {
1022 Count->CountValue = sumEdgeCount(Count->OutEdges);
1023 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001024 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001025 } else if (Count->UnknownCountInEdge == 0) {
1026 Count->CountValue = sumEdgeCount(Count->InEdges);
1027 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001028 Changes = true;
1029 }
1030 }
Rong Xua5b57452016-12-02 19:10:29 +00001031 if (Count->CountValid) {
1032 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001033 uint64_t Total = 0;
1034 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1035 // If the one of the successor block can early terminate (no-return),
1036 // we can end up with situation where out edge sum count is larger as
1037 // the source BB's count is collected by a post-dominated block.
1038 if (Count->CountValue > OutSum)
1039 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001040 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001041 Changes = true;
1042 }
Rong Xua5b57452016-12-02 19:10:29 +00001043 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001044 uint64_t Total = 0;
1045 uint64_t InSum = sumEdgeCount(Count->InEdges);
1046 if (Count->CountValue > InSum)
1047 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001048 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001049 Changes = true;
1050 }
1051 }
1052 }
1053 }
1054
1055 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001056#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001057 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001058 for (auto &BB : F) {
1059 auto BI = findBBInfo(&BB);
1060 if (BI == nullptr)
1061 continue;
1062 assert(BI->CountValid && "BB count is not valid");
1063 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001064#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001065 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001066 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001067 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001068 for (auto &BB : F) {
1069 auto BI = findBBInfo(&BB);
1070 if (BI == nullptr)
1071 continue;
1072 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1073 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001074 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001075
Rong Xu33308f92016-10-25 21:47:24 +00001076 // Now annotate select instructions
1077 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1078 assert(CountPosition == ProfileCountSize);
1079
Rong Xuf430ae42015-12-09 18:08:16 +00001080 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1081}
1082
1083// Assign the scaled count values to the BB with multiple out edges.
1084void PGOUseFunc::setBranchWeights() {
1085 // Generate MD_prof metadata for every branch instruction.
1086 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001087 for (auto &BB : F) {
1088 TerminatorInst *TI = BB.getTerminator();
1089 if (TI->getNumSuccessors() < 2)
1090 continue;
1091 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1092 continue;
1093 if (getBBInfo(&BB).CountValue == 0)
1094 continue;
1095
1096 // We have a non-zero Branch BB.
1097 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1098 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001099 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001100 uint64_t MaxCount = 0;
1101 for (unsigned s = 0; s < Size; s++) {
1102 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1103 const BasicBlock *SrcBB = E->SrcBB;
1104 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001105 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001106 continue;
1107 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1108 uint64_t EdgeCount = E->CountValue;
1109 if (EdgeCount > MaxCount)
1110 MaxCount = EdgeCount;
1111 EdgeCounts[SuccNum] = EdgeCount;
1112 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001113 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001114 }
1115}
Rong Xu13b01dc2016-02-10 18:24:45 +00001116
Xinliang David Li4ca17332016-09-18 18:34:07 +00001117void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1118 Module *M = F.getParent();
1119 IRBuilder<> Builder(&SI);
1120 Type *Int64Ty = Builder.getInt64Ty();
1121 Type *I8PtrTy = Builder.getInt8PtrTy();
1122 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1123 Builder.CreateCall(
1124 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1125 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001126 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1127 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001128 ++(*CurCtrIdx);
1129}
1130
1131void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1132 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1133 assert(*CurCtrIdx < CountFromProfile.size() &&
1134 "Out of bound access of counters");
1135 uint64_t SCounts[2];
1136 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1137 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001138 uint64_t TotalCount = 0;
1139 auto BI = UseFunc->findBBInfo(SI.getParent());
1140 if (BI != nullptr)
1141 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001142 // False Count
1143 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1144 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001145 if (MaxCount)
1146 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001147}
1148
1149void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1150 if (!PGOInstrSelect)
1151 return;
1152 // FIXME: do not handle this yet.
1153 if (SI.getCondition()->getType()->isVectorTy())
1154 return;
1155
Xinliang David Li4ca17332016-09-18 18:34:07 +00001156 switch (Mode) {
1157 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001158 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001159 return;
1160 case VM_instrument:
1161 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001162 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001163 case VM_annotate:
1164 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001165 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001166 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001167
1168 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001169}
1170
Rong Xu60faea12017-03-16 21:15:48 +00001171void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1172 Module *M = F.getParent();
1173 IRBuilder<> Builder(&MI);
1174 Type *Int64Ty = Builder.getInt64Ty();
1175 Type *I8PtrTy = Builder.getInt8PtrTy();
1176 Value *Length = MI.getLength();
1177 assert(!dyn_cast<ConstantInt>(Length));
1178 Builder.CreateCall(
1179 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1180 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001181 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001182 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1183 ++CurCtrId;
1184}
1185
1186void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1187 if (!PGOInstrMemOP)
1188 return;
1189 Value *Length = MI.getLength();
1190 // Not instrument constant length calls.
1191 if (dyn_cast<ConstantInt>(Length))
1192 return;
1193
1194 switch (Mode) {
1195 case VM_counting:
1196 NMemIs++;
1197 return;
1198 case VM_instrument:
1199 instrumentOneMemIntrinsic(MI);
1200 return;
1201 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001202 Candidates.push_back(&MI);
1203 return;
Rong Xu60faea12017-03-16 21:15:48 +00001204 }
1205 llvm_unreachable("Unknown visiting mode");
1206}
1207
Rong Xua3bbf962017-03-15 18:23:39 +00001208// Traverse all valuesites and annotate the instructions for all value kind.
1209void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001210 if (DisableValueProfiling)
1211 return;
1212
Rong Xu8e8fe852016-04-01 16:43:30 +00001213 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001214 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001215
Rong Xua3bbf962017-03-15 18:23:39 +00001216 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001217 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001218}
1219
1220// Annotate the instructions for a specific value kind.
1221void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1222 unsigned ValueSiteIndex = 0;
1223 auto &ValueSites = FuncInfo.ValueSites[Kind];
1224 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1225 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001226 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001227 Ctx.diagnose(DiagnosticInfoPGOProfile(
1228 M->getName().data(),
1229 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1230 " in " + F.getName().str(),
1231 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001232 return;
1233 }
1234
Rong Xua3bbf962017-03-15 18:23:39 +00001235 for (auto &I : ValueSites) {
1236 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1237 << "): Index = " << ValueSiteIndex << " out of "
1238 << NumValueSites << "\n");
1239 annotateValueSite(*M, *I, ProfileRecord,
1240 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001241 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1242 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001243 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001244 }
1245}
Rong Xuf430ae42015-12-09 18:08:16 +00001246} // end anonymous namespace
1247
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001248// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001249// aware this is an ir_level profile so it can set the version flag.
1250static void createIRLevelProfileFlagVariable(Module &M) {
1251 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1252 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001253 auto IRLevelVersionVariable = new GlobalVariable(
1254 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1255 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001256 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001257 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1258 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001259 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001260 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001261 else
Rong Xu9e926e82016-02-29 19:16:04 +00001262 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001263 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001264}
1265
Rong Xu705f7772016-07-25 18:45:37 +00001266// Collect the set of members for each Comdat in module M and store
1267// in ComdatMembers.
1268static void collectComdatMembers(
1269 Module &M,
1270 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1271 if (!DoComdatRenaming)
1272 return;
1273 for (Function &F : M)
1274 if (Comdat *C = F.getComdat())
1275 ComdatMembers.insert(std::make_pair(C, &F));
1276 for (GlobalVariable &GV : M.globals())
1277 if (Comdat *C = GV.getComdat())
1278 ComdatMembers.insert(std::make_pair(C, &GV));
1279 for (GlobalAlias &GA : M.aliases())
1280 if (Comdat *C = GA.getComdat())
1281 ComdatMembers.insert(std::make_pair(C, &GA));
1282}
1283
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001284static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001285 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1286 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001287 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001288 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1289 collectComdatMembers(M, ComdatMembers);
1290
Rong Xuf430ae42015-12-09 18:08:16 +00001291 for (auto &F : M) {
1292 if (F.isDeclaration())
1293 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001294 auto *BPI = LookupBPI(F);
1295 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001296 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001297 }
1298 return true;
1299}
1300
Xinliang David Li8aebf442016-05-06 05:49:19 +00001301bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001302 if (skipModule(M))
1303 return false;
1304
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001305 auto LookupBPI = [this](Function &F) {
1306 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001307 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001308 auto LookupBFI = [this](Function &F) {
1309 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001310 };
1311 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1312}
1313
Xinliang David Li8aebf442016-05-06 05:49:19 +00001314PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001315 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001316
1317 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001318 auto LookupBPI = [&FAM](Function &F) {
1319 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001320 };
1321
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001322 auto LookupBFI = [&FAM](Function &F) {
1323 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001324 };
1325
1326 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1327 return PreservedAnalyses::all();
1328
1329 return PreservedAnalyses::none();
1330}
1331
Xinliang David Lida195582016-05-10 21:59:52 +00001332static bool annotateAllFunctions(
1333 Module &M, StringRef ProfileFileName,
1334 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001335 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001336 DEBUG(dbgs() << "Read in profile counters: ");
1337 auto &Ctx = M.getContext();
1338 // Read the counter array from file.
1339 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001340 if (Error E = ReaderOrErr.takeError()) {
1341 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1342 Ctx.diagnose(
1343 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1344 });
Rong Xuf430ae42015-12-09 18:08:16 +00001345 return false;
1346 }
1347
Xinliang David Lida195582016-05-10 21:59:52 +00001348 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1349 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001350 if (!PGOReader) {
1351 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001352 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001353 return false;
1354 }
Rong Xu33c76c02016-02-10 17:18:30 +00001355 // TODO: might need to change the warning once the clang option is finalized.
1356 if (!PGOReader->isIRLevelProfile()) {
1357 Ctx.diagnose(DiagnosticInfoPGOProfile(
1358 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1359 return false;
1360 }
1361
Rong Xu705f7772016-07-25 18:45:37 +00001362 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1363 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001364 std::vector<Function *> HotFunctions;
1365 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001366 for (auto &F : M) {
1367 if (F.isDeclaration())
1368 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001369 auto *BPI = LookupBPI(F);
1370 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001371 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001372 if (!Func.readCounters(PGOReader.get()))
1373 continue;
1374 Func.populateCounters();
1375 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001376 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001377 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1378 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001379 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001380 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1381 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001382 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1383 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001384 LoopInfo LI{DominatorTree(F)};
1385 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1386 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1387 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1388 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1389
1390 NewBFI->view();
1391 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001392 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1393 F.getName().equals(ViewBlockFreqFuncName))) {
1394 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001395 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1396 else
1397 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1398 }
Rong Xuf430ae42015-12-09 18:08:16 +00001399 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001400 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001401 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001402 // We have to apply these attributes at the end because their presence
1403 // can affect the BranchProbabilityInfo of any callers, resulting in an
1404 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001405 for (auto &F : HotFunctions) {
1406 F->addFnAttr(llvm::Attribute::InlineHint);
1407 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1408 << "\n");
1409 }
1410 for (auto &F : ColdFunctions) {
1411 F->addFnAttr(llvm::Attribute::Cold);
1412 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1413 }
Rong Xuf430ae42015-12-09 18:08:16 +00001414 return true;
1415}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001416
Xinliang David Lida195582016-05-10 21:59:52 +00001417PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001418 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001419 if (!PGOTestProfileFile.empty())
1420 ProfileFileName = PGOTestProfileFile;
1421}
1422
1423PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001424 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001425
1426 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1427 auto LookupBPI = [&FAM](Function &F) {
1428 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1429 };
1430
1431 auto LookupBFI = [&FAM](Function &F) {
1432 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1433 };
1434
1435 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1436 return PreservedAnalyses::all();
1437
1438 return PreservedAnalyses::none();
1439}
1440
Xinliang David Lid55827f2016-05-07 05:39:12 +00001441bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1442 if (skipModule(M))
1443 return false;
1444
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001445 auto LookupBPI = [this](Function &F) {
1446 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001447 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001448 auto LookupBFI = [this](Function &F) {
1449 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001450 };
1451
Xinliang David Lida195582016-05-10 21:59:52 +00001452 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001453}
Xinliang David Lid289e452017-01-27 19:06:25 +00001454
1455namespace llvm {
Rong Xu48596b62017-04-04 16:42:20 +00001456void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1457 uint64_t MaxCount) {
1458 MDBuilder MDB(M->getContext());
1459 assert(MaxCount > 0 && "Bad max count");
1460 uint64_t Scale = calculateCountScale(MaxCount);
1461 SmallVector<unsigned, 4> Weights;
1462 for (const auto &ECI : EdgeCounts)
1463 Weights.push_back(scaleBranchCount(ECI, Scale));
1464
1465 DEBUG(dbgs() << "Weight is: ";
1466 for (const auto &W : Weights) { dbgs() << W << " "; }
1467 dbgs() << "\n";);
1468 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001469 if (EmitBranchProbability) {
1470 std::string BrCondStr = getBranchCondString(TI);
1471 if (BrCondStr.empty())
1472 return;
1473
1474 unsigned WSum =
1475 std::accumulate(Weights.begin(), Weights.end(), 0,
1476 [](unsigned w1, unsigned w2) { return w1 + w2; });
1477 uint64_t TotalCount =
1478 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1479 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1480 BranchProbability BP(Weights[0], WSum);
1481 std::string BranchProbStr;
1482 raw_string_ostream OS(BranchProbStr);
1483 OS << BP;
1484 OS << " (total count : " << TotalCount << ")";
1485 OS.flush();
1486 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001487 OptimizationRemarkEmitter ORE(F);
1488 ORE.emit(OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1489 << BrCondStr << " is true with probability : " << BranchProbStr);
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001490 }
Rong Xu48596b62017-04-04 16:42:20 +00001491}
1492
Xinliang David Lid289e452017-01-27 19:06:25 +00001493template <> struct GraphTraits<PGOUseFunc *> {
1494 typedef const BasicBlock *NodeRef;
1495 typedef succ_const_iterator ChildIteratorType;
1496 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1497
1498 static NodeRef getEntryNode(const PGOUseFunc *G) {
1499 return &G->getFunc().front();
1500 }
1501 static ChildIteratorType child_begin(const NodeRef N) {
1502 return succ_begin(N);
1503 }
1504 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1505 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1506 return nodes_iterator(G->getFunc().begin());
1507 }
1508 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1509 return nodes_iterator(G->getFunc().end());
1510 }
1511};
1512
Xinliang David Li6144a592017-02-03 21:57:51 +00001513static std::string getSimpleNodeName(const BasicBlock *Node) {
1514 if (!Node->getName().empty())
1515 return Node->getName();
1516
1517 std::string SimpleNodeName;
1518 raw_string_ostream OS(SimpleNodeName);
1519 Node->printAsOperand(OS, false);
1520 return OS.str();
1521}
1522
Xinliang David Lid289e452017-01-27 19:06:25 +00001523template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1524 explicit DOTGraphTraits(bool isSimple = false)
1525 : DefaultDOTGraphTraits(isSimple) {}
1526
1527 static std::string getGraphName(const PGOUseFunc *G) {
1528 return G->getFunc().getName();
1529 }
1530
1531 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1532 std::string Result;
1533 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001534
1535 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001536 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001537 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001538 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001539 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001540 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001541 OS << "Unknown\\l";
1542
1543 if (!PGOInstrSelect)
1544 return Result;
1545
1546 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1547 auto *I = &*BI;
1548 if (!isa<SelectInst>(I))
1549 continue;
1550 // Display scaled counts for SELECT instruction:
1551 OS << "SELECT : { T = ";
1552 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001553 bool HasProf = I->extractProfMetadata(TC, FC);
1554 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001555 OS << "Unknown, F = Unknown }\\l";
1556 else
1557 OS << TC << ", F = " << FC << " }\\l";
1558 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001559 return Result;
1560 }
1561};
Rong Xu0a2a1312017-03-09 19:08:55 +00001562} // namespace llvm