blob: 7431edbb262fdfd8438add47eccd79ad7effc202 [file] [log] [blame]
Eugene Zelenkofce43572017-10-21 00:57:46 +00001//===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
Rong Xuf430ae42015-12-09 18:08:16 +00002//
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"
Eugene Zelenkofce43572017-10-21 00:57:46 +000053#include "llvm/ADT/APInt.h"
54#include "llvm/ADT/ArrayRef.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000056#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/ADT/Statistic.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000058#include "llvm/ADT/StringRef.h"
Rong Xu33c76c02016-02-10 17:18:30 +000059#include "llvm/ADT/Triple.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000060#include "llvm/ADT/Twine.h"
61#include "llvm/ADT/iterator.h"
62#include "llvm/ADT/iterator_range.h"
Rong Xuf430ae42015-12-09 18:08:16 +000063#include "llvm/Analysis/BlockFrequencyInfo.h"
64#include "llvm/Analysis/BranchProbabilityInfo.h"
65#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000066#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000067#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000068#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000069#include "llvm/IR/Attributes.h"
70#include "llvm/IR/BasicBlock.h"
71#include "llvm/IR/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000072#include "llvm/IR/CallSite.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000073#include "llvm/IR/Comdat.h"
74#include "llvm/IR/Constant.h"
75#include "llvm/IR/Constants.h"
Rong Xuf430ae42015-12-09 18:08:16 +000076#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000077#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000078#include "llvm/IR/Function.h"
79#include "llvm/IR/GlobalAlias.h"
Rong Xu705f7772016-07-25 18:45:37 +000080#include "llvm/IR/GlobalValue.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000081#include "llvm/IR/GlobalVariable.h"
Rong Xuf430ae42015-12-09 18:08:16 +000082#include "llvm/IR/IRBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000083#include "llvm/IR/InstVisitor.h"
84#include "llvm/IR/InstrTypes.h"
85#include "llvm/IR/Instruction.h"
Rong Xuf430ae42015-12-09 18:08:16 +000086#include "llvm/IR/Instructions.h"
87#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000088#include "llvm/IR/Intrinsics.h"
89#include "llvm/IR/LLVMContext.h"
Rong Xuf430ae42015-12-09 18:08:16 +000090#include "llvm/IR/MDBuilder.h"
91#include "llvm/IR/Module.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000092#include "llvm/IR/PassManager.h"
93#include "llvm/IR/ProfileSummary.h"
94#include "llvm/IR/Type.h"
95#include "llvm/IR/Value.h"
Rong Xuf430ae42015-12-09 18:08:16 +000096#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000097#include "llvm/ProfileData/InstrProf.h"
Rong Xuf430ae42015-12-09 18:08:16 +000098#include "llvm/ProfileData/InstrProfReader.h"
99#include "llvm/Support/BranchProbability.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000100#include "llvm/Support/Casting.h"
101#include "llvm/Support/CommandLine.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000102#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000103#include "llvm/Support/Debug.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000104#include "llvm/Support/Error.h"
105#include "llvm/Support/ErrorHandling.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000106#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000107#include "llvm/Support/JamCRC.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000108#include "llvm/Support/raw_ostream.h"
Rong Xued9fec72016-01-21 18:11:44 +0000109#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000110#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +0000111#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000112#include <cassert>
113#include <cstdint>
114#include <memory>
115#include <numeric>
Rong Xuf430ae42015-12-09 18:08:16 +0000116#include <string>
Rong Xu705f7772016-07-25 18:45:37 +0000117#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +0000118#include <utility>
119#include <vector>
120
121using namespace llvm;
122
123#define DEBUG_TYPE "pgo-instrumentation"
124
125STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000126STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +0000127STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +0000128STATISTIC(NumOfPGOEdge, "Number of edges.");
129STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
130STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
131STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
132STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
133STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000134STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000135
136// Command line option to specify the file to read profile from. This is
137// mainly used for testing.
138static cl::opt<std::string>
139 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
140 cl::value_desc("filename"),
141 cl::desc("Specify the path of profile data file. This is"
142 "mainly for test purpose."));
143
Rong Xuecdc98f2016-03-04 22:08:44 +0000144// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000145// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000146static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
147 cl::Hidden,
148 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000149
Rong Xuecdc98f2016-03-04 22:08:44 +0000150// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000151// the metadata for a single indirect call callsite.
152static cl::opt<unsigned> MaxNumAnnotations(
153 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
154 cl::desc("Max number of annotations for a single indirect "
155 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000156
Rong Xue60343d2017-03-17 18:07:26 +0000157// Command line option to set the maximum number of value annotations
158// to write to the metadata for a single memop intrinsic.
159static cl::opt<unsigned> MaxNumMemOPAnnotations(
160 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
161 cl::desc("Max number of preicise value annotations for a single memop"
162 "intrinsic"));
163
Rong Xu705f7772016-07-25 18:45:37 +0000164// Command line option to control appending FunctionHash to the name of a COMDAT
165// function. This is to avoid the hash mismatch caused by the preinliner.
166static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000167 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000168 cl::desc("Append function hash to the name of COMDAT function to avoid "
169 "function hash mismatch due to the preinliner"));
170
Rong Xu0698de92016-05-13 17:26:06 +0000171// Command line option to enable/disable the warning about missing profile
172// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000173static cl::opt<bool>
174 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
175 cl::desc("Use this option to turn on/off "
176 "warnings about missing profile data for "
177 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000178
179// Command line option to enable/disable the warning about a hash mismatch in
180// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000181static cl::opt<bool>
182 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
183 cl::desc("Use this option to turn off/on "
184 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000185
Rong Xu20f5df12017-01-11 20:19:41 +0000186// Command line option to enable/disable the warning about a hash mismatch in
187// the profile data for Comdat functions, which often turns out to be false
188// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000189static cl::opt<bool>
190 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
191 cl::Hidden,
192 cl::desc("The option is used to turn on/off "
193 "warnings about hash mismatch for comdat "
194 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000195
Xinliang David Li4ca17332016-09-18 18:34:07 +0000196// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000197static cl::opt<bool>
198 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
199 cl::desc("Use this option to turn on/off SELECT "
200 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000201
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000202// Command line option to turn on CFG dot or text dump of raw profile counts
203static cl::opt<PGOViewCountsType> PGOViewRawCounts(
204 "pgo-view-raw-counts", cl::Hidden,
205 cl::desc("A boolean option to show CFG dag or text "
206 "with raw profile counts from "
207 "profile data. See also option "
208 "-pgo-view-counts. To limit graph "
209 "display to only one function, use "
210 "filtering option -view-bfi-func-name."),
211 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
212 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
213 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000214
Rong Xu8e06e802017-03-17 20:51:44 +0000215// Command line option to enable/disable memop intrinsic call.size profiling.
216static cl::opt<bool>
217 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
218 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000219 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000220
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000221// Emit branch probability as optimization remarks.
222static cl::opt<bool>
223 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
224 cl::desc("When this option is on, the annotated "
225 "branch probability will be emitted as "
226 " optimization remarks: -Rpass-analysis="
227 "pgo-instr-use"));
228
Xinliang David Licb253ce2017-01-23 18:58:24 +0000229// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000230// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000231extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000232
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000233// Command line option to specify the name of the function for CFG dump
234// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
235extern cl::opt<std::string> ViewBlockFreqFuncName;
236
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000237// Return a string describing the branch condition that can be
238// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000239static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000240 BranchInst *BI = dyn_cast<BranchInst>(TI);
241 if (!BI || !BI->isConditional())
242 return std::string();
243
244 Value *Cond = BI->getCondition();
245 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
246 if (!CI)
247 return std::string();
248
249 std::string result;
250 raw_string_ostream OS(result);
251 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
252 CI->getOperand(0)->getType()->print(OS, true);
253
254 Value *RHS = CI->getOperand(1);
255 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
256 if (CV) {
257 if (CV->isZero())
258 OS << "_Zero";
259 else if (CV->isOne())
260 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000261 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000262 OS << "_MinusOne";
263 else
264 OS << "_Const";
265 }
266 OS.flush();
267 return result;
268}
269
Eugene Zelenkofce43572017-10-21 00:57:46 +0000270namespace {
271
Xinliang David Li4ca17332016-09-18 18:34:07 +0000272/// The select instruction visitor plays three roles specified
273/// by the mode. In \c VM_counting mode, it simply counts the number of
274/// select instructions. In \c VM_instrument mode, it inserts code to count
275/// the number times TrueValue of select is taken. In \c VM_annotate mode,
276/// it reads the profile data and annotate the select instruction with metadata.
277enum VisitMode { VM_counting, VM_instrument, VM_annotate };
278class PGOUseFunc;
279
280/// Instruction Visitor class to visit select instructions.
281struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
282 Function &F;
283 unsigned NSIs = 0; // Number of select instructions instrumented.
284 VisitMode Mode = VM_counting; // Visiting mode.
285 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
286 unsigned TotalNumCtrs = 0; // Total number of counters
287 GlobalVariable *FuncNameVar = nullptr;
288 uint64_t FuncHash = 0;
289 PGOUseFunc *UseFunc = nullptr;
290
291 SelectInstVisitor(Function &Func) : F(Func) {}
292
293 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000294 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000295 Mode = VM_counting;
296 visit(Func);
297 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000298
Xinliang David Li4ca17332016-09-18 18:34:07 +0000299 // Visit the IR stream and instrument all select instructions. \p
300 // Ind is a pointer to the counter index variable; \p TotalNC
301 // is the total number of counters; \p FNV is the pointer to the
302 // PGO function name var; \p FHash is the function hash.
303 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
304 GlobalVariable *FNV, uint64_t FHash) {
305 Mode = VM_instrument;
306 CurCtrIdx = Ind;
307 TotalNumCtrs = TotalNC;
308 FuncHash = FHash;
309 FuncNameVar = FNV;
310 visit(Func);
311 }
312
313 // Visit the IR stream and annotate all select instructions.
314 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
315 Mode = VM_annotate;
316 UseFunc = UF;
317 CurCtrIdx = Ind;
318 visit(Func);
319 }
320
321 void instrumentOneSelectInst(SelectInst &SI);
322 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000323
Xinliang David Li4ca17332016-09-18 18:34:07 +0000324 // Visit \p SI instruction and perform tasks according to visit mode.
325 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000326
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000327 // Return the number of select instructions. This needs be called after
328 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000329 unsigned getNumOfSelectInsts() const { return NSIs; }
330};
331
Rong Xu60faea12017-03-16 21:15:48 +0000332/// Instruction Visitor class to visit memory intrinsic calls.
333struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
334 Function &F;
335 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
336 VisitMode Mode = VM_counting; // Visiting mode.
337 unsigned CurCtrId = 0; // Current counter index.
338 unsigned TotalNumCtrs = 0; // Total number of counters
339 GlobalVariable *FuncNameVar = nullptr;
340 uint64_t FuncHash = 0;
341 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000342 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000343
344 MemIntrinsicVisitor(Function &Func) : F(Func) {}
345
346 void countMemIntrinsics(Function &Func) {
347 NMemIs = 0;
348 Mode = VM_counting;
349 visit(Func);
350 }
Rong Xue60343d2017-03-17 18:07:26 +0000351
Rong Xu60faea12017-03-16 21:15:48 +0000352 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
353 GlobalVariable *FNV, uint64_t FHash) {
354 Mode = VM_instrument;
355 TotalNumCtrs = TotalNC;
356 FuncHash = FHash;
357 FuncNameVar = FNV;
358 visit(Func);
359 }
360
Rong Xue60343d2017-03-17 18:07:26 +0000361 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
362 Candidates.clear();
363 Mode = VM_annotate;
364 visit(Func);
365 return Candidates;
366 }
367
Rong Xu60faea12017-03-16 21:15:48 +0000368 // Visit the IR stream and annotate all mem intrinsic call instructions.
369 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000370
Rong Xu60faea12017-03-16 21:15:48 +0000371 // Visit \p MI instruction and perform tasks according to visit mode.
372 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000373
Rong Xu60faea12017-03-16 21:15:48 +0000374 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
375};
376
Xinliang David Li8aebf442016-05-06 05:49:19 +0000377class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000378public:
379 static char ID;
380
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000381 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000382 initializePGOInstrumentationGenLegacyPassPass(
383 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000384 }
385
Mehdi Amini117296c2016-10-01 02:56:57 +0000386 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000387
388private:
389 bool runOnModule(Module &M) override;
390
391 void getAnalysisUsage(AnalysisUsage &AU) const override {
392 AU.addRequired<BlockFrequencyInfoWrapperPass>();
393 }
394};
395
Xinliang David Lid55827f2016-05-07 05:39:12 +0000396class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000397public:
398 static char ID;
399
400 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000401 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000402 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000403 if (!PGOTestProfileFile.empty())
404 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000405 initializePGOInstrumentationUseLegacyPassPass(
406 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000407 }
408
Mehdi Amini117296c2016-10-01 02:56:57 +0000409 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000410
411private:
412 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000413
Xinliang David Lida195582016-05-10 21:59:52 +0000414 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000415
Rong Xuf430ae42015-12-09 18:08:16 +0000416 void getAnalysisUsage(AnalysisUsage &AU) const override {
417 AU.addRequired<BlockFrequencyInfoWrapperPass>();
418 }
419};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000420
Rong Xuf430ae42015-12-09 18:08:16 +0000421} // end anonymous namespace
422
Xinliang David Li8aebf442016-05-06 05:49:19 +0000423char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000424
Xinliang David Li8aebf442016-05-06 05:49:19 +0000425INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000426 "PGO instrumentation.", false, false)
427INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000428INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000429INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000430 "PGO instrumentation.", false, false)
431
Xinliang David Li8aebf442016-05-06 05:49:19 +0000432ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
433 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000434}
435
Xinliang David Lid55827f2016-05-07 05:39:12 +0000436char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000437
Xinliang David Lid55827f2016-05-07 05:39:12 +0000438INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000439 "Read PGO instrumentation profile.", false, false)
440INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000441INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000442INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000443 "Read PGO instrumentation profile.", false, false)
444
Xinliang David Lid55827f2016-05-07 05:39:12 +0000445ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
446 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000447}
448
449namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000450
Rong Xuf430ae42015-12-09 18:08:16 +0000451/// \brief An MST based instrumentation for PGO
452///
453/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
454/// in the function level.
455struct PGOEdge {
456 // This class implements the CFG edges. Note the CFG can be a multi-graph.
457 // So there might be multiple edges with same SrcBB and DestBB.
458 const BasicBlock *SrcBB;
459 const BasicBlock *DestBB;
460 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000461 bool InMST = false;
462 bool Removed = false;
463 bool IsCritical = false;
464
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000465 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000466 : SrcBB(Src), DestBB(Dest), Weight(W) {}
467
Rong Xuf430ae42015-12-09 18:08:16 +0000468 // Return the information string of an edge.
469 const std::string infoString() const {
470 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
471 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
472 }
473};
474
475// This class stores the auxiliary information for each BB.
476struct BBInfo {
477 BBInfo *Group;
478 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000479 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000480
Eugene Zelenkofce43572017-10-21 00:57:46 +0000481 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000482
483 // Return the information string of this object.
484 const std::string infoString() const {
485 return (Twine("Index=") + Twine(Index)).str();
486 }
487};
488
489// This class implements the CFG edges. Note the CFG can be a multi-graph.
490template <class Edge, class BBInfo> class FuncPGOInstrumentation {
491private:
492 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000493
Rong Xu705f7772016-07-25 18:45:37 +0000494 // A map that stores the Comdat group in function F.
495 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000496
Eugene Zelenkofce43572017-10-21 00:57:46 +0000497 void computeCFGHash();
498 void renameComdatFunction();
499
Rong Xuf430ae42015-12-09 18:08:16 +0000500public:
Rong Xua3bbf962017-03-15 18:23:39 +0000501 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000502 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000503 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000504 std::string FuncName;
505 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000506
Rong Xuf430ae42015-12-09 18:08:16 +0000507 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000508 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000509
510 // The Minimum Spanning Tree of function CFG.
511 CFGMST<Edge, BBInfo> MST;
512
513 // Give an edge, find the BB that will be instrumented.
514 // Return nullptr if there is no BB to be instrumented.
515 BasicBlock *getInstrBB(Edge *E);
516
517 // Return the auxiliary BB information.
518 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
519
Rong Xua5b57452016-12-02 19:10:29 +0000520 // Return the auxiliary BB information if available.
521 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
522
Rong Xuf430ae42015-12-09 18:08:16 +0000523 // Dump edges and BB information.
524 void dumpInfo(std::string Str = "") const {
525 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000526 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000527 }
528
Rong Xu705f7772016-07-25 18:45:37 +0000529 FuncPGOInstrumentation(
530 Function &Func,
531 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000532 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
533 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000534 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000535 SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000536 // This should be done before CFG hash computation.
537 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000538 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000539 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000540 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000541 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000542 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000543
Rong Xuf430ae42015-12-09 18:08:16 +0000544 FuncName = getPGOFuncName(F);
545 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000546 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000547 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000548 DEBUG(dumpInfo("after CFGMST"));
549
550 NumOfPGOBB += MST.BBInfos.size();
551 for (auto &E : MST.AllEdges) {
552 if (E->Removed)
553 continue;
554 NumOfPGOEdge++;
555 if (!E->InMST)
556 NumOfPGOInstrument++;
557 }
558
559 if (CreateGlobalVar)
560 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000561 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000562
563 // Return the number of profile counters needed for the function.
564 unsigned getNumCounters() {
565 unsigned NumCounters = 0;
566 for (auto &E : this->MST.AllEdges) {
567 if (!E->InMST && !E->Removed)
568 NumCounters++;
569 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000570 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000571 }
Rong Xuf430ae42015-12-09 18:08:16 +0000572};
573
Eugene Zelenkofce43572017-10-21 00:57:46 +0000574} // end anonymous namespace
575
Rong Xuf430ae42015-12-09 18:08:16 +0000576// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
577// value of each BB in the CFG. The higher 32 bits record the number of edges.
578template <class Edge, class BBInfo>
579void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
580 std::vector<char> Indexes;
581 JamCRC JC;
582 for (auto &BB : F) {
583 const TerminatorInst *TI = BB.getTerminator();
584 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
585 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000586 auto BI = findBBInfo(Succ);
587 if (BI == nullptr)
588 continue;
589 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000590 for (int J = 0; J < 4; J++)
591 Indexes.push_back((char)(Index >> (J * 8)));
592 }
593 }
594 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000595 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000596 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000597 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Xinliang David Li8e436982017-07-21 21:36:25 +0000598 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
599 << " CRC = " << JC.getCRC()
600 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
601 << ", Edges = " << MST.AllEdges.size()
602 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
603 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000604}
605
606// Check if we can safely rename this Comdat function.
607static bool canRenameComdat(
608 Function &F,
609 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000610 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000611 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000612
613 // FIXME: Current only handle those Comdat groups that only containing one
614 // function and function aliases.
615 // (1) For a Comdat group containing multiple functions, we need to have a
616 // unique postfix based on the hashes for each function. There is a
617 // non-trivial code refactoring to do this efficiently.
618 // (2) Variables can not be renamed, so we can not rename Comdat function in a
619 // group including global vars.
620 Comdat *C = F.getComdat();
621 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
622 if (dyn_cast<GlobalAlias>(CM.second))
623 continue;
624 Function *FM = dyn_cast<Function>(CM.second);
625 if (FM != &F)
626 return false;
627 }
628 return true;
629}
630
631// Append the CFGHash to the Comdat function name.
632template <class Edge, class BBInfo>
633void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
634 if (!canRenameComdat(F, ComdatMembers))
635 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000636 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000637 std::string NewFuncName =
638 Twine(F.getName() + "." + Twine(FunctionHash)).str();
639 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000640 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000641 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
642 Comdat *NewComdat;
643 Module *M = F.getParent();
644 // For AvailableExternallyLinkage functions, change the linkage to
645 // LinkOnceODR and put them into comdat. This is because after renaming, there
646 // is no backup external copy available for the function.
647 if (!F.hasComdat()) {
648 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
649 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
650 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
651 F.setComdat(NewComdat);
652 return;
653 }
654
655 // This function belongs to a single function Comdat group.
656 Comdat *OrigComdat = F.getComdat();
657 std::string NewComdatName =
658 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
659 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
660 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
661
662 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
663 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
664 // For aliases, change the name directly.
665 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000666 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000667 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000668 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000669 continue;
670 }
671 // Must be a function.
672 Function *CF = dyn_cast<Function>(CM.second);
673 assert(CF);
674 CF->setComdat(NewComdat);
675 }
Rong Xuf430ae42015-12-09 18:08:16 +0000676}
677
678// Given a CFG E to be instrumented, find which BB to place the instrumented
679// code. The function will split the critical edge if necessary.
680template <class Edge, class BBInfo>
681BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
682 if (E->InMST || E->Removed)
683 return nullptr;
684
685 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
686 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
687 // For a fake edge, instrument the real BB.
688 if (SrcBB == nullptr)
689 return DestBB;
690 if (DestBB == nullptr)
691 return SrcBB;
692
693 // Instrument the SrcBB if it has a single successor,
694 // otherwise, the DestBB if this is not a critical edge.
695 TerminatorInst *TI = SrcBB->getTerminator();
696 if (TI->getNumSuccessors() <= 1)
697 return SrcBB;
698 if (!E->IsCritical)
699 return DestBB;
700
701 // For a critical edge, we have to split. Instrument the newly
702 // created BB.
703 NumOfPGOSplit++;
704 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
705 << getBBInfo(DestBB).Index << "\n");
706 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
707 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
708 assert(InstrBB && "Critical edge is not split");
709
710 E->Removed = true;
711 return InstrBB;
712}
713
Rong Xued9fec72016-01-21 18:11:44 +0000714// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000715// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000716static void instrumentOneFunc(
Xinliang David Lid91057b2017-12-08 19:38:07 +0000717 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Rong Xu705f7772016-07-25 18:45:37 +0000718 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Xinliang David Lid91057b2017-12-08 19:38:07 +0000719 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
720 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000721 unsigned NumCounters = FuncInfo.getNumCounters();
722
Rong Xuf430ae42015-12-09 18:08:16 +0000723 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000724 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000725 for (auto &E : FuncInfo.MST.AllEdges) {
726 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
727 if (!InstrBB)
728 continue;
729
730 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
731 assert(Builder.GetInsertPoint() != InstrBB->end() &&
732 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000733 Builder.CreateCall(
734 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000735 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000736 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
737 Builder.getInt32(I++)});
738 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000739
740 // Now instrument select instructions:
741 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
742 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000743 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000744
745 if (DisableValueProfiling)
746 return;
747
748 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000749 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000750 CallSite CS(I);
751 Value *Callee = CS.getCalledValue();
752 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
753 << NumIndirectCallSites << "\n");
754 IRBuilder<> Builder(I);
755 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
756 "Cannot get the Instrumentation point");
757 Builder.CreateCall(
758 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000759 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000760 Builder.getInt64(FuncInfo.FunctionHash),
761 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000762 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000763 Builder.getInt32(NumIndirectCallSites++)});
764 }
765 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000766
767 // Now instrument memop intrinsic calls.
768 FuncInfo.MIVisitor.instrumentMemIntrinsics(
769 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000770}
771
Eugene Zelenkofce43572017-10-21 00:57:46 +0000772namespace {
773
Rong Xuf430ae42015-12-09 18:08:16 +0000774// This class represents a CFG edge in profile use compilation.
775struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000776 bool CountValid = false;
777 uint64_t CountValue = 0;
778
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000779 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000780 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000781
782 // Set edge count value
783 void setEdgeCount(uint64_t Value) {
784 CountValue = Value;
785 CountValid = true;
786 }
787
788 // Return the information string for this object.
789 const std::string infoString() const {
790 if (!CountValid)
791 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000792 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
793 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000794 }
795};
796
Eugene Zelenkofce43572017-10-21 00:57:46 +0000797using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000798
799// This class stores the auxiliary information for each BB.
800struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000801 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000802 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000803 int32_t UnknownCountInEdge = 0;
804 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000805 DirectEdges InEdges;
806 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000807
808 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
809
Rong Xuf430ae42015-12-09 18:08:16 +0000810 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000811 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000812
813 // Set the profile count value for this BB.
814 void setBBInfoCount(uint64_t Value) {
815 CountValue = Value;
816 CountValid = true;
817 }
818
819 // Return the information string of this object.
820 const std::string infoString() const {
821 if (!CountValid)
822 return BBInfo::infoString();
823 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
824 }
825};
826
Eugene Zelenkofce43572017-10-21 00:57:46 +0000827} // end anonymous namespace
828
Rong Xuf430ae42015-12-09 18:08:16 +0000829// Sum up the count values for all the edges.
830static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
831 uint64_t Total = 0;
832 for (auto &E : Edges) {
833 if (E->Removed)
834 continue;
835 Total += E->CountValue;
836 }
837 return Total;
838}
839
Eugene Zelenkofce43572017-10-21 00:57:46 +0000840namespace {
841
Rong Xuf430ae42015-12-09 18:08:16 +0000842class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000843public:
Rong Xu705f7772016-07-25 18:45:37 +0000844 PGOUseFunc(Function &Func, Module *Modu,
845 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000846 BranchProbabilityInfo *BPI = nullptr,
Xinliang David Li45c81902017-12-05 21:54:01 +0000847 BlockFrequencyInfo *BFIin = nullptr)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000848 : F(Func), M(Modu), BFI(BFIin),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000849 FuncInfo(Func, ComdatMembers, false, BPI, BFIin),
850 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000851
852 // Read counts for the instrumented BB from profile.
853 bool readCounters(IndexedInstrProfReader *PGOReader);
854
855 // Populate the counts for all BBs.
856 void populateCounters();
857
858 // Set the branch weights based on the count values.
859 void setBranchWeights();
860
Rong Xua3bbf962017-03-15 18:23:39 +0000861 // Annotate the value profile call sites all all value kind.
862 void annotateValueSites();
863
864 // Annotate the value profile call sites for one value kind.
865 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000866
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000867 // Annotate the irreducible loop header weights.
868 void annotateIrrLoopHeaderWeights();
869
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000870 // The hotness of the function from the profile count.
871 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
872
873 // Return the function hotness from the profile.
874 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
875
Rong Xu705f7772016-07-25 18:45:37 +0000876 // Return the function hash.
877 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000878
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000879 // Return the profile record for this function;
880 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
881
Xinliang David Li4ca17332016-09-18 18:34:07 +0000882 // Return the auxiliary BB information.
883 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
884 return FuncInfo.getBBInfo(BB);
885 }
886
Rong Xua5b57452016-12-02 19:10:29 +0000887 // Return the auxiliary BB information if available.
888 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
889 return FuncInfo.findBBInfo(BB);
890 }
891
Xinliang David Lid289e452017-01-27 19:06:25 +0000892 Function &getFunc() const { return F; }
893
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000894 void dumpInfo(std::string Str = "") const {
895 FuncInfo.dumpInfo(Str);
896 }
897
Rong Xuf430ae42015-12-09 18:08:16 +0000898private:
899 Function &F;
900 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000901 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000902
Rong Xuf430ae42015-12-09 18:08:16 +0000903 // This member stores the shared information with class PGOGenFunc.
904 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
905
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000906 // The maximum count value in the profile. This is only used in PGO use
907 // compilation.
908 uint64_t ProgramMaxCount;
909
Rong Xu33308f92016-10-25 21:47:24 +0000910 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000911 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000912
913 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000914 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000915
Rong Xu13b01dc2016-02-10 18:24:45 +0000916 // ProfileRecord for this function.
917 InstrProfRecord ProfileRecord;
918
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000919 // Function hotness info derived from profile.
920 FuncFreqAttr FreqAttr;
921
Rong Xuf430ae42015-12-09 18:08:16 +0000922 // Find the Instrumented BB and set the value.
923 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
924
925 // Set the edge counter value for the unknown edge -- there should be only
926 // one unknown edge.
927 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
928
929 // Return FuncName string;
930 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000931
932 // Set the hot/cold inline hints based on the count values.
933 // FIXME: This function should be removed once the functionality in
934 // the inliner is implemented.
935 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
936 if (ProgramMaxCount == 0)
937 return;
938 // Threshold of the hot functions.
939 const BranchProbability HotFunctionThreshold(1, 100);
940 // Threshold of the cold functions.
941 const BranchProbability ColdFunctionThreshold(2, 10000);
942 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
943 FreqAttr = FFA_Hot;
944 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
945 FreqAttr = FFA_Cold;
946 }
Rong Xuf430ae42015-12-09 18:08:16 +0000947};
948
Eugene Zelenkofce43572017-10-21 00:57:46 +0000949} // end anonymous namespace
950
Rong Xuf430ae42015-12-09 18:08:16 +0000951// Visit all the edges and assign the count value for the instrumented
952// edges and the BB.
953void PGOUseFunc::setInstrumentedCounts(
954 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +0000955 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000956 // Use a worklist as we will update the vector during the iteration.
957 std::vector<PGOUseEdge *> WorkList;
958 for (auto &E : FuncInfo.MST.AllEdges)
959 WorkList.push_back(E.get());
960
961 uint32_t I = 0;
962 for (auto &E : WorkList) {
963 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
964 if (!InstrBB)
965 continue;
966 uint64_t CountValue = CountFromProfile[I++];
967 if (!E->Removed) {
968 getBBInfo(InstrBB).setBBInfoCount(CountValue);
969 E->setEdgeCount(CountValue);
970 continue;
971 }
972
973 // Need to add two new edges.
974 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
975 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
976 // Add new edge of SrcBB->InstrBB.
977 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
978 NewEdge.setEdgeCount(CountValue);
979 // Add new edge of InstrBB->DestBB.
980 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
981 NewEdge1.setEdgeCount(CountValue);
982 NewEdge1.InMST = true;
983 getBBInfo(InstrBB).setBBInfoCount(CountValue);
984 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000985 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000986 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000987}
988
989// Set the count value for the unknown edge. There should be one and only one
990// unknown edge in Edges vector.
991void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
992 for (auto &E : Edges) {
993 if (E->CountValid)
994 continue;
995 E->setEdgeCount(Value);
996
997 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
998 getBBInfo(E->DestBB).UnknownCountInEdge--;
999 return;
1000 }
1001 llvm_unreachable("Cannot find the unknown count edge");
1002}
1003
1004// Read the profile from ProfileFileName and assign the value to the
1005// instrumented BB and the edges. This function also updates ProgramMaxCount.
1006// Return true if the profile are successfully read, and false on errors.
1007bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
1008 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001009 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001010 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001011 if (Error E = Result.takeError()) {
1012 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1013 auto Err = IPE.get();
1014 bool SkipWarning = false;
1015 if (Err == instrprof_error::unknown_function) {
1016 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001017 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +00001018 } else if (Err == instrprof_error::hash_mismatch ||
1019 Err == instrprof_error::malformed) {
1020 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001021 SkipWarning =
1022 NoPGOWarnMismatch ||
1023 (NoPGOWarnMismatchComdat &&
1024 (F.hasComdat() ||
1025 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +00001026 }
Rong Xuf430ae42015-12-09 18:08:16 +00001027
Vedant Kumar9152fd12016-05-19 03:54:45 +00001028 if (SkipWarning)
1029 return;
1030
1031 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1032 Ctx.diagnose(
1033 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1034 });
Rong Xuf430ae42015-12-09 18:08:16 +00001035 return false;
1036 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001037 ProfileRecord = std::move(Result.get());
1038 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001039
1040 NumOfPGOFunc++;
1041 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1042 uint64_t ValueSum = 0;
1043 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1044 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1045 ValueSum += CountFromProfile[I];
1046 }
1047
1048 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1049
1050 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1051 getBBInfo(nullptr).UnknownCountInEdge = 2;
1052
1053 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001054 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +00001055 return true;
1056}
1057
1058// Populate the counters from instrumented BBs to all BBs.
1059// In the end of this operation, all BBs should have a valid count value.
1060void PGOUseFunc::populateCounters() {
1061 // First set up Count variable for all BBs.
1062 for (auto &E : FuncInfo.MST.AllEdges) {
1063 if (E->Removed)
1064 continue;
1065
1066 const BasicBlock *SrcBB = E->SrcBB;
1067 const BasicBlock *DestBB = E->DestBB;
1068 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1069 UseBBInfo &DestInfo = getBBInfo(DestBB);
1070 SrcInfo.OutEdges.push_back(E.get());
1071 DestInfo.InEdges.push_back(E.get());
1072 SrcInfo.UnknownCountOutEdge++;
1073 DestInfo.UnknownCountInEdge++;
1074
1075 if (!E->CountValid)
1076 continue;
1077 DestInfo.UnknownCountInEdge--;
1078 SrcInfo.UnknownCountOutEdge--;
1079 }
1080
1081 bool Changes = true;
1082 unsigned NumPasses = 0;
1083 while (Changes) {
1084 NumPasses++;
1085 Changes = false;
1086
1087 // For efficient traversal, it's better to start from the end as most
1088 // of the instrumented edges are at the end.
1089 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001090 UseBBInfo *Count = findBBInfo(&BB);
1091 if (Count == nullptr)
1092 continue;
1093 if (!Count->CountValid) {
1094 if (Count->UnknownCountOutEdge == 0) {
1095 Count->CountValue = sumEdgeCount(Count->OutEdges);
1096 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001097 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001098 } else if (Count->UnknownCountInEdge == 0) {
1099 Count->CountValue = sumEdgeCount(Count->InEdges);
1100 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001101 Changes = true;
1102 }
1103 }
Rong Xua5b57452016-12-02 19:10:29 +00001104 if (Count->CountValid) {
1105 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001106 uint64_t Total = 0;
1107 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1108 // If the one of the successor block can early terminate (no-return),
1109 // we can end up with situation where out edge sum count is larger as
1110 // the source BB's count is collected by a post-dominated block.
1111 if (Count->CountValue > OutSum)
1112 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001113 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001114 Changes = true;
1115 }
Rong Xua5b57452016-12-02 19:10:29 +00001116 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001117 uint64_t Total = 0;
1118 uint64_t InSum = sumEdgeCount(Count->InEdges);
1119 if (Count->CountValue > InSum)
1120 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001121 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001122 Changes = true;
1123 }
1124 }
1125 }
1126 }
1127
1128 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001129#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001130 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001131 for (auto &BB : F) {
1132 auto BI = findBBInfo(&BB);
1133 if (BI == nullptr)
1134 continue;
1135 assert(BI->CountValid && "BB count is not valid");
1136 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001137#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001138 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001139 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001140 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001141 for (auto &BB : F) {
1142 auto BI = findBBInfo(&BB);
1143 if (BI == nullptr)
1144 continue;
1145 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1146 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001147 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001148
Rong Xu33308f92016-10-25 21:47:24 +00001149 // Now annotate select instructions
1150 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1151 assert(CountPosition == ProfileCountSize);
1152
Rong Xuf430ae42015-12-09 18:08:16 +00001153 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1154}
1155
1156// Assign the scaled count values to the BB with multiple out edges.
1157void PGOUseFunc::setBranchWeights() {
1158 // Generate MD_prof metadata for every branch instruction.
1159 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001160 for (auto &BB : F) {
1161 TerminatorInst *TI = BB.getTerminator();
1162 if (TI->getNumSuccessors() < 2)
1163 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001164 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1165 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001166 continue;
1167 if (getBBInfo(&BB).CountValue == 0)
1168 continue;
1169
1170 // We have a non-zero Branch BB.
1171 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1172 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001173 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001174 uint64_t MaxCount = 0;
1175 for (unsigned s = 0; s < Size; s++) {
1176 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1177 const BasicBlock *SrcBB = E->SrcBB;
1178 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001179 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001180 continue;
1181 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1182 uint64_t EdgeCount = E->CountValue;
1183 if (EdgeCount > MaxCount)
1184 MaxCount = EdgeCount;
1185 EdgeCounts[SuccNum] = EdgeCount;
1186 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001187 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001188 }
1189}
Rong Xu13b01dc2016-02-10 18:24:45 +00001190
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001191static bool isIndirectBrTarget(BasicBlock *BB) {
1192 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1193 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1194 return true;
1195 }
1196 return false;
1197}
1198
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001199void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1200 DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1201 // Find irr loop headers
1202 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001203 // As a heuristic also annotate indrectbr targets as they have a high chance
1204 // to become an irreducible loop header after the indirectbr tail
1205 // duplication.
1206 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001207 TerminatorInst *TI = BB.getTerminator();
1208 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1209 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1210 }
1211 }
1212}
1213
Xinliang David Li4ca17332016-09-18 18:34:07 +00001214void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1215 Module *M = F.getParent();
1216 IRBuilder<> Builder(&SI);
1217 Type *Int64Ty = Builder.getInt64Ty();
1218 Type *I8PtrTy = Builder.getInt8PtrTy();
1219 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1220 Builder.CreateCall(
1221 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001222 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001223 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1224 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001225 ++(*CurCtrIdx);
1226}
1227
1228void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1229 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1230 assert(*CurCtrIdx < CountFromProfile.size() &&
1231 "Out of bound access of counters");
1232 uint64_t SCounts[2];
1233 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1234 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001235 uint64_t TotalCount = 0;
1236 auto BI = UseFunc->findBBInfo(SI.getParent());
1237 if (BI != nullptr)
1238 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001239 // False Count
1240 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1241 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001242 if (MaxCount)
1243 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001244}
1245
1246void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1247 if (!PGOInstrSelect)
1248 return;
1249 // FIXME: do not handle this yet.
1250 if (SI.getCondition()->getType()->isVectorTy())
1251 return;
1252
Xinliang David Li4ca17332016-09-18 18:34:07 +00001253 switch (Mode) {
1254 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001255 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001256 return;
1257 case VM_instrument:
1258 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001259 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001260 case VM_annotate:
1261 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001262 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001263 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001264
1265 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001266}
1267
Rong Xu60faea12017-03-16 21:15:48 +00001268void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1269 Module *M = F.getParent();
1270 IRBuilder<> Builder(&MI);
1271 Type *Int64Ty = Builder.getInt64Ty();
1272 Type *I8PtrTy = Builder.getInt8PtrTy();
1273 Value *Length = MI.getLength();
1274 assert(!dyn_cast<ConstantInt>(Length));
1275 Builder.CreateCall(
1276 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001277 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001278 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001279 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1280 ++CurCtrId;
1281}
1282
1283void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1284 if (!PGOInstrMemOP)
1285 return;
1286 Value *Length = MI.getLength();
1287 // Not instrument constant length calls.
1288 if (dyn_cast<ConstantInt>(Length))
1289 return;
1290
1291 switch (Mode) {
1292 case VM_counting:
1293 NMemIs++;
1294 return;
1295 case VM_instrument:
1296 instrumentOneMemIntrinsic(MI);
1297 return;
1298 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001299 Candidates.push_back(&MI);
1300 return;
Rong Xu60faea12017-03-16 21:15:48 +00001301 }
1302 llvm_unreachable("Unknown visiting mode");
1303}
1304
Rong Xua3bbf962017-03-15 18:23:39 +00001305// Traverse all valuesites and annotate the instructions for all value kind.
1306void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001307 if (DisableValueProfiling)
1308 return;
1309
Rong Xu8e8fe852016-04-01 16:43:30 +00001310 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001311 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001312
Rong Xua3bbf962017-03-15 18:23:39 +00001313 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001314 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001315}
1316
1317// Annotate the instructions for a specific value kind.
1318void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1319 unsigned ValueSiteIndex = 0;
1320 auto &ValueSites = FuncInfo.ValueSites[Kind];
1321 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1322 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001323 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001324 Ctx.diagnose(DiagnosticInfoPGOProfile(
1325 M->getName().data(),
1326 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1327 " in " + F.getName().str(),
1328 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001329 return;
1330 }
1331
Rong Xua3bbf962017-03-15 18:23:39 +00001332 for (auto &I : ValueSites) {
1333 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1334 << "): Index = " << ValueSiteIndex << " out of "
1335 << NumValueSites << "\n");
1336 annotateValueSite(*M, *I, ProfileRecord,
1337 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001338 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1339 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001340 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001341 }
1342}
Rong Xuf430ae42015-12-09 18:08:16 +00001343
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001344// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001345// aware this is an ir_level profile so it can set the version flag.
1346static void createIRLevelProfileFlagVariable(Module &M) {
1347 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1348 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001349 auto IRLevelVersionVariable = new GlobalVariable(
1350 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1351 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001352 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001353 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1354 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001355 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001356 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001357 else
Rong Xu9e926e82016-02-29 19:16:04 +00001358 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001359 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001360}
1361
Rong Xu705f7772016-07-25 18:45:37 +00001362// Collect the set of members for each Comdat in module M and store
1363// in ComdatMembers.
1364static void collectComdatMembers(
1365 Module &M,
1366 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1367 if (!DoComdatRenaming)
1368 return;
1369 for (Function &F : M)
1370 if (Comdat *C = F.getComdat())
1371 ComdatMembers.insert(std::make_pair(C, &F));
1372 for (GlobalVariable &GV : M.globals())
1373 if (Comdat *C = GV.getComdat())
1374 ComdatMembers.insert(std::make_pair(C, &GV));
1375 for (GlobalAlias &GA : M.aliases())
1376 if (Comdat *C = GA.getComdat())
1377 ComdatMembers.insert(std::make_pair(C, &GA));
1378}
1379
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001380static bool InstrumentAllFunctions(
Xinliang David Lid91057b2017-12-08 19:38:07 +00001381 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1382 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001383 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001384 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1385 collectComdatMembers(M, ComdatMembers);
1386
Rong Xuf430ae42015-12-09 18:08:16 +00001387 for (auto &F : M) {
1388 if (F.isDeclaration())
1389 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001390 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001391 auto *BFI = LookupBFI(F);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001392 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001393 }
1394 return true;
1395}
1396
Xinliang David Li8aebf442016-05-06 05:49:19 +00001397bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001398 if (skipModule(M))
1399 return false;
1400
Xinliang David Lid91057b2017-12-08 19:38:07 +00001401 auto LookupBPI = [this](Function &F) {
1402 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1403 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001404 auto LookupBFI = [this](Function &F) {
1405 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001406 };
Xinliang David Lid91057b2017-12-08 19:38:07 +00001407 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001408}
1409
Xinliang David Li8aebf442016-05-06 05:49:19 +00001410PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001411 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001412 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001413 auto LookupBPI = [&FAM](Function &F) {
1414 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1415 };
Xinliang David Li8aebf442016-05-06 05:49:19 +00001416
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001417 auto LookupBFI = [&FAM](Function &F) {
1418 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001419 };
1420
Xinliang David Lid91057b2017-12-08 19:38:07 +00001421 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001422 return PreservedAnalyses::all();
1423
1424 return PreservedAnalyses::none();
1425}
1426
Xinliang David Lida195582016-05-10 21:59:52 +00001427static bool annotateAllFunctions(
1428 Module &M, StringRef ProfileFileName,
Xinliang David Lid91057b2017-12-08 19:38:07 +00001429 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Li45c81902017-12-05 21:54:01 +00001430 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001431 DEBUG(dbgs() << "Read in profile counters: ");
1432 auto &Ctx = M.getContext();
1433 // Read the counter array from file.
1434 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001435 if (Error E = ReaderOrErr.takeError()) {
1436 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1437 Ctx.diagnose(
1438 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1439 });
Rong Xuf430ae42015-12-09 18:08:16 +00001440 return false;
1441 }
1442
Xinliang David Lida195582016-05-10 21:59:52 +00001443 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1444 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001445 if (!PGOReader) {
1446 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001447 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001448 return false;
1449 }
Rong Xu33c76c02016-02-10 17:18:30 +00001450 // TODO: might need to change the warning once the clang option is finalized.
1451 if (!PGOReader->isIRLevelProfile()) {
1452 Ctx.diagnose(DiagnosticInfoPGOProfile(
1453 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1454 return false;
1455 }
1456
Rong Xu705f7772016-07-25 18:45:37 +00001457 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1458 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001459 std::vector<Function *> HotFunctions;
1460 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001461 for (auto &F : M) {
1462 if (F.isDeclaration())
1463 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001464 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001465 auto *BFI = LookupBFI(F);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001466 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001467 if (!Func.readCounters(PGOReader.get()))
1468 continue;
1469 Func.populateCounters();
1470 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001471 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001472 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001473 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1474 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001475 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001476 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1477 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001478 if (PGOViewCounts != PGOVCT_None &&
1479 (ViewBlockFreqFuncName.empty() ||
1480 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001481 LoopInfo LI{DominatorTree(F)};
1482 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1483 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1484 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1485 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001486 if (PGOViewCounts == PGOVCT_Graph)
1487 NewBFI->view();
1488 else if (PGOViewCounts == PGOVCT_Text) {
1489 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1490 NewBFI->print(dbgs());
1491 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001492 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001493 if (PGOViewRawCounts != PGOVCT_None &&
1494 (ViewBlockFreqFuncName.empty() ||
1495 F.getName().equals(ViewBlockFreqFuncName))) {
1496 if (PGOViewRawCounts == PGOVCT_Graph)
1497 if (ViewBlockFreqFuncName.empty())
1498 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1499 else
1500 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1501 else if (PGOViewRawCounts == PGOVCT_Text) {
1502 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1503 Func.dumpInfo();
1504 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001505 }
Rong Xuf430ae42015-12-09 18:08:16 +00001506 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001507 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001508 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001509 // We have to apply these attributes at the end because their presence
1510 // can affect the BranchProbabilityInfo of any callers, resulting in an
1511 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001512 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001513 F->addFnAttr(Attribute::InlineHint);
Rong Xu6090afd2016-03-28 17:08:56 +00001514 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1515 << "\n");
1516 }
1517 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001518 F->addFnAttr(Attribute::Cold);
Rong Xu6090afd2016-03-28 17:08:56 +00001519 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1520 }
Rong Xuf430ae42015-12-09 18:08:16 +00001521 return true;
1522}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001523
Xinliang David Lida195582016-05-10 21:59:52 +00001524PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001525 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001526 if (!PGOTestProfileFile.empty())
1527 ProfileFileName = PGOTestProfileFile;
1528}
1529
1530PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001531 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001532
1533 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001534 auto LookupBPI = [&FAM](Function &F) {
1535 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1536 };
Xinliang David Lida195582016-05-10 21:59:52 +00001537
1538 auto LookupBFI = [&FAM](Function &F) {
1539 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1540 };
1541
Xinliang David Lid91057b2017-12-08 19:38:07 +00001542 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
Xinliang David Lida195582016-05-10 21:59:52 +00001543 return PreservedAnalyses::all();
1544
1545 return PreservedAnalyses::none();
1546}
1547
Xinliang David Lid55827f2016-05-07 05:39:12 +00001548bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1549 if (skipModule(M))
1550 return false;
1551
Xinliang David Lid91057b2017-12-08 19:38:07 +00001552 auto LookupBPI = [this](Function &F) {
1553 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1554 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001555 auto LookupBFI = [this](Function &F) {
1556 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001557 };
1558
Xinliang David Lid91057b2017-12-08 19:38:07 +00001559 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001560}
Xinliang David Lid289e452017-01-27 19:06:25 +00001561
Eugene Zelenkofce43572017-10-21 00:57:46 +00001562static std::string getSimpleNodeName(const BasicBlock *Node) {
1563 if (!Node->getName().empty())
1564 return Node->getName();
1565
1566 std::string SimpleNodeName;
1567 raw_string_ostream OS(SimpleNodeName);
1568 Node->printAsOperand(OS, false);
1569 return OS.str();
1570}
1571
1572void llvm::setProfMetadata(Module *M, Instruction *TI,
1573 ArrayRef<uint64_t> EdgeCounts,
1574 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001575 MDBuilder MDB(M->getContext());
1576 assert(MaxCount > 0 && "Bad max count");
1577 uint64_t Scale = calculateCountScale(MaxCount);
1578 SmallVector<unsigned, 4> Weights;
1579 for (const auto &ECI : EdgeCounts)
1580 Weights.push_back(scaleBranchCount(ECI, Scale));
1581
1582 DEBUG(dbgs() << "Weight is: ";
1583 for (const auto &W : Weights) { dbgs() << W << " "; }
1584 dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001585 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001586 if (EmitBranchProbability) {
1587 std::string BrCondStr = getBranchCondString(TI);
1588 if (BrCondStr.empty())
1589 return;
1590
1591 unsigned WSum =
1592 std::accumulate(Weights.begin(), Weights.end(), 0,
1593 [](unsigned w1, unsigned w2) { return w1 + w2; });
1594 uint64_t TotalCount =
1595 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1596 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1597 BranchProbability BP(Weights[0], WSum);
1598 std::string BranchProbStr;
1599 raw_string_ostream OS(BranchProbStr);
1600 OS << BP;
1601 OS << " (total count : " << TotalCount << ")";
1602 OS.flush();
1603 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001604 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001605 ORE.emit([&]() {
1606 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1607 << BrCondStr << " is true with probability : " << BranchProbStr;
1608 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001609 }
Rong Xu48596b62017-04-04 16:42:20 +00001610}
1611
Eugene Zelenkofce43572017-10-21 00:57:46 +00001612namespace llvm {
1613
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001614void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1615 MDBuilder MDB(M->getContext());
1616 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1617 MDB.createIrrLoopHeaderWeight(Count));
1618}
1619
Xinliang David Lid289e452017-01-27 19:06:25 +00001620template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001621 using NodeRef = const BasicBlock *;
1622 using ChildIteratorType = succ_const_iterator;
1623 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001624
1625 static NodeRef getEntryNode(const PGOUseFunc *G) {
1626 return &G->getFunc().front();
1627 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001628
Xinliang David Lid289e452017-01-27 19:06:25 +00001629 static ChildIteratorType child_begin(const NodeRef N) {
1630 return succ_begin(N);
1631 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001632
Xinliang David Lid289e452017-01-27 19:06:25 +00001633 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001634
Xinliang David Lid289e452017-01-27 19:06:25 +00001635 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1636 return nodes_iterator(G->getFunc().begin());
1637 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001638
Xinliang David Lid289e452017-01-27 19:06:25 +00001639 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1640 return nodes_iterator(G->getFunc().end());
1641 }
1642};
1643
1644template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1645 explicit DOTGraphTraits(bool isSimple = false)
1646 : DefaultDOTGraphTraits(isSimple) {}
1647
1648 static std::string getGraphName(const PGOUseFunc *G) {
1649 return G->getFunc().getName();
1650 }
1651
1652 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1653 std::string Result;
1654 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001655
1656 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001657 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001658 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001659 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001660 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001661 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001662 OS << "Unknown\\l";
1663
1664 if (!PGOInstrSelect)
1665 return Result;
1666
1667 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1668 auto *I = &*BI;
1669 if (!isa<SelectInst>(I))
1670 continue;
1671 // Display scaled counts for SELECT instruction:
1672 OS << "SELECT : { T = ";
1673 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001674 bool HasProf = I->extractProfMetadata(TC, FC);
1675 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001676 OS << "Unknown, F = Unknown }\\l";
1677 else
1678 OS << TC << ", F = " << FC << " }\\l";
1679 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001680 return Result;
1681 }
1682};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001683
1684} // end namespace llvm