blob: 876ae23dfd29db28875eec38573d6d53751e0c89 [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
David Blaikie4fe1fe12018-03-23 22:11:06 +000051#include "llvm/Transforms/Instrumentation/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;
Easwaran Ramane5b8de22018-01-17 22:24:23 +0000122using ProfileCount = Function::ProfileCount;
Rong Xuf430ae42015-12-09 18:08:16 +0000123
124#define DEBUG_TYPE "pgo-instrumentation"
125
126STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000127STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +0000128STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +0000129STATISTIC(NumOfPGOEdge, "Number of edges.");
130STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
131STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
132STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
133STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
134STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000135STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000136
137// Command line option to specify the file to read profile from. This is
138// mainly used for testing.
139static cl::opt<std::string>
140 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
141 cl::value_desc("filename"),
142 cl::desc("Specify the path of profile data file. This is"
143 "mainly for test purpose."));
Richard Smith6c676622018-10-10 23:13:47 +0000144static cl::opt<std::string> PGOTestProfileRemappingFile(
145 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
146 cl::value_desc("filename"),
147 cl::desc("Specify the path of profile remapping file. This is mainly for "
148 "test purpose."));
Rong Xuf430ae42015-12-09 18:08:16 +0000149
Rong Xuecdc98f2016-03-04 22:08:44 +0000150// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000151// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000152static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
153 cl::Hidden,
154 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000155
Rong Xuecdc98f2016-03-04 22:08:44 +0000156// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000157// the metadata for a single indirect call callsite.
158static cl::opt<unsigned> MaxNumAnnotations(
159 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
160 cl::desc("Max number of annotations for a single indirect "
161 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000162
Rong Xue60343d2017-03-17 18:07:26 +0000163// Command line option to set the maximum number of value annotations
164// to write to the metadata for a single memop intrinsic.
165static cl::opt<unsigned> MaxNumMemOPAnnotations(
166 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
167 cl::desc("Max number of preicise value annotations for a single memop"
168 "intrinsic"));
169
Rong Xu705f7772016-07-25 18:45:37 +0000170// Command line option to control appending FunctionHash to the name of a COMDAT
171// function. This is to avoid the hash mismatch caused by the preinliner.
172static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000173 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000174 cl::desc("Append function hash to the name of COMDAT function to avoid "
175 "function hash mismatch due to the preinliner"));
176
Rong Xu0698de92016-05-13 17:26:06 +0000177// Command line option to enable/disable the warning about missing profile
178// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000179static cl::opt<bool>
180 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
181 cl::desc("Use this option to turn on/off "
182 "warnings about missing profile data for "
183 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000184
185// Command line option to enable/disable the warning about a hash mismatch in
186// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000187static cl::opt<bool>
188 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
189 cl::desc("Use this option to turn off/on "
190 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000191
Rong Xu20f5df12017-01-11 20:19:41 +0000192// Command line option to enable/disable the warning about a hash mismatch in
193// the profile data for Comdat functions, which often turns out to be false
194// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000195static cl::opt<bool>
196 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
197 cl::Hidden,
198 cl::desc("The option is used to turn on/off "
199 "warnings about hash mismatch for comdat "
200 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000201
Xinliang David Li4ca17332016-09-18 18:34:07 +0000202// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000203static cl::opt<bool>
204 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
205 cl::desc("Use this option to turn on/off SELECT "
206 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000207
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000208// Command line option to turn on CFG dot or text dump of raw profile counts
209static cl::opt<PGOViewCountsType> PGOViewRawCounts(
210 "pgo-view-raw-counts", cl::Hidden,
211 cl::desc("A boolean option to show CFG dag or text "
212 "with raw profile counts from "
213 "profile data. See also option "
214 "-pgo-view-counts. To limit graph "
215 "display to only one function, use "
216 "filtering option -view-bfi-func-name."),
217 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
218 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
219 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000220
Rong Xu8e06e802017-03-17 20:51:44 +0000221// Command line option to enable/disable memop intrinsic call.size profiling.
222static cl::opt<bool>
223 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
224 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000225 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000226
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000227// Emit branch probability as optimization remarks.
228static cl::opt<bool>
229 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
230 cl::desc("When this option is on, the annotated "
231 "branch probability will be emitted as "
Rong Xu662f38b2018-03-27 18:55:56 +0000232 "optimization remarks: -{Rpass|"
233 "pass-remarks}=pgo-instrumentation"));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000234
Xinliang David Licb253ce2017-01-23 18:58:24 +0000235// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000236// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000237extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000238
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000239// Command line option to specify the name of the function for CFG dump
240// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
241extern cl::opt<std::string> ViewBlockFreqFuncName;
242
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000243// Return a string describing the branch condition that can be
244// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000245static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000246 BranchInst *BI = dyn_cast<BranchInst>(TI);
247 if (!BI || !BI->isConditional())
248 return std::string();
249
250 Value *Cond = BI->getCondition();
251 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
252 if (!CI)
253 return std::string();
254
255 std::string result;
256 raw_string_ostream OS(result);
257 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
258 CI->getOperand(0)->getType()->print(OS, true);
259
260 Value *RHS = CI->getOperand(1);
261 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
262 if (CV) {
263 if (CV->isZero())
264 OS << "_Zero";
265 else if (CV->isOne())
266 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000267 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000268 OS << "_MinusOne";
269 else
270 OS << "_Const";
271 }
272 OS.flush();
273 return result;
274}
275
Eugene Zelenkofce43572017-10-21 00:57:46 +0000276namespace {
277
Xinliang David Li4ca17332016-09-18 18:34:07 +0000278/// The select instruction visitor plays three roles specified
279/// by the mode. In \c VM_counting mode, it simply counts the number of
280/// select instructions. In \c VM_instrument mode, it inserts code to count
281/// the number times TrueValue of select is taken. In \c VM_annotate mode,
282/// it reads the profile data and annotate the select instruction with metadata.
283enum VisitMode { VM_counting, VM_instrument, VM_annotate };
284class PGOUseFunc;
285
286/// Instruction Visitor class to visit select instructions.
287struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
288 Function &F;
289 unsigned NSIs = 0; // Number of select instructions instrumented.
290 VisitMode Mode = VM_counting; // Visiting mode.
291 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
292 unsigned TotalNumCtrs = 0; // Total number of counters
293 GlobalVariable *FuncNameVar = nullptr;
294 uint64_t FuncHash = 0;
295 PGOUseFunc *UseFunc = nullptr;
296
297 SelectInstVisitor(Function &Func) : F(Func) {}
298
299 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000300 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000301 Mode = VM_counting;
302 visit(Func);
303 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000304
Xinliang David Li4ca17332016-09-18 18:34:07 +0000305 // Visit the IR stream and instrument all select instructions. \p
306 // Ind is a pointer to the counter index variable; \p TotalNC
307 // is the total number of counters; \p FNV is the pointer to the
308 // PGO function name var; \p FHash is the function hash.
309 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
310 GlobalVariable *FNV, uint64_t FHash) {
311 Mode = VM_instrument;
312 CurCtrIdx = Ind;
313 TotalNumCtrs = TotalNC;
314 FuncHash = FHash;
315 FuncNameVar = FNV;
316 visit(Func);
317 }
318
319 // Visit the IR stream and annotate all select instructions.
320 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
321 Mode = VM_annotate;
322 UseFunc = UF;
323 CurCtrIdx = Ind;
324 visit(Func);
325 }
326
327 void instrumentOneSelectInst(SelectInst &SI);
328 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000329
Xinliang David Li4ca17332016-09-18 18:34:07 +0000330 // Visit \p SI instruction and perform tasks according to visit mode.
331 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000332
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000333 // Return the number of select instructions. This needs be called after
334 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000335 unsigned getNumOfSelectInsts() const { return NSIs; }
336};
337
Rong Xu60faea12017-03-16 21:15:48 +0000338/// Instruction Visitor class to visit memory intrinsic calls.
339struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
340 Function &F;
341 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
342 VisitMode Mode = VM_counting; // Visiting mode.
343 unsigned CurCtrId = 0; // Current counter index.
344 unsigned TotalNumCtrs = 0; // Total number of counters
345 GlobalVariable *FuncNameVar = nullptr;
346 uint64_t FuncHash = 0;
347 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000348 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000349
350 MemIntrinsicVisitor(Function &Func) : F(Func) {}
351
352 void countMemIntrinsics(Function &Func) {
353 NMemIs = 0;
354 Mode = VM_counting;
355 visit(Func);
356 }
Rong Xue60343d2017-03-17 18:07:26 +0000357
Rong Xu60faea12017-03-16 21:15:48 +0000358 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
359 GlobalVariable *FNV, uint64_t FHash) {
360 Mode = VM_instrument;
361 TotalNumCtrs = TotalNC;
362 FuncHash = FHash;
363 FuncNameVar = FNV;
364 visit(Func);
365 }
366
Rong Xue60343d2017-03-17 18:07:26 +0000367 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
368 Candidates.clear();
369 Mode = VM_annotate;
370 visit(Func);
371 return Candidates;
372 }
373
Rong Xu60faea12017-03-16 21:15:48 +0000374 // Visit the IR stream and annotate all mem intrinsic call instructions.
375 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000376
Rong Xu60faea12017-03-16 21:15:48 +0000377 // Visit \p MI instruction and perform tasks according to visit mode.
378 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000379
Rong Xu60faea12017-03-16 21:15:48 +0000380 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
381};
382
Xinliang David Li8aebf442016-05-06 05:49:19 +0000383class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000384public:
385 static char ID;
386
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000387 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000388 initializePGOInstrumentationGenLegacyPassPass(
389 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000390 }
391
Mehdi Amini117296c2016-10-01 02:56:57 +0000392 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000393
394private:
395 bool runOnModule(Module &M) override;
396
397 void getAnalysisUsage(AnalysisUsage &AU) const override {
398 AU.addRequired<BlockFrequencyInfoWrapperPass>();
399 }
400};
401
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000403public:
404 static char ID;
405
406 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000407 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000408 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000409 if (!PGOTestProfileFile.empty())
410 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000411 initializePGOInstrumentationUseLegacyPassPass(
412 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000413 }
414
Mehdi Amini117296c2016-10-01 02:56:57 +0000415 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000416
417private:
418 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000419
Xinliang David Lida195582016-05-10 21:59:52 +0000420 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000421
Rong Xuf430ae42015-12-09 18:08:16 +0000422 void getAnalysisUsage(AnalysisUsage &AU) const override {
423 AU.addRequired<BlockFrequencyInfoWrapperPass>();
424 }
425};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000426
Rong Xuf430ae42015-12-09 18:08:16 +0000427} // end anonymous namespace
428
Xinliang David Li8aebf442016-05-06 05:49:19 +0000429char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000430
Xinliang David Li8aebf442016-05-06 05:49:19 +0000431INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000432 "PGO instrumentation.", false, false)
433INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000434INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000435INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000436 "PGO instrumentation.", false, false)
437
Xinliang David Li8aebf442016-05-06 05:49:19 +0000438ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
439 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000440}
441
Xinliang David Lid55827f2016-05-07 05:39:12 +0000442char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000443
Xinliang David Lid55827f2016-05-07 05:39:12 +0000444INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000445 "Read PGO instrumentation profile.", false, false)
446INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000447INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000448INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000449 "Read PGO instrumentation profile.", false, false)
450
Xinliang David Lid55827f2016-05-07 05:39:12 +0000451ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
452 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000453}
454
455namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000456
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000457/// An MST based instrumentation for PGO
Rong Xuf430ae42015-12-09 18:08:16 +0000458///
459/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
460/// in the function level.
461struct PGOEdge {
462 // This class implements the CFG edges. Note the CFG can be a multi-graph.
463 // So there might be multiple edges with same SrcBB and DestBB.
464 const BasicBlock *SrcBB;
465 const BasicBlock *DestBB;
466 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000467 bool InMST = false;
468 bool Removed = false;
469 bool IsCritical = false;
470
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000471 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000472 : SrcBB(Src), DestBB(Dest), Weight(W) {}
473
Rong Xuf430ae42015-12-09 18:08:16 +0000474 // Return the information string of an edge.
475 const std::string infoString() const {
476 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
477 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
478 }
479};
480
481// This class stores the auxiliary information for each BB.
482struct BBInfo {
483 BBInfo *Group;
484 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000485 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000486
Eugene Zelenkofce43572017-10-21 00:57:46 +0000487 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000488
489 // Return the information string of this object.
490 const std::string infoString() const {
491 return (Twine("Index=") + Twine(Index)).str();
492 }
493};
494
495// This class implements the CFG edges. Note the CFG can be a multi-graph.
496template <class Edge, class BBInfo> class FuncPGOInstrumentation {
497private:
498 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000499
Rong Xu705f7772016-07-25 18:45:37 +0000500 // A map that stores the Comdat group in function F.
501 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000502
Eugene Zelenkofce43572017-10-21 00:57:46 +0000503 void computeCFGHash();
504 void renameComdatFunction();
505
Rong Xuf430ae42015-12-09 18:08:16 +0000506public:
Rong Xua3bbf962017-03-15 18:23:39 +0000507 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000508 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000509 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000510 std::string FuncName;
511 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000512
Rong Xuf430ae42015-12-09 18:08:16 +0000513 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000514 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000515
516 // The Minimum Spanning Tree of function CFG.
517 CFGMST<Edge, BBInfo> MST;
518
519 // Give an edge, find the BB that will be instrumented.
520 // Return nullptr if there is no BB to be instrumented.
521 BasicBlock *getInstrBB(Edge *E);
522
523 // Return the auxiliary BB information.
524 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
525
Rong Xua5b57452016-12-02 19:10:29 +0000526 // Return the auxiliary BB information if available.
527 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
528
Rong Xuf430ae42015-12-09 18:08:16 +0000529 // Dump edges and BB information.
530 void dumpInfo(std::string Str = "") const {
531 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000532 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000533 }
534
Rong Xu705f7772016-07-25 18:45:37 +0000535 FuncPGOInstrumentation(
536 Function &Func,
537 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000538 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
539 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000540 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000541 SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000542 // This should be done before CFG hash computation.
543 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000544 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000545 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000546 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000547 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000548 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000549
Rong Xuf430ae42015-12-09 18:08:16 +0000550 FuncName = getPGOFuncName(F);
551 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000552 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000553 renameComdatFunction();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dumpInfo("after CFGMST"));
Rong Xuf430ae42015-12-09 18:08:16 +0000555
556 NumOfPGOBB += MST.BBInfos.size();
557 for (auto &E : MST.AllEdges) {
558 if (E->Removed)
559 continue;
560 NumOfPGOEdge++;
561 if (!E->InMST)
562 NumOfPGOInstrument++;
563 }
564
565 if (CreateGlobalVar)
566 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000567 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000568
569 // Return the number of profile counters needed for the function.
570 unsigned getNumCounters() {
571 unsigned NumCounters = 0;
572 for (auto &E : this->MST.AllEdges) {
573 if (!E->InMST && !E->Removed)
574 NumCounters++;
575 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000576 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000577 }
Rong Xuf430ae42015-12-09 18:08:16 +0000578};
579
Eugene Zelenkofce43572017-10-21 00:57:46 +0000580} // end anonymous namespace
581
Rong Xuf430ae42015-12-09 18:08:16 +0000582// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
583// value of each BB in the CFG. The higher 32 bits record the number of edges.
584template <class Edge, class BBInfo>
585void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
586 std::vector<char> Indexes;
587 JamCRC JC;
588 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000589 const Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000590 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
591 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000592 auto BI = findBBInfo(Succ);
593 if (BI == nullptr)
594 continue;
595 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000596 for (int J = 0; J < 4; J++)
597 Indexes.push_back((char)(Index >> (J * 8)));
598 }
599 }
600 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000601 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000602 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000603 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000604 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
605 << " CRC = " << JC.getCRC()
606 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
607 << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
608 << ValueSites[IPVK_IndirectCallTarget].size()
609 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000610}
611
612// Check if we can safely rename this Comdat function.
613static bool canRenameComdat(
614 Function &F,
615 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000616 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000617 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000618
619 // FIXME: Current only handle those Comdat groups that only containing one
620 // function and function aliases.
621 // (1) For a Comdat group containing multiple functions, we need to have a
622 // unique postfix based on the hashes for each function. There is a
623 // non-trivial code refactoring to do this efficiently.
624 // (2) Variables can not be renamed, so we can not rename Comdat function in a
625 // group including global vars.
626 Comdat *C = F.getComdat();
627 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
628 if (dyn_cast<GlobalAlias>(CM.second))
629 continue;
630 Function *FM = dyn_cast<Function>(CM.second);
631 if (FM != &F)
632 return false;
633 }
634 return true;
635}
636
637// Append the CFGHash to the Comdat function name.
638template <class Edge, class BBInfo>
639void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
640 if (!canRenameComdat(F, ComdatMembers))
641 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000642 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000643 std::string NewFuncName =
644 Twine(F.getName() + "." + Twine(FunctionHash)).str();
645 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000646 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000647 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
648 Comdat *NewComdat;
649 Module *M = F.getParent();
650 // For AvailableExternallyLinkage functions, change the linkage to
651 // LinkOnceODR and put them into comdat. This is because after renaming, there
652 // is no backup external copy available for the function.
653 if (!F.hasComdat()) {
654 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
655 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
656 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
657 F.setComdat(NewComdat);
658 return;
659 }
660
661 // This function belongs to a single function Comdat group.
662 Comdat *OrigComdat = F.getComdat();
663 std::string NewComdatName =
664 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
665 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
666 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
667
668 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
669 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
670 // For aliases, change the name directly.
671 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000672 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000673 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000674 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000675 continue;
676 }
677 // Must be a function.
678 Function *CF = dyn_cast<Function>(CM.second);
679 assert(CF);
680 CF->setComdat(NewComdat);
681 }
Rong Xuf430ae42015-12-09 18:08:16 +0000682}
683
684// Given a CFG E to be instrumented, find which BB to place the instrumented
685// code. The function will split the critical edge if necessary.
686template <class Edge, class BBInfo>
687BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
688 if (E->InMST || E->Removed)
689 return nullptr;
690
691 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
692 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
693 // For a fake edge, instrument the real BB.
694 if (SrcBB == nullptr)
695 return DestBB;
696 if (DestBB == nullptr)
697 return SrcBB;
698
699 // Instrument the SrcBB if it has a single successor,
700 // otherwise, the DestBB if this is not a critical edge.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000701 Instruction *TI = SrcBB->getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000702 if (TI->getNumSuccessors() <= 1)
703 return SrcBB;
704 if (!E->IsCritical)
705 return DestBB;
706
707 // For a critical edge, we have to split. Instrument the newly
708 // created BB.
709 NumOfPGOSplit++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000710 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
711 << " --> " << getBBInfo(DestBB).Index << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000712 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
713 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
714 assert(InstrBB && "Critical edge is not split");
715
716 E->Removed = true;
717 return InstrBB;
718}
719
Rong Xued9fec72016-01-21 18:11:44 +0000720// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000721// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000722static void instrumentOneFunc(
Xinliang David Lid91057b2017-12-08 19:38:07 +0000723 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Rong Xu705f7772016-07-25 18:45:37 +0000724 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000725 // Split indirectbr critical edges here before computing the MST rather than
726 // later in getInstrBB() to avoid invalidating it.
727 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +0000728 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
729 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000730 unsigned NumCounters = FuncInfo.getNumCounters();
731
Rong Xuf430ae42015-12-09 18:08:16 +0000732 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000733 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000734 for (auto &E : FuncInfo.MST.AllEdges) {
735 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
736 if (!InstrBB)
737 continue;
738
739 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
740 assert(Builder.GetInsertPoint() != InstrBB->end() &&
741 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000742 Builder.CreateCall(
743 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000744 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000745 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
746 Builder.getInt32(I++)});
747 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000748
749 // Now instrument select instructions:
750 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
751 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000752 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000753
754 if (DisableValueProfiling)
755 return;
756
757 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000758 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000759 CallSite CS(I);
760 Value *Callee = CS.getCalledValue();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000761 LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
762 << NumIndirectCallSites << "\n");
Rong Xued9fec72016-01-21 18:11:44 +0000763 IRBuilder<> Builder(I);
764 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
765 "Cannot get the Instrumentation point");
766 Builder.CreateCall(
767 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000768 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000769 Builder.getInt64(FuncInfo.FunctionHash),
770 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000771 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000772 Builder.getInt32(NumIndirectCallSites++)});
773 }
774 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000775
776 // Now instrument memop intrinsic calls.
777 FuncInfo.MIVisitor.instrumentMemIntrinsics(
778 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000779}
780
Eugene Zelenkofce43572017-10-21 00:57:46 +0000781namespace {
782
Rong Xuf430ae42015-12-09 18:08:16 +0000783// This class represents a CFG edge in profile use compilation.
784struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000785 bool CountValid = false;
786 uint64_t CountValue = 0;
787
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000788 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000789 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000790
791 // Set edge count value
792 void setEdgeCount(uint64_t Value) {
793 CountValue = Value;
794 CountValid = true;
795 }
796
797 // Return the information string for this object.
798 const std::string infoString() const {
799 if (!CountValid)
800 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000801 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
802 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000803 }
804};
805
Eugene Zelenkofce43572017-10-21 00:57:46 +0000806using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000807
808// This class stores the auxiliary information for each BB.
809struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000810 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000811 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000812 int32_t UnknownCountInEdge = 0;
813 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000814 DirectEdges InEdges;
815 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000816
817 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
818
Rong Xuf430ae42015-12-09 18:08:16 +0000819 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000820 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000821
822 // Set the profile count value for this BB.
823 void setBBInfoCount(uint64_t Value) {
824 CountValue = Value;
825 CountValid = true;
826 }
827
828 // Return the information string of this object.
829 const std::string infoString() const {
830 if (!CountValid)
831 return BBInfo::infoString();
832 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
833 }
834};
835
Eugene Zelenkofce43572017-10-21 00:57:46 +0000836} // end anonymous namespace
837
Rong Xuf430ae42015-12-09 18:08:16 +0000838// Sum up the count values for all the edges.
839static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
840 uint64_t Total = 0;
841 for (auto &E : Edges) {
842 if (E->Removed)
843 continue;
844 Total += E->CountValue;
845 }
846 return Total;
847}
848
Eugene Zelenkofce43572017-10-21 00:57:46 +0000849namespace {
850
Rong Xuf430ae42015-12-09 18:08:16 +0000851class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000852public:
Rong Xu705f7772016-07-25 18:45:37 +0000853 PGOUseFunc(Function &Func, Module *Modu,
854 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000855 BranchProbabilityInfo *BPI = nullptr,
Xinliang David Li45c81902017-12-05 21:54:01 +0000856 BlockFrequencyInfo *BFIin = nullptr)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000857 : F(Func), M(Modu), BFI(BFIin),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000858 FuncInfo(Func, ComdatMembers, false, BPI, BFIin),
859 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000860
861 // Read counts for the instrumented BB from profile.
Rong Xufb4bcc42018-11-07 23:51:20 +0000862 bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros);
Rong Xu6090afd2016-03-28 17:08:56 +0000863
864 // Populate the counts for all BBs.
865 void populateCounters();
866
867 // Set the branch weights based on the count values.
868 void setBranchWeights();
869
Hiroshi Inoueae179002018-04-14 08:59:00 +0000870 // Annotate the value profile call sites for all value kind.
Rong Xua3bbf962017-03-15 18:23:39 +0000871 void annotateValueSites();
872
873 // Annotate the value profile call sites for one value kind.
874 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000875
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000876 // Annotate the irreducible loop header weights.
877 void annotateIrrLoopHeaderWeights();
878
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000879 // The hotness of the function from the profile count.
880 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
881
882 // Return the function hotness from the profile.
883 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
884
Rong Xu705f7772016-07-25 18:45:37 +0000885 // Return the function hash.
886 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000887
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000888 // Return the profile record for this function;
889 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
890
Xinliang David Li4ca17332016-09-18 18:34:07 +0000891 // Return the auxiliary BB information.
892 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
893 return FuncInfo.getBBInfo(BB);
894 }
895
Rong Xua5b57452016-12-02 19:10:29 +0000896 // Return the auxiliary BB information if available.
897 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
898 return FuncInfo.findBBInfo(BB);
899 }
900
Xinliang David Lid289e452017-01-27 19:06:25 +0000901 Function &getFunc() const { return F; }
902
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000903 void dumpInfo(std::string Str = "") const {
904 FuncInfo.dumpInfo(Str);
905 }
906
Rong Xufb4bcc42018-11-07 23:51:20 +0000907 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
Rong Xuf430ae42015-12-09 18:08:16 +0000908private:
909 Function &F;
910 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000911 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000912
Rong Xuf430ae42015-12-09 18:08:16 +0000913 // This member stores the shared information with class PGOGenFunc.
914 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
915
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000916 // The maximum count value in the profile. This is only used in PGO use
917 // compilation.
918 uint64_t ProgramMaxCount;
919
Rong Xu33308f92016-10-25 21:47:24 +0000920 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000921 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000922
923 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000924 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000925
Rong Xu13b01dc2016-02-10 18:24:45 +0000926 // ProfileRecord for this function.
927 InstrProfRecord ProfileRecord;
928
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000929 // Function hotness info derived from profile.
930 FuncFreqAttr FreqAttr;
931
Rong Xuf430ae42015-12-09 18:08:16 +0000932 // Find the Instrumented BB and set the value.
933 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
934
935 // Set the edge counter value for the unknown edge -- there should be only
936 // one unknown edge.
937 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
938
939 // Return FuncName string;
940 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000941
942 // Set the hot/cold inline hints based on the count values.
943 // FIXME: This function should be removed once the functionality in
944 // the inliner is implemented.
945 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
946 if (ProgramMaxCount == 0)
947 return;
948 // Threshold of the hot functions.
949 const BranchProbability HotFunctionThreshold(1, 100);
950 // Threshold of the cold functions.
951 const BranchProbability ColdFunctionThreshold(2, 10000);
952 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
953 FreqAttr = FFA_Hot;
954 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
955 FreqAttr = FFA_Cold;
956 }
Rong Xuf430ae42015-12-09 18:08:16 +0000957};
958
Eugene Zelenkofce43572017-10-21 00:57:46 +0000959} // end anonymous namespace
960
Rong Xuf430ae42015-12-09 18:08:16 +0000961// Visit all the edges and assign the count value for the instrumented
962// edges and the BB.
963void PGOUseFunc::setInstrumentedCounts(
964 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +0000965 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000966 // Use a worklist as we will update the vector during the iteration.
967 std::vector<PGOUseEdge *> WorkList;
968 for (auto &E : FuncInfo.MST.AllEdges)
969 WorkList.push_back(E.get());
970
971 uint32_t I = 0;
972 for (auto &E : WorkList) {
973 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
974 if (!InstrBB)
975 continue;
976 uint64_t CountValue = CountFromProfile[I++];
977 if (!E->Removed) {
978 getBBInfo(InstrBB).setBBInfoCount(CountValue);
979 E->setEdgeCount(CountValue);
980 continue;
981 }
982
983 // Need to add two new edges.
984 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
985 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
986 // Add new edge of SrcBB->InstrBB.
987 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
988 NewEdge.setEdgeCount(CountValue);
989 // Add new edge of InstrBB->DestBB.
990 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
991 NewEdge1.setEdgeCount(CountValue);
992 NewEdge1.InMST = true;
993 getBBInfo(InstrBB).setBBInfoCount(CountValue);
994 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000995 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000996 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000997}
998
999// Set the count value for the unknown edge. There should be one and only one
1000// unknown edge in Edges vector.
1001void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1002 for (auto &E : Edges) {
1003 if (E->CountValid)
1004 continue;
1005 E->setEdgeCount(Value);
1006
1007 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1008 getBBInfo(E->DestBB).UnknownCountInEdge--;
1009 return;
1010 }
1011 llvm_unreachable("Cannot find the unknown count edge");
1012}
1013
1014// Read the profile from ProfileFileName and assign the value to the
1015// instrumented BB and the edges. This function also updates ProgramMaxCount.
1016// Return true if the profile are successfully read, and false on errors.
Rong Xufb4bcc42018-11-07 23:51:20 +00001017bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros) {
Rong Xuf430ae42015-12-09 18:08:16 +00001018 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001019 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001020 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001021 if (Error E = Result.takeError()) {
1022 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1023 auto Err = IPE.get();
1024 bool SkipWarning = false;
1025 if (Err == instrprof_error::unknown_function) {
1026 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001027 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +00001028 } else if (Err == instrprof_error::hash_mismatch ||
1029 Err == instrprof_error::malformed) {
1030 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001031 SkipWarning =
1032 NoPGOWarnMismatch ||
1033 (NoPGOWarnMismatchComdat &&
1034 (F.hasComdat() ||
1035 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +00001036 }
Rong Xuf430ae42015-12-09 18:08:16 +00001037
Vedant Kumar9152fd12016-05-19 03:54:45 +00001038 if (SkipWarning)
1039 return;
1040
1041 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1042 Ctx.diagnose(
1043 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1044 });
Rong Xuf430ae42015-12-09 18:08:16 +00001045 return false;
1046 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001047 ProfileRecord = std::move(Result.get());
1048 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001049
1050 NumOfPGOFunc++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001051 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001052 uint64_t ValueSum = 0;
1053 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001054 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001055 ValueSum += CountFromProfile[I];
1056 }
Rong Xufb4bcc42018-11-07 23:51:20 +00001057 AllZeros = (ValueSum == 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001058
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001059 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001060
1061 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1062 getBBInfo(nullptr).UnknownCountInEdge = 2;
1063
1064 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001065 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +00001066 return true;
1067}
1068
1069// Populate the counters from instrumented BBs to all BBs.
1070// In the end of this operation, all BBs should have a valid count value.
1071void PGOUseFunc::populateCounters() {
1072 // First set up Count variable for all BBs.
1073 for (auto &E : FuncInfo.MST.AllEdges) {
1074 if (E->Removed)
1075 continue;
1076
1077 const BasicBlock *SrcBB = E->SrcBB;
1078 const BasicBlock *DestBB = E->DestBB;
1079 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1080 UseBBInfo &DestInfo = getBBInfo(DestBB);
1081 SrcInfo.OutEdges.push_back(E.get());
1082 DestInfo.InEdges.push_back(E.get());
1083 SrcInfo.UnknownCountOutEdge++;
1084 DestInfo.UnknownCountInEdge++;
1085
1086 if (!E->CountValid)
1087 continue;
1088 DestInfo.UnknownCountInEdge--;
1089 SrcInfo.UnknownCountOutEdge--;
1090 }
1091
1092 bool Changes = true;
1093 unsigned NumPasses = 0;
1094 while (Changes) {
1095 NumPasses++;
1096 Changes = false;
1097
1098 // For efficient traversal, it's better to start from the end as most
1099 // of the instrumented edges are at the end.
1100 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001101 UseBBInfo *Count = findBBInfo(&BB);
1102 if (Count == nullptr)
1103 continue;
1104 if (!Count->CountValid) {
1105 if (Count->UnknownCountOutEdge == 0) {
1106 Count->CountValue = sumEdgeCount(Count->OutEdges);
1107 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001108 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001109 } else if (Count->UnknownCountInEdge == 0) {
1110 Count->CountValue = sumEdgeCount(Count->InEdges);
1111 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001112 Changes = true;
1113 }
1114 }
Rong Xua5b57452016-12-02 19:10:29 +00001115 if (Count->CountValid) {
1116 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001117 uint64_t Total = 0;
1118 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1119 // If the one of the successor block can early terminate (no-return),
1120 // we can end up with situation where out edge sum count is larger as
1121 // the source BB's count is collected by a post-dominated block.
1122 if (Count->CountValue > OutSum)
1123 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001124 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001125 Changes = true;
1126 }
Rong Xua5b57452016-12-02 19:10:29 +00001127 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001128 uint64_t Total = 0;
1129 uint64_t InSum = sumEdgeCount(Count->InEdges);
1130 if (Count->CountValue > InSum)
1131 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001132 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001133 Changes = true;
1134 }
1135 }
1136 }
1137 }
1138
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001139 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001140#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001141 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001142 for (auto &BB : F) {
1143 auto BI = findBBInfo(&BB);
1144 if (BI == nullptr)
1145 continue;
1146 assert(BI->CountValid && "BB count is not valid");
1147 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001148#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001149 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001150 F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001151 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001152 for (auto &BB : F) {
1153 auto BI = findBBInfo(&BB);
1154 if (BI == nullptr)
1155 continue;
1156 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1157 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001158 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001159
Rong Xu33308f92016-10-25 21:47:24 +00001160 // Now annotate select instructions
1161 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1162 assert(CountPosition == ProfileCountSize);
1163
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001164 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
Rong Xuf430ae42015-12-09 18:08:16 +00001165}
1166
1167// Assign the scaled count values to the BB with multiple out edges.
1168void PGOUseFunc::setBranchWeights() {
1169 // Generate MD_prof metadata for every branch instruction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001170 LLVM_DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001171 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001172 Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +00001173 if (TI->getNumSuccessors() < 2)
1174 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001175 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1176 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001177 continue;
1178 if (getBBInfo(&BB).CountValue == 0)
1179 continue;
1180
1181 // We have a non-zero Branch BB.
1182 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1183 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001184 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001185 uint64_t MaxCount = 0;
1186 for (unsigned s = 0; s < Size; s++) {
1187 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1188 const BasicBlock *SrcBB = E->SrcBB;
1189 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001190 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001191 continue;
1192 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1193 uint64_t EdgeCount = E->CountValue;
1194 if (EdgeCount > MaxCount)
1195 MaxCount = EdgeCount;
1196 EdgeCounts[SuccNum] = EdgeCount;
1197 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001198 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001199 }
1200}
Rong Xu13b01dc2016-02-10 18:24:45 +00001201
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001202static bool isIndirectBrTarget(BasicBlock *BB) {
1203 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1204 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1205 return true;
1206 }
1207 return false;
1208}
1209
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001210void PGOUseFunc::annotateIrrLoopHeaderWeights() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001211 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001212 // Find irr loop headers
1213 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001214 // As a heuristic also annotate indrectbr targets as they have a high chance
1215 // to become an irreducible loop header after the indirectbr tail
1216 // duplication.
1217 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001218 Instruction *TI = BB.getTerminator();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001219 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1220 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1221 }
1222 }
1223}
1224
Xinliang David Li4ca17332016-09-18 18:34:07 +00001225void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1226 Module *M = F.getParent();
1227 IRBuilder<> Builder(&SI);
1228 Type *Int64Ty = Builder.getInt64Ty();
1229 Type *I8PtrTy = Builder.getInt8PtrTy();
1230 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1231 Builder.CreateCall(
1232 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001233 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001234 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1235 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001236 ++(*CurCtrIdx);
1237}
1238
1239void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1240 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1241 assert(*CurCtrIdx < CountFromProfile.size() &&
1242 "Out of bound access of counters");
1243 uint64_t SCounts[2];
1244 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1245 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001246 uint64_t TotalCount = 0;
1247 auto BI = UseFunc->findBBInfo(SI.getParent());
1248 if (BI != nullptr)
1249 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001250 // False Count
1251 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1252 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001253 if (MaxCount)
1254 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001255}
1256
1257void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1258 if (!PGOInstrSelect)
1259 return;
1260 // FIXME: do not handle this yet.
1261 if (SI.getCondition()->getType()->isVectorTy())
1262 return;
1263
Xinliang David Li4ca17332016-09-18 18:34:07 +00001264 switch (Mode) {
1265 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001266 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001267 return;
1268 case VM_instrument:
1269 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001270 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001271 case VM_annotate:
1272 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001273 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001274 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001275
1276 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001277}
1278
Rong Xu60faea12017-03-16 21:15:48 +00001279void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1280 Module *M = F.getParent();
1281 IRBuilder<> Builder(&MI);
1282 Type *Int64Ty = Builder.getInt64Ty();
1283 Type *I8PtrTy = Builder.getInt8PtrTy();
1284 Value *Length = MI.getLength();
1285 assert(!dyn_cast<ConstantInt>(Length));
1286 Builder.CreateCall(
1287 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001288 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001289 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001290 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1291 ++CurCtrId;
1292}
1293
1294void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1295 if (!PGOInstrMemOP)
1296 return;
1297 Value *Length = MI.getLength();
1298 // Not instrument constant length calls.
1299 if (dyn_cast<ConstantInt>(Length))
1300 return;
1301
1302 switch (Mode) {
1303 case VM_counting:
1304 NMemIs++;
1305 return;
1306 case VM_instrument:
1307 instrumentOneMemIntrinsic(MI);
1308 return;
1309 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001310 Candidates.push_back(&MI);
1311 return;
Rong Xu60faea12017-03-16 21:15:48 +00001312 }
1313 llvm_unreachable("Unknown visiting mode");
1314}
1315
Rong Xua3bbf962017-03-15 18:23:39 +00001316// Traverse all valuesites and annotate the instructions for all value kind.
1317void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001318 if (DisableValueProfiling)
1319 return;
1320
Rong Xu8e8fe852016-04-01 16:43:30 +00001321 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001322 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001323
Rong Xua3bbf962017-03-15 18:23:39 +00001324 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001325 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001326}
1327
1328// Annotate the instructions for a specific value kind.
1329void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1330 unsigned ValueSiteIndex = 0;
1331 auto &ValueSites = FuncInfo.ValueSites[Kind];
1332 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1333 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001334 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001335 Ctx.diagnose(DiagnosticInfoPGOProfile(
1336 M->getName().data(),
1337 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1338 " in " + F.getName().str(),
1339 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001340 return;
1341 }
1342
Rong Xua3bbf962017-03-15 18:23:39 +00001343 for (auto &I : ValueSites) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001344 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1345 << "): Index = " << ValueSiteIndex << " out of "
1346 << NumValueSites << "\n");
Rong Xua3bbf962017-03-15 18:23:39 +00001347 annotateValueSite(*M, *I, ProfileRecord,
1348 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001349 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1350 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001351 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001352 }
1353}
Rong Xuf430ae42015-12-09 18:08:16 +00001354
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001355// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001356// aware this is an ir_level profile so it can set the version flag.
1357static void createIRLevelProfileFlagVariable(Module &M) {
1358 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1359 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001360 auto IRLevelVersionVariable = new GlobalVariable(
1361 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1362 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001363 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001364 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1365 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001366 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001367 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001368 else
Rong Xu9e926e82016-02-29 19:16:04 +00001369 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001370 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001371}
1372
Rong Xu705f7772016-07-25 18:45:37 +00001373// Collect the set of members for each Comdat in module M and store
1374// in ComdatMembers.
1375static void collectComdatMembers(
1376 Module &M,
1377 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1378 if (!DoComdatRenaming)
1379 return;
1380 for (Function &F : M)
1381 if (Comdat *C = F.getComdat())
1382 ComdatMembers.insert(std::make_pair(C, &F));
1383 for (GlobalVariable &GV : M.globals())
1384 if (Comdat *C = GV.getComdat())
1385 ComdatMembers.insert(std::make_pair(C, &GV));
1386 for (GlobalAlias &GA : M.aliases())
1387 if (Comdat *C = GA.getComdat())
1388 ComdatMembers.insert(std::make_pair(C, &GA));
1389}
1390
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001391static bool InstrumentAllFunctions(
Xinliang David Lid91057b2017-12-08 19:38:07 +00001392 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1393 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001394 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001395 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1396 collectComdatMembers(M, ComdatMembers);
1397
Rong Xuf430ae42015-12-09 18:08:16 +00001398 for (auto &F : M) {
1399 if (F.isDeclaration())
1400 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001401 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001402 auto *BFI = LookupBFI(F);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001403 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001404 }
1405 return true;
1406}
1407
Xinliang David Li8aebf442016-05-06 05:49:19 +00001408bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001409 if (skipModule(M))
1410 return false;
1411
Xinliang David Lid91057b2017-12-08 19:38:07 +00001412 auto LookupBPI = [this](Function &F) {
1413 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1414 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001415 auto LookupBFI = [this](Function &F) {
1416 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001417 };
Xinliang David Lid91057b2017-12-08 19:38:07 +00001418 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001419}
1420
Xinliang David Li8aebf442016-05-06 05:49:19 +00001421PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001422 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001423 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001424 auto LookupBPI = [&FAM](Function &F) {
1425 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1426 };
Xinliang David Li8aebf442016-05-06 05:49:19 +00001427
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001428 auto LookupBFI = [&FAM](Function &F) {
1429 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001430 };
1431
Xinliang David Lid91057b2017-12-08 19:38:07 +00001432 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001433 return PreservedAnalyses::all();
1434
1435 return PreservedAnalyses::none();
1436}
1437
Xinliang David Lida195582016-05-10 21:59:52 +00001438static bool annotateAllFunctions(
Richard Smith6c676622018-10-10 23:13:47 +00001439 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
Xinliang David Lid91057b2017-12-08 19:38:07 +00001440 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Li45c81902017-12-05 21:54:01 +00001441 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001442 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
Rong Xuf430ae42015-12-09 18:08:16 +00001443 auto &Ctx = M.getContext();
1444 // Read the counter array from file.
Richard Smith6c676622018-10-10 23:13:47 +00001445 auto ReaderOrErr =
1446 IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001447 if (Error E = ReaderOrErr.takeError()) {
1448 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1449 Ctx.diagnose(
1450 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1451 });
Rong Xuf430ae42015-12-09 18:08:16 +00001452 return false;
1453 }
1454
Xinliang David Lida195582016-05-10 21:59:52 +00001455 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1456 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001457 if (!PGOReader) {
1458 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001459 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001460 return false;
1461 }
Rong Xu33c76c02016-02-10 17:18:30 +00001462 // TODO: might need to change the warning once the clang option is finalized.
1463 if (!PGOReader->isIRLevelProfile()) {
1464 Ctx.diagnose(DiagnosticInfoPGOProfile(
1465 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1466 return false;
1467 }
1468
Rong Xu705f7772016-07-25 18:45:37 +00001469 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1470 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001471 std::vector<Function *> HotFunctions;
1472 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001473 for (auto &F : M) {
1474 if (F.isDeclaration())
1475 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001476 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001477 auto *BFI = LookupBFI(F);
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +00001478 // Split indirectbr critical edges here before computing the MST rather than
1479 // later in getInstrBB() to avoid invalidating it.
1480 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001481 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Rong Xufb4bcc42018-11-07 23:51:20 +00001482 bool AllZeros = false;
1483 if (!Func.readCounters(PGOReader.get(), AllZeros))
Sean Silva2e8f0952016-05-28 04:19:40 +00001484 continue;
Rong Xufb4bcc42018-11-07 23:51:20 +00001485 if (AllZeros) {
1486 F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1487 if (Func.getProgramMaxCount() != 0)
1488 ColdFunctions.push_back(&F);
1489 continue;
1490 }
Sean Silva2e8f0952016-05-28 04:19:40 +00001491 Func.populateCounters();
1492 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001493 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001494 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001495 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1496 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001497 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001498 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1499 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001500 if (PGOViewCounts != PGOVCT_None &&
1501 (ViewBlockFreqFuncName.empty() ||
1502 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001503 LoopInfo LI{DominatorTree(F)};
1504 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1505 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1506 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1507 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001508 if (PGOViewCounts == PGOVCT_Graph)
1509 NewBFI->view();
1510 else if (PGOViewCounts == PGOVCT_Text) {
1511 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1512 NewBFI->print(dbgs());
1513 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001514 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001515 if (PGOViewRawCounts != PGOVCT_None &&
1516 (ViewBlockFreqFuncName.empty() ||
1517 F.getName().equals(ViewBlockFreqFuncName))) {
1518 if (PGOViewRawCounts == PGOVCT_Graph)
1519 if (ViewBlockFreqFuncName.empty())
1520 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1521 else
1522 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1523 else if (PGOViewRawCounts == PGOVCT_Text) {
1524 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1525 Func.dumpInfo();
1526 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001527 }
Rong Xuf430ae42015-12-09 18:08:16 +00001528 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001529 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001530 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001531 // We have to apply these attributes at the end because their presence
1532 // can affect the BranchProbabilityInfo of any callers, resulting in an
1533 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001534 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001535 F->addFnAttr(Attribute::InlineHint);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001536 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1537 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001538 }
1539 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001540 F->addFnAttr(Attribute::Cold);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001541 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1542 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001543 }
Rong Xuf430ae42015-12-09 18:08:16 +00001544 return true;
1545}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001546
Richard Smith6c676622018-10-10 23:13:47 +00001547PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
1548 std::string RemappingFilename)
1549 : ProfileFileName(std::move(Filename)),
1550 ProfileRemappingFileName(std::move(RemappingFilename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001551 if (!PGOTestProfileFile.empty())
1552 ProfileFileName = PGOTestProfileFile;
Richard Smith6c676622018-10-10 23:13:47 +00001553 if (!PGOTestProfileRemappingFile.empty())
1554 ProfileRemappingFileName = PGOTestProfileRemappingFile;
Xinliang David Lida195582016-05-10 21:59:52 +00001555}
1556
1557PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001558 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001559
1560 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001561 auto LookupBPI = [&FAM](Function &F) {
1562 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1563 };
Xinliang David Lida195582016-05-10 21:59:52 +00001564
1565 auto LookupBFI = [&FAM](Function &F) {
1566 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1567 };
1568
Richard Smith6c676622018-10-10 23:13:47 +00001569 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1570 LookupBPI, LookupBFI))
Xinliang David Lida195582016-05-10 21:59:52 +00001571 return PreservedAnalyses::all();
1572
1573 return PreservedAnalyses::none();
1574}
1575
Xinliang David Lid55827f2016-05-07 05:39:12 +00001576bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1577 if (skipModule(M))
1578 return false;
1579
Xinliang David Lid91057b2017-12-08 19:38:07 +00001580 auto LookupBPI = [this](Function &F) {
1581 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1582 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001583 auto LookupBFI = [this](Function &F) {
1584 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001585 };
1586
Richard Smith6c676622018-10-10 23:13:47 +00001587 return annotateAllFunctions(M, ProfileFileName, "", LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001588}
Xinliang David Lid289e452017-01-27 19:06:25 +00001589
Eugene Zelenkofce43572017-10-21 00:57:46 +00001590static std::string getSimpleNodeName(const BasicBlock *Node) {
1591 if (!Node->getName().empty())
1592 return Node->getName();
1593
1594 std::string SimpleNodeName;
1595 raw_string_ostream OS(SimpleNodeName);
1596 Node->printAsOperand(OS, false);
1597 return OS.str();
1598}
1599
1600void llvm::setProfMetadata(Module *M, Instruction *TI,
1601 ArrayRef<uint64_t> EdgeCounts,
1602 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001603 MDBuilder MDB(M->getContext());
1604 assert(MaxCount > 0 && "Bad max count");
1605 uint64_t Scale = calculateCountScale(MaxCount);
1606 SmallVector<unsigned, 4> Weights;
1607 for (const auto &ECI : EdgeCounts)
1608 Weights.push_back(scaleBranchCount(ECI, Scale));
1609
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001610 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1611 : Weights) {
1612 dbgs() << W << " ";
1613 } dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001614 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001615 if (EmitBranchProbability) {
1616 std::string BrCondStr = getBranchCondString(TI);
1617 if (BrCondStr.empty())
1618 return;
1619
Rong Xu662f38b2018-03-27 18:55:56 +00001620 uint64_t WSum =
1621 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1622 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001623 uint64_t TotalCount =
Rong Xu662f38b2018-03-27 18:55:56 +00001624 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001625 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
Rong Xu662f38b2018-03-27 18:55:56 +00001626 Scale = calculateCountScale(WSum);
1627 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1628 scaleBranchCount(WSum, Scale));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001629 std::string BranchProbStr;
1630 raw_string_ostream OS(BranchProbStr);
1631 OS << BP;
1632 OS << " (total count : " << TotalCount << ")";
1633 OS.flush();
1634 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001635 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001636 ORE.emit([&]() {
1637 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1638 << BrCondStr << " is true with probability : " << BranchProbStr;
1639 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001640 }
Rong Xu48596b62017-04-04 16:42:20 +00001641}
1642
Eugene Zelenkofce43572017-10-21 00:57:46 +00001643namespace llvm {
1644
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001645void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1646 MDBuilder MDB(M->getContext());
1647 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1648 MDB.createIrrLoopHeaderWeight(Count));
1649}
1650
Xinliang David Lid289e452017-01-27 19:06:25 +00001651template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001652 using NodeRef = const BasicBlock *;
1653 using ChildIteratorType = succ_const_iterator;
1654 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001655
1656 static NodeRef getEntryNode(const PGOUseFunc *G) {
1657 return &G->getFunc().front();
1658 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001659
Xinliang David Lid289e452017-01-27 19:06:25 +00001660 static ChildIteratorType child_begin(const NodeRef N) {
1661 return succ_begin(N);
1662 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001663
Xinliang David Lid289e452017-01-27 19:06:25 +00001664 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001665
Xinliang David Lid289e452017-01-27 19:06:25 +00001666 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1667 return nodes_iterator(G->getFunc().begin());
1668 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001669
Xinliang David Lid289e452017-01-27 19:06:25 +00001670 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1671 return nodes_iterator(G->getFunc().end());
1672 }
1673};
1674
1675template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1676 explicit DOTGraphTraits(bool isSimple = false)
1677 : DefaultDOTGraphTraits(isSimple) {}
1678
1679 static std::string getGraphName(const PGOUseFunc *G) {
1680 return G->getFunc().getName();
1681 }
1682
1683 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1684 std::string Result;
1685 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001686
1687 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001688 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001689 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001690 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001691 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001692 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001693 OS << "Unknown\\l";
1694
1695 if (!PGOInstrSelect)
1696 return Result;
1697
1698 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1699 auto *I = &*BI;
1700 if (!isa<SelectInst>(I))
1701 continue;
1702 // Display scaled counts for SELECT instruction:
1703 OS << "SELECT : { T = ";
1704 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001705 bool HasProf = I->extractProfMetadata(TC, FC);
1706 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001707 OS << "Unknown, F = Unknown }\\l";
1708 else
1709 OS << TC << ", F = " << FC << " }\\l";
1710 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001711 return Result;
1712 }
1713};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001714
1715} // end namespace llvm