blob: 8bc5671040fa33407f7e64ff37020baac9dd1de4 [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."));
144
Rong Xuecdc98f2016-03-04 22:08:44 +0000145// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000146// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000147static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
148 cl::Hidden,
149 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000150
Rong Xuecdc98f2016-03-04 22:08:44 +0000151// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000152// the metadata for a single indirect call callsite.
153static cl::opt<unsigned> MaxNumAnnotations(
154 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
155 cl::desc("Max number of annotations for a single indirect "
156 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000157
Rong Xue60343d2017-03-17 18:07:26 +0000158// Command line option to set the maximum number of value annotations
159// to write to the metadata for a single memop intrinsic.
160static cl::opt<unsigned> MaxNumMemOPAnnotations(
161 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
162 cl::desc("Max number of preicise value annotations for a single memop"
163 "intrinsic"));
164
Rong Xu705f7772016-07-25 18:45:37 +0000165// Command line option to control appending FunctionHash to the name of a COMDAT
166// function. This is to avoid the hash mismatch caused by the preinliner.
167static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000168 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000169 cl::desc("Append function hash to the name of COMDAT function to avoid "
170 "function hash mismatch due to the preinliner"));
171
Rong Xu0698de92016-05-13 17:26:06 +0000172// Command line option to enable/disable the warning about missing profile
173// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000174static cl::opt<bool>
175 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
176 cl::desc("Use this option to turn on/off "
177 "warnings about missing profile data for "
178 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000179
180// Command line option to enable/disable the warning about a hash mismatch in
181// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000182static cl::opt<bool>
183 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
184 cl::desc("Use this option to turn off/on "
185 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000186
Rong Xu20f5df12017-01-11 20:19:41 +0000187// Command line option to enable/disable the warning about a hash mismatch in
188// the profile data for Comdat functions, which often turns out to be false
189// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000190static cl::opt<bool>
191 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
192 cl::Hidden,
193 cl::desc("The option is used to turn on/off "
194 "warnings about hash mismatch for comdat "
195 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000196
Xinliang David Li4ca17332016-09-18 18:34:07 +0000197// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000198static cl::opt<bool>
199 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
200 cl::desc("Use this option to turn on/off SELECT "
201 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000202
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000203// Command line option to turn on CFG dot or text dump of raw profile counts
204static cl::opt<PGOViewCountsType> PGOViewRawCounts(
205 "pgo-view-raw-counts", cl::Hidden,
206 cl::desc("A boolean option to show CFG dag or text "
207 "with raw profile counts from "
208 "profile data. See also option "
209 "-pgo-view-counts. To limit graph "
210 "display to only one function, use "
211 "filtering option -view-bfi-func-name."),
212 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
213 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
214 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000215
Rong Xu8e06e802017-03-17 20:51:44 +0000216// Command line option to enable/disable memop intrinsic call.size profiling.
217static cl::opt<bool>
218 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
219 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000220 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000221
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000222// Emit branch probability as optimization remarks.
223static cl::opt<bool>
224 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
225 cl::desc("When this option is on, the annotated "
226 "branch probability will be emitted as "
227 " optimization remarks: -Rpass-analysis="
228 "pgo-instr-use"));
229
Xinliang David Licb253ce2017-01-23 18:58:24 +0000230// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000231// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000232extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000233
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000234// Command line option to specify the name of the function for CFG dump
235// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
236extern cl::opt<std::string> ViewBlockFreqFuncName;
237
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000238// Return a string describing the branch condition that can be
239// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000240static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000241 BranchInst *BI = dyn_cast<BranchInst>(TI);
242 if (!BI || !BI->isConditional())
243 return std::string();
244
245 Value *Cond = BI->getCondition();
246 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
247 if (!CI)
248 return std::string();
249
250 std::string result;
251 raw_string_ostream OS(result);
252 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
253 CI->getOperand(0)->getType()->print(OS, true);
254
255 Value *RHS = CI->getOperand(1);
256 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
257 if (CV) {
258 if (CV->isZero())
259 OS << "_Zero";
260 else if (CV->isOne())
261 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000262 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000263 OS << "_MinusOne";
264 else
265 OS << "_Const";
266 }
267 OS.flush();
268 return result;
269}
270
Eugene Zelenkofce43572017-10-21 00:57:46 +0000271namespace {
272
Xinliang David Li4ca17332016-09-18 18:34:07 +0000273/// The select instruction visitor plays three roles specified
274/// by the mode. In \c VM_counting mode, it simply counts the number of
275/// select instructions. In \c VM_instrument mode, it inserts code to count
276/// the number times TrueValue of select is taken. In \c VM_annotate mode,
277/// it reads the profile data and annotate the select instruction with metadata.
278enum VisitMode { VM_counting, VM_instrument, VM_annotate };
279class PGOUseFunc;
280
281/// Instruction Visitor class to visit select instructions.
282struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
283 Function &F;
284 unsigned NSIs = 0; // Number of select instructions instrumented.
285 VisitMode Mode = VM_counting; // Visiting mode.
286 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
287 unsigned TotalNumCtrs = 0; // Total number of counters
288 GlobalVariable *FuncNameVar = nullptr;
289 uint64_t FuncHash = 0;
290 PGOUseFunc *UseFunc = nullptr;
291
292 SelectInstVisitor(Function &Func) : F(Func) {}
293
294 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000295 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000296 Mode = VM_counting;
297 visit(Func);
298 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000299
Xinliang David Li4ca17332016-09-18 18:34:07 +0000300 // Visit the IR stream and instrument all select instructions. \p
301 // Ind is a pointer to the counter index variable; \p TotalNC
302 // is the total number of counters; \p FNV is the pointer to the
303 // PGO function name var; \p FHash is the function hash.
304 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
305 GlobalVariable *FNV, uint64_t FHash) {
306 Mode = VM_instrument;
307 CurCtrIdx = Ind;
308 TotalNumCtrs = TotalNC;
309 FuncHash = FHash;
310 FuncNameVar = FNV;
311 visit(Func);
312 }
313
314 // Visit the IR stream and annotate all select instructions.
315 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
316 Mode = VM_annotate;
317 UseFunc = UF;
318 CurCtrIdx = Ind;
319 visit(Func);
320 }
321
322 void instrumentOneSelectInst(SelectInst &SI);
323 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000324
Xinliang David Li4ca17332016-09-18 18:34:07 +0000325 // Visit \p SI instruction and perform tasks according to visit mode.
326 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000327
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000328 // Return the number of select instructions. This needs be called after
329 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000330 unsigned getNumOfSelectInsts() const { return NSIs; }
331};
332
Rong Xu60faea12017-03-16 21:15:48 +0000333/// Instruction Visitor class to visit memory intrinsic calls.
334struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
335 Function &F;
336 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
337 VisitMode Mode = VM_counting; // Visiting mode.
338 unsigned CurCtrId = 0; // Current counter index.
339 unsigned TotalNumCtrs = 0; // Total number of counters
340 GlobalVariable *FuncNameVar = nullptr;
341 uint64_t FuncHash = 0;
342 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000343 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000344
345 MemIntrinsicVisitor(Function &Func) : F(Func) {}
346
347 void countMemIntrinsics(Function &Func) {
348 NMemIs = 0;
349 Mode = VM_counting;
350 visit(Func);
351 }
Rong Xue60343d2017-03-17 18:07:26 +0000352
Rong Xu60faea12017-03-16 21:15:48 +0000353 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
354 GlobalVariable *FNV, uint64_t FHash) {
355 Mode = VM_instrument;
356 TotalNumCtrs = TotalNC;
357 FuncHash = FHash;
358 FuncNameVar = FNV;
359 visit(Func);
360 }
361
Rong Xue60343d2017-03-17 18:07:26 +0000362 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
363 Candidates.clear();
364 Mode = VM_annotate;
365 visit(Func);
366 return Candidates;
367 }
368
Rong Xu60faea12017-03-16 21:15:48 +0000369 // Visit the IR stream and annotate all mem intrinsic call instructions.
370 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000371
Rong Xu60faea12017-03-16 21:15:48 +0000372 // Visit \p MI instruction and perform tasks according to visit mode.
373 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000374
Rong Xu60faea12017-03-16 21:15:48 +0000375 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
376};
377
Xinliang David Li8aebf442016-05-06 05:49:19 +0000378class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000379public:
380 static char ID;
381
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000382 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000383 initializePGOInstrumentationGenLegacyPassPass(
384 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000385 }
386
Mehdi Amini117296c2016-10-01 02:56:57 +0000387 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000388
389private:
390 bool runOnModule(Module &M) override;
391
392 void getAnalysisUsage(AnalysisUsage &AU) const override {
393 AU.addRequired<BlockFrequencyInfoWrapperPass>();
394 }
395};
396
Xinliang David Lid55827f2016-05-07 05:39:12 +0000397class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000398public:
399 static char ID;
400
401 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000403 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000404 if (!PGOTestProfileFile.empty())
405 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000406 initializePGOInstrumentationUseLegacyPassPass(
407 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000408 }
409
Mehdi Amini117296c2016-10-01 02:56:57 +0000410 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000411
412private:
413 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000414
Xinliang David Lida195582016-05-10 21:59:52 +0000415 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000416
Rong Xuf430ae42015-12-09 18:08:16 +0000417 void getAnalysisUsage(AnalysisUsage &AU) const override {
418 AU.addRequired<BlockFrequencyInfoWrapperPass>();
419 }
420};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000421
Rong Xuf430ae42015-12-09 18:08:16 +0000422} // end anonymous namespace
423
Xinliang David Li8aebf442016-05-06 05:49:19 +0000424char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000425
Xinliang David Li8aebf442016-05-06 05:49:19 +0000426INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000427 "PGO instrumentation.", false, false)
428INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000429INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000430INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000431 "PGO instrumentation.", false, false)
432
Xinliang David Li8aebf442016-05-06 05:49:19 +0000433ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
434 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000435}
436
Xinliang David Lid55827f2016-05-07 05:39:12 +0000437char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000438
Xinliang David Lid55827f2016-05-07 05:39:12 +0000439INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000440 "Read PGO instrumentation profile.", false, false)
441INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000442INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000443INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000444 "Read PGO instrumentation profile.", false, false)
445
Xinliang David Lid55827f2016-05-07 05:39:12 +0000446ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
447 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000448}
449
450namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000451
Rong Xuf430ae42015-12-09 18:08:16 +0000452/// \brief An MST based instrumentation for PGO
453///
454/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
455/// in the function level.
456struct PGOEdge {
457 // This class implements the CFG edges. Note the CFG can be a multi-graph.
458 // So there might be multiple edges with same SrcBB and DestBB.
459 const BasicBlock *SrcBB;
460 const BasicBlock *DestBB;
461 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000462 bool InMST = false;
463 bool Removed = false;
464 bool IsCritical = false;
465
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000466 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000467 : SrcBB(Src), DestBB(Dest), Weight(W) {}
468
Rong Xuf430ae42015-12-09 18:08:16 +0000469 // Return the information string of an edge.
470 const std::string infoString() const {
471 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
472 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
473 }
474};
475
476// This class stores the auxiliary information for each BB.
477struct BBInfo {
478 BBInfo *Group;
479 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000480 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000481
Eugene Zelenkofce43572017-10-21 00:57:46 +0000482 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000483
484 // Return the information string of this object.
485 const std::string infoString() const {
486 return (Twine("Index=") + Twine(Index)).str();
487 }
488};
489
490// This class implements the CFG edges. Note the CFG can be a multi-graph.
491template <class Edge, class BBInfo> class FuncPGOInstrumentation {
492private:
493 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000494
Rong Xu705f7772016-07-25 18:45:37 +0000495 // A map that stores the Comdat group in function F.
496 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000497
Eugene Zelenkofce43572017-10-21 00:57:46 +0000498 void computeCFGHash();
499 void renameComdatFunction();
500
Rong Xuf430ae42015-12-09 18:08:16 +0000501public:
Rong Xua3bbf962017-03-15 18:23:39 +0000502 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000503 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000504 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000505 std::string FuncName;
506 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000507
Rong Xuf430ae42015-12-09 18:08:16 +0000508 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000509 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000510
511 // The Minimum Spanning Tree of function CFG.
512 CFGMST<Edge, BBInfo> MST;
513
514 // Give an edge, find the BB that will be instrumented.
515 // Return nullptr if there is no BB to be instrumented.
516 BasicBlock *getInstrBB(Edge *E);
517
518 // Return the auxiliary BB information.
519 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
520
Rong Xua5b57452016-12-02 19:10:29 +0000521 // Return the auxiliary BB information if available.
522 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
523
Rong Xuf430ae42015-12-09 18:08:16 +0000524 // Dump edges and BB information.
525 void dumpInfo(std::string Str = "") const {
526 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000527 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000528 }
529
Rong Xu705f7772016-07-25 18:45:37 +0000530 FuncPGOInstrumentation(
531 Function &Func,
532 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000533 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
534 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000535 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000536 SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000537 // This should be done before CFG hash computation.
538 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000539 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000540 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000541 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000542 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000543 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000544
Rong Xuf430ae42015-12-09 18:08:16 +0000545 FuncName = getPGOFuncName(F);
546 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000547 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000548 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000549 DEBUG(dumpInfo("after CFGMST"));
550
551 NumOfPGOBB += MST.BBInfos.size();
552 for (auto &E : MST.AllEdges) {
553 if (E->Removed)
554 continue;
555 NumOfPGOEdge++;
556 if (!E->InMST)
557 NumOfPGOInstrument++;
558 }
559
560 if (CreateGlobalVar)
561 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000562 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000563
564 // Return the number of profile counters needed for the function.
565 unsigned getNumCounters() {
566 unsigned NumCounters = 0;
567 for (auto &E : this->MST.AllEdges) {
568 if (!E->InMST && !E->Removed)
569 NumCounters++;
570 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000571 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000572 }
Rong Xuf430ae42015-12-09 18:08:16 +0000573};
574
Eugene Zelenkofce43572017-10-21 00:57:46 +0000575} // end anonymous namespace
576
Rong Xuf430ae42015-12-09 18:08:16 +0000577// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
578// value of each BB in the CFG. The higher 32 bits record the number of edges.
579template <class Edge, class BBInfo>
580void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
581 std::vector<char> Indexes;
582 JamCRC JC;
583 for (auto &BB : F) {
584 const TerminatorInst *TI = BB.getTerminator();
585 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
586 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000587 auto BI = findBBInfo(Succ);
588 if (BI == nullptr)
589 continue;
590 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000591 for (int J = 0; J < 4; J++)
592 Indexes.push_back((char)(Index >> (J * 8)));
593 }
594 }
595 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000596 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000597 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000598 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Xinliang David Li8e436982017-07-21 21:36:25 +0000599 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
600 << " CRC = " << JC.getCRC()
601 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
602 << ", Edges = " << MST.AllEdges.size()
603 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
604 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000605}
606
607// Check if we can safely rename this Comdat function.
608static bool canRenameComdat(
609 Function &F,
610 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000611 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000612 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000613
614 // FIXME: Current only handle those Comdat groups that only containing one
615 // function and function aliases.
616 // (1) For a Comdat group containing multiple functions, we need to have a
617 // unique postfix based on the hashes for each function. There is a
618 // non-trivial code refactoring to do this efficiently.
619 // (2) Variables can not be renamed, so we can not rename Comdat function in a
620 // group including global vars.
621 Comdat *C = F.getComdat();
622 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
623 if (dyn_cast<GlobalAlias>(CM.second))
624 continue;
625 Function *FM = dyn_cast<Function>(CM.second);
626 if (FM != &F)
627 return false;
628 }
629 return true;
630}
631
632// Append the CFGHash to the Comdat function name.
633template <class Edge, class BBInfo>
634void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
635 if (!canRenameComdat(F, ComdatMembers))
636 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000637 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000638 std::string NewFuncName =
639 Twine(F.getName() + "." + Twine(FunctionHash)).str();
640 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000641 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000642 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
643 Comdat *NewComdat;
644 Module *M = F.getParent();
645 // For AvailableExternallyLinkage functions, change the linkage to
646 // LinkOnceODR and put them into comdat. This is because after renaming, there
647 // is no backup external copy available for the function.
648 if (!F.hasComdat()) {
649 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
650 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
651 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
652 F.setComdat(NewComdat);
653 return;
654 }
655
656 // This function belongs to a single function Comdat group.
657 Comdat *OrigComdat = F.getComdat();
658 std::string NewComdatName =
659 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
660 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
661 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
662
663 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
664 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
665 // For aliases, change the name directly.
666 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000667 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000668 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000669 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000670 continue;
671 }
672 // Must be a function.
673 Function *CF = dyn_cast<Function>(CM.second);
674 assert(CF);
675 CF->setComdat(NewComdat);
676 }
Rong Xuf430ae42015-12-09 18:08:16 +0000677}
678
679// Given a CFG E to be instrumented, find which BB to place the instrumented
680// code. The function will split the critical edge if necessary.
681template <class Edge, class BBInfo>
682BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
683 if (E->InMST || E->Removed)
684 return nullptr;
685
686 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
687 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
688 // For a fake edge, instrument the real BB.
689 if (SrcBB == nullptr)
690 return DestBB;
691 if (DestBB == nullptr)
692 return SrcBB;
693
694 // Instrument the SrcBB if it has a single successor,
695 // otherwise, the DestBB if this is not a critical edge.
696 TerminatorInst *TI = SrcBB->getTerminator();
697 if (TI->getNumSuccessors() <= 1)
698 return SrcBB;
699 if (!E->IsCritical)
700 return DestBB;
701
702 // For a critical edge, we have to split. Instrument the newly
703 // created BB.
704 NumOfPGOSplit++;
705 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
706 << getBBInfo(DestBB).Index << "\n");
707 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
708 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
709 assert(InstrBB && "Critical edge is not split");
710
711 E->Removed = true;
712 return InstrBB;
713}
714
Rong Xued9fec72016-01-21 18:11:44 +0000715// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000716// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000717static void instrumentOneFunc(
Xinliang David Lid91057b2017-12-08 19:38:07 +0000718 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Rong Xu705f7772016-07-25 18:45:37 +0000719 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000720 // Split indirectbr critical edges here before computing the MST rather than
721 // later in getInstrBB() to avoid invalidating it.
722 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +0000723 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
724 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000725 unsigned NumCounters = FuncInfo.getNumCounters();
726
Rong Xuf430ae42015-12-09 18:08:16 +0000727 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000728 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000729 for (auto &E : FuncInfo.MST.AllEdges) {
730 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
731 if (!InstrBB)
732 continue;
733
734 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
735 assert(Builder.GetInsertPoint() != InstrBB->end() &&
736 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000737 Builder.CreateCall(
738 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000739 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000740 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
741 Builder.getInt32(I++)});
742 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000743
744 // Now instrument select instructions:
745 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
746 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000747 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000748
749 if (DisableValueProfiling)
750 return;
751
752 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000753 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000754 CallSite CS(I);
755 Value *Callee = CS.getCalledValue();
756 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
757 << NumIndirectCallSites << "\n");
758 IRBuilder<> Builder(I);
759 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
760 "Cannot get the Instrumentation point");
761 Builder.CreateCall(
762 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000763 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000764 Builder.getInt64(FuncInfo.FunctionHash),
765 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000766 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000767 Builder.getInt32(NumIndirectCallSites++)});
768 }
769 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000770
771 // Now instrument memop intrinsic calls.
772 FuncInfo.MIVisitor.instrumentMemIntrinsics(
773 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000774}
775
Eugene Zelenkofce43572017-10-21 00:57:46 +0000776namespace {
777
Rong Xuf430ae42015-12-09 18:08:16 +0000778// This class represents a CFG edge in profile use compilation.
779struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000780 bool CountValid = false;
781 uint64_t CountValue = 0;
782
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000783 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000784 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000785
786 // Set edge count value
787 void setEdgeCount(uint64_t Value) {
788 CountValue = Value;
789 CountValid = true;
790 }
791
792 // Return the information string for this object.
793 const std::string infoString() const {
794 if (!CountValid)
795 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000796 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
797 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000798 }
799};
800
Eugene Zelenkofce43572017-10-21 00:57:46 +0000801using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000802
803// This class stores the auxiliary information for each BB.
804struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000805 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000806 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000807 int32_t UnknownCountInEdge = 0;
808 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000809 DirectEdges InEdges;
810 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000811
812 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
813
Rong Xuf430ae42015-12-09 18:08:16 +0000814 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000815 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000816
817 // Set the profile count value for this BB.
818 void setBBInfoCount(uint64_t Value) {
819 CountValue = Value;
820 CountValid = true;
821 }
822
823 // Return the information string of this object.
824 const std::string infoString() const {
825 if (!CountValid)
826 return BBInfo::infoString();
827 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
828 }
829};
830
Eugene Zelenkofce43572017-10-21 00:57:46 +0000831} // end anonymous namespace
832
Rong Xuf430ae42015-12-09 18:08:16 +0000833// Sum up the count values for all the edges.
834static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
835 uint64_t Total = 0;
836 for (auto &E : Edges) {
837 if (E->Removed)
838 continue;
839 Total += E->CountValue;
840 }
841 return Total;
842}
843
Eugene Zelenkofce43572017-10-21 00:57:46 +0000844namespace {
845
Rong Xuf430ae42015-12-09 18:08:16 +0000846class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000847public:
Rong Xu705f7772016-07-25 18:45:37 +0000848 PGOUseFunc(Function &Func, Module *Modu,
849 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000850 BranchProbabilityInfo *BPI = nullptr,
Xinliang David Li45c81902017-12-05 21:54:01 +0000851 BlockFrequencyInfo *BFIin = nullptr)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000852 : F(Func), M(Modu), BFI(BFIin),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000853 FuncInfo(Func, ComdatMembers, false, BPI, BFIin),
854 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000855
856 // Read counts for the instrumented BB from profile.
857 bool readCounters(IndexedInstrProfReader *PGOReader);
858
859 // Populate the counts for all BBs.
860 void populateCounters();
861
862 // Set the branch weights based on the count values.
863 void setBranchWeights();
864
Rong Xua3bbf962017-03-15 18:23:39 +0000865 // Annotate the value profile call sites all all value kind.
866 void annotateValueSites();
867
868 // Annotate the value profile call sites for one value kind.
869 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000870
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000871 // Annotate the irreducible loop header weights.
872 void annotateIrrLoopHeaderWeights();
873
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000874 // The hotness of the function from the profile count.
875 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
876
877 // Return the function hotness from the profile.
878 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
879
Rong Xu705f7772016-07-25 18:45:37 +0000880 // Return the function hash.
881 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000882
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000883 // Return the profile record for this function;
884 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
885
Xinliang David Li4ca17332016-09-18 18:34:07 +0000886 // Return the auxiliary BB information.
887 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
888 return FuncInfo.getBBInfo(BB);
889 }
890
Rong Xua5b57452016-12-02 19:10:29 +0000891 // Return the auxiliary BB information if available.
892 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
893 return FuncInfo.findBBInfo(BB);
894 }
895
Xinliang David Lid289e452017-01-27 19:06:25 +0000896 Function &getFunc() const { return F; }
897
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000898 void dumpInfo(std::string Str = "") const {
899 FuncInfo.dumpInfo(Str);
900 }
901
Rong Xuf430ae42015-12-09 18:08:16 +0000902private:
903 Function &F;
904 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000905 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000906
Rong Xuf430ae42015-12-09 18:08:16 +0000907 // This member stores the shared information with class PGOGenFunc.
908 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
909
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000910 // The maximum count value in the profile. This is only used in PGO use
911 // compilation.
912 uint64_t ProgramMaxCount;
913
Rong Xu33308f92016-10-25 21:47:24 +0000914 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000915 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000916
917 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000918 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000919
Rong Xu13b01dc2016-02-10 18:24:45 +0000920 // ProfileRecord for this function.
921 InstrProfRecord ProfileRecord;
922
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000923 // Function hotness info derived from profile.
924 FuncFreqAttr FreqAttr;
925
Rong Xuf430ae42015-12-09 18:08:16 +0000926 // Find the Instrumented BB and set the value.
927 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
928
929 // Set the edge counter value for the unknown edge -- there should be only
930 // one unknown edge.
931 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
932
933 // Return FuncName string;
934 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000935
936 // Set the hot/cold inline hints based on the count values.
937 // FIXME: This function should be removed once the functionality in
938 // the inliner is implemented.
939 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
940 if (ProgramMaxCount == 0)
941 return;
942 // Threshold of the hot functions.
943 const BranchProbability HotFunctionThreshold(1, 100);
944 // Threshold of the cold functions.
945 const BranchProbability ColdFunctionThreshold(2, 10000);
946 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
947 FreqAttr = FFA_Hot;
948 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
949 FreqAttr = FFA_Cold;
950 }
Rong Xuf430ae42015-12-09 18:08:16 +0000951};
952
Eugene Zelenkofce43572017-10-21 00:57:46 +0000953} // end anonymous namespace
954
Rong Xuf430ae42015-12-09 18:08:16 +0000955// Visit all the edges and assign the count value for the instrumented
956// edges and the BB.
957void PGOUseFunc::setInstrumentedCounts(
958 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +0000959 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000960 // Use a worklist as we will update the vector during the iteration.
961 std::vector<PGOUseEdge *> WorkList;
962 for (auto &E : FuncInfo.MST.AllEdges)
963 WorkList.push_back(E.get());
964
965 uint32_t I = 0;
966 for (auto &E : WorkList) {
967 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
968 if (!InstrBB)
969 continue;
970 uint64_t CountValue = CountFromProfile[I++];
971 if (!E->Removed) {
972 getBBInfo(InstrBB).setBBInfoCount(CountValue);
973 E->setEdgeCount(CountValue);
974 continue;
975 }
976
977 // Need to add two new edges.
978 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
979 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
980 // Add new edge of SrcBB->InstrBB.
981 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
982 NewEdge.setEdgeCount(CountValue);
983 // Add new edge of InstrBB->DestBB.
984 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
985 NewEdge1.setEdgeCount(CountValue);
986 NewEdge1.InMST = true;
987 getBBInfo(InstrBB).setBBInfoCount(CountValue);
988 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000989 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000990 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000991}
992
993// Set the count value for the unknown edge. There should be one and only one
994// unknown edge in Edges vector.
995void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
996 for (auto &E : Edges) {
997 if (E->CountValid)
998 continue;
999 E->setEdgeCount(Value);
1000
1001 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1002 getBBInfo(E->DestBB).UnknownCountInEdge--;
1003 return;
1004 }
1005 llvm_unreachable("Cannot find the unknown count edge");
1006}
1007
1008// Read the profile from ProfileFileName and assign the value to the
1009// instrumented BB and the edges. This function also updates ProgramMaxCount.
1010// Return true if the profile are successfully read, and false on errors.
1011bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
1012 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001013 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001014 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001015 if (Error E = Result.takeError()) {
1016 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1017 auto Err = IPE.get();
1018 bool SkipWarning = false;
1019 if (Err == instrprof_error::unknown_function) {
1020 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001021 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +00001022 } else if (Err == instrprof_error::hash_mismatch ||
1023 Err == instrprof_error::malformed) {
1024 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001025 SkipWarning =
1026 NoPGOWarnMismatch ||
1027 (NoPGOWarnMismatchComdat &&
1028 (F.hasComdat() ||
1029 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +00001030 }
Rong Xuf430ae42015-12-09 18:08:16 +00001031
Vedant Kumar9152fd12016-05-19 03:54:45 +00001032 if (SkipWarning)
1033 return;
1034
1035 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1036 Ctx.diagnose(
1037 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1038 });
Rong Xuf430ae42015-12-09 18:08:16 +00001039 return false;
1040 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001041 ProfileRecord = std::move(Result.get());
1042 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001043
1044 NumOfPGOFunc++;
1045 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1046 uint64_t ValueSum = 0;
1047 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1048 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1049 ValueSum += CountFromProfile[I];
1050 }
1051
1052 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1053
1054 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1055 getBBInfo(nullptr).UnknownCountInEdge = 2;
1056
1057 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001058 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +00001059 return true;
1060}
1061
1062// Populate the counters from instrumented BBs to all BBs.
1063// In the end of this operation, all BBs should have a valid count value.
1064void PGOUseFunc::populateCounters() {
1065 // First set up Count variable for all BBs.
1066 for (auto &E : FuncInfo.MST.AllEdges) {
1067 if (E->Removed)
1068 continue;
1069
1070 const BasicBlock *SrcBB = E->SrcBB;
1071 const BasicBlock *DestBB = E->DestBB;
1072 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1073 UseBBInfo &DestInfo = getBBInfo(DestBB);
1074 SrcInfo.OutEdges.push_back(E.get());
1075 DestInfo.InEdges.push_back(E.get());
1076 SrcInfo.UnknownCountOutEdge++;
1077 DestInfo.UnknownCountInEdge++;
1078
1079 if (!E->CountValid)
1080 continue;
1081 DestInfo.UnknownCountInEdge--;
1082 SrcInfo.UnknownCountOutEdge--;
1083 }
1084
1085 bool Changes = true;
1086 unsigned NumPasses = 0;
1087 while (Changes) {
1088 NumPasses++;
1089 Changes = false;
1090
1091 // For efficient traversal, it's better to start from the end as most
1092 // of the instrumented edges are at the end.
1093 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001094 UseBBInfo *Count = findBBInfo(&BB);
1095 if (Count == nullptr)
1096 continue;
1097 if (!Count->CountValid) {
1098 if (Count->UnknownCountOutEdge == 0) {
1099 Count->CountValue = sumEdgeCount(Count->OutEdges);
1100 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001101 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001102 } else if (Count->UnknownCountInEdge == 0) {
1103 Count->CountValue = sumEdgeCount(Count->InEdges);
1104 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001105 Changes = true;
1106 }
1107 }
Rong Xua5b57452016-12-02 19:10:29 +00001108 if (Count->CountValid) {
1109 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001110 uint64_t Total = 0;
1111 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1112 // If the one of the successor block can early terminate (no-return),
1113 // we can end up with situation where out edge sum count is larger as
1114 // the source BB's count is collected by a post-dominated block.
1115 if (Count->CountValue > OutSum)
1116 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001117 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001118 Changes = true;
1119 }
Rong Xua5b57452016-12-02 19:10:29 +00001120 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001121 uint64_t Total = 0;
1122 uint64_t InSum = sumEdgeCount(Count->InEdges);
1123 if (Count->CountValue > InSum)
1124 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001125 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001126 Changes = true;
1127 }
1128 }
1129 }
1130 }
1131
1132 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001133#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001134 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001135 for (auto &BB : F) {
1136 auto BI = findBBInfo(&BB);
1137 if (BI == nullptr)
1138 continue;
1139 assert(BI->CountValid && "BB count is not valid");
1140 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001141#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001142 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001143 F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001144 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001145 for (auto &BB : F) {
1146 auto BI = findBBInfo(&BB);
1147 if (BI == nullptr)
1148 continue;
1149 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1150 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001151 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001152
Rong Xu33308f92016-10-25 21:47:24 +00001153 // Now annotate select instructions
1154 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1155 assert(CountPosition == ProfileCountSize);
1156
Rong Xuf430ae42015-12-09 18:08:16 +00001157 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1158}
1159
1160// Assign the scaled count values to the BB with multiple out edges.
1161void PGOUseFunc::setBranchWeights() {
1162 // Generate MD_prof metadata for every branch instruction.
1163 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001164 for (auto &BB : F) {
1165 TerminatorInst *TI = BB.getTerminator();
1166 if (TI->getNumSuccessors() < 2)
1167 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001168 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1169 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001170 continue;
1171 if (getBBInfo(&BB).CountValue == 0)
1172 continue;
1173
1174 // We have a non-zero Branch BB.
1175 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1176 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001177 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001178 uint64_t MaxCount = 0;
1179 for (unsigned s = 0; s < Size; s++) {
1180 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1181 const BasicBlock *SrcBB = E->SrcBB;
1182 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001183 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001184 continue;
1185 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1186 uint64_t EdgeCount = E->CountValue;
1187 if (EdgeCount > MaxCount)
1188 MaxCount = EdgeCount;
1189 EdgeCounts[SuccNum] = EdgeCount;
1190 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001191 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001192 }
1193}
Rong Xu13b01dc2016-02-10 18:24:45 +00001194
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001195static bool isIndirectBrTarget(BasicBlock *BB) {
1196 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1197 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1198 return true;
1199 }
1200 return false;
1201}
1202
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001203void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1204 DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1205 // Find irr loop headers
1206 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001207 // As a heuristic also annotate indrectbr targets as they have a high chance
1208 // to become an irreducible loop header after the indirectbr tail
1209 // duplication.
1210 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001211 TerminatorInst *TI = BB.getTerminator();
1212 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1213 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1214 }
1215 }
1216}
1217
Xinliang David Li4ca17332016-09-18 18:34:07 +00001218void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1219 Module *M = F.getParent();
1220 IRBuilder<> Builder(&SI);
1221 Type *Int64Ty = Builder.getInt64Ty();
1222 Type *I8PtrTy = Builder.getInt8PtrTy();
1223 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1224 Builder.CreateCall(
1225 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001226 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001227 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1228 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001229 ++(*CurCtrIdx);
1230}
1231
1232void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1233 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1234 assert(*CurCtrIdx < CountFromProfile.size() &&
1235 "Out of bound access of counters");
1236 uint64_t SCounts[2];
1237 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1238 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001239 uint64_t TotalCount = 0;
1240 auto BI = UseFunc->findBBInfo(SI.getParent());
1241 if (BI != nullptr)
1242 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001243 // False Count
1244 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1245 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001246 if (MaxCount)
1247 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001248}
1249
1250void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1251 if (!PGOInstrSelect)
1252 return;
1253 // FIXME: do not handle this yet.
1254 if (SI.getCondition()->getType()->isVectorTy())
1255 return;
1256
Xinliang David Li4ca17332016-09-18 18:34:07 +00001257 switch (Mode) {
1258 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001259 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001260 return;
1261 case VM_instrument:
1262 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001263 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001264 case VM_annotate:
1265 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001266 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001267 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001268
1269 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001270}
1271
Rong Xu60faea12017-03-16 21:15:48 +00001272void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1273 Module *M = F.getParent();
1274 IRBuilder<> Builder(&MI);
1275 Type *Int64Ty = Builder.getInt64Ty();
1276 Type *I8PtrTy = Builder.getInt8PtrTy();
1277 Value *Length = MI.getLength();
1278 assert(!dyn_cast<ConstantInt>(Length));
1279 Builder.CreateCall(
1280 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001281 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001282 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001283 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1284 ++CurCtrId;
1285}
1286
1287void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1288 if (!PGOInstrMemOP)
1289 return;
1290 Value *Length = MI.getLength();
1291 // Not instrument constant length calls.
1292 if (dyn_cast<ConstantInt>(Length))
1293 return;
1294
1295 switch (Mode) {
1296 case VM_counting:
1297 NMemIs++;
1298 return;
1299 case VM_instrument:
1300 instrumentOneMemIntrinsic(MI);
1301 return;
1302 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001303 Candidates.push_back(&MI);
1304 return;
Rong Xu60faea12017-03-16 21:15:48 +00001305 }
1306 llvm_unreachable("Unknown visiting mode");
1307}
1308
Rong Xua3bbf962017-03-15 18:23:39 +00001309// Traverse all valuesites and annotate the instructions for all value kind.
1310void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001311 if (DisableValueProfiling)
1312 return;
1313
Rong Xu8e8fe852016-04-01 16:43:30 +00001314 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001315 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001316
Rong Xua3bbf962017-03-15 18:23:39 +00001317 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001318 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001319}
1320
1321// Annotate the instructions for a specific value kind.
1322void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1323 unsigned ValueSiteIndex = 0;
1324 auto &ValueSites = FuncInfo.ValueSites[Kind];
1325 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1326 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001327 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001328 Ctx.diagnose(DiagnosticInfoPGOProfile(
1329 M->getName().data(),
1330 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1331 " in " + F.getName().str(),
1332 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001333 return;
1334 }
1335
Rong Xua3bbf962017-03-15 18:23:39 +00001336 for (auto &I : ValueSites) {
1337 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1338 << "): Index = " << ValueSiteIndex << " out of "
1339 << NumValueSites << "\n");
1340 annotateValueSite(*M, *I, ProfileRecord,
1341 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001342 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1343 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001344 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001345 }
1346}
Rong Xuf430ae42015-12-09 18:08:16 +00001347
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001348// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001349// aware this is an ir_level profile so it can set the version flag.
1350static void createIRLevelProfileFlagVariable(Module &M) {
1351 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1352 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001353 auto IRLevelVersionVariable = new GlobalVariable(
1354 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1355 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001356 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001357 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1358 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001359 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001360 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001361 else
Rong Xu9e926e82016-02-29 19:16:04 +00001362 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001363 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001364}
1365
Rong Xu705f7772016-07-25 18:45:37 +00001366// Collect the set of members for each Comdat in module M and store
1367// in ComdatMembers.
1368static void collectComdatMembers(
1369 Module &M,
1370 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1371 if (!DoComdatRenaming)
1372 return;
1373 for (Function &F : M)
1374 if (Comdat *C = F.getComdat())
1375 ComdatMembers.insert(std::make_pair(C, &F));
1376 for (GlobalVariable &GV : M.globals())
1377 if (Comdat *C = GV.getComdat())
1378 ComdatMembers.insert(std::make_pair(C, &GV));
1379 for (GlobalAlias &GA : M.aliases())
1380 if (Comdat *C = GA.getComdat())
1381 ComdatMembers.insert(std::make_pair(C, &GA));
1382}
1383
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001384static bool InstrumentAllFunctions(
Xinliang David Lid91057b2017-12-08 19:38:07 +00001385 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1386 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001387 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001388 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1389 collectComdatMembers(M, ComdatMembers);
1390
Rong Xuf430ae42015-12-09 18:08:16 +00001391 for (auto &F : M) {
1392 if (F.isDeclaration())
1393 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001394 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001395 auto *BFI = LookupBFI(F);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001396 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001397 }
1398 return true;
1399}
1400
Xinliang David Li8aebf442016-05-06 05:49:19 +00001401bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001402 if (skipModule(M))
1403 return false;
1404
Xinliang David Lid91057b2017-12-08 19:38:07 +00001405 auto LookupBPI = [this](Function &F) {
1406 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1407 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001408 auto LookupBFI = [this](Function &F) {
1409 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001410 };
Xinliang David Lid91057b2017-12-08 19:38:07 +00001411 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001412}
1413
Xinliang David Li8aebf442016-05-06 05:49:19 +00001414PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001415 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001416 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001417 auto LookupBPI = [&FAM](Function &F) {
1418 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1419 };
Xinliang David Li8aebf442016-05-06 05:49:19 +00001420
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001421 auto LookupBFI = [&FAM](Function &F) {
1422 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001423 };
1424
Xinliang David Lid91057b2017-12-08 19:38:07 +00001425 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001426 return PreservedAnalyses::all();
1427
1428 return PreservedAnalyses::none();
1429}
1430
Xinliang David Lida195582016-05-10 21:59:52 +00001431static bool annotateAllFunctions(
1432 Module &M, StringRef ProfileFileName,
Xinliang David Lid91057b2017-12-08 19:38:07 +00001433 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Li45c81902017-12-05 21:54:01 +00001434 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001435 DEBUG(dbgs() << "Read in profile counters: ");
1436 auto &Ctx = M.getContext();
1437 // Read the counter array from file.
1438 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001439 if (Error E = ReaderOrErr.takeError()) {
1440 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1441 Ctx.diagnose(
1442 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1443 });
Rong Xuf430ae42015-12-09 18:08:16 +00001444 return false;
1445 }
1446
Xinliang David Lida195582016-05-10 21:59:52 +00001447 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1448 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001449 if (!PGOReader) {
1450 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001451 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001452 return false;
1453 }
Rong Xu33c76c02016-02-10 17:18:30 +00001454 // TODO: might need to change the warning once the clang option is finalized.
1455 if (!PGOReader->isIRLevelProfile()) {
1456 Ctx.diagnose(DiagnosticInfoPGOProfile(
1457 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1458 return false;
1459 }
1460
Rong Xu705f7772016-07-25 18:45:37 +00001461 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1462 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001463 std::vector<Function *> HotFunctions;
1464 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001465 for (auto &F : M) {
1466 if (F.isDeclaration())
1467 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001468 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001469 auto *BFI = LookupBFI(F);
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +00001470 // Split indirectbr critical edges here before computing the MST rather than
1471 // later in getInstrBB() to avoid invalidating it.
1472 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001473 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001474 if (!Func.readCounters(PGOReader.get()))
1475 continue;
1476 Func.populateCounters();
1477 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001478 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001479 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001480 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1481 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001482 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001483 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1484 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001485 if (PGOViewCounts != PGOVCT_None &&
1486 (ViewBlockFreqFuncName.empty() ||
1487 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001488 LoopInfo LI{DominatorTree(F)};
1489 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1490 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1491 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1492 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001493 if (PGOViewCounts == PGOVCT_Graph)
1494 NewBFI->view();
1495 else if (PGOViewCounts == PGOVCT_Text) {
1496 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1497 NewBFI->print(dbgs());
1498 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001499 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001500 if (PGOViewRawCounts != PGOVCT_None &&
1501 (ViewBlockFreqFuncName.empty() ||
1502 F.getName().equals(ViewBlockFreqFuncName))) {
1503 if (PGOViewRawCounts == PGOVCT_Graph)
1504 if (ViewBlockFreqFuncName.empty())
1505 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1506 else
1507 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1508 else if (PGOViewRawCounts == PGOVCT_Text) {
1509 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1510 Func.dumpInfo();
1511 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001512 }
Rong Xuf430ae42015-12-09 18:08:16 +00001513 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001514 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001515 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001516 // We have to apply these attributes at the end because their presence
1517 // can affect the BranchProbabilityInfo of any callers, resulting in an
1518 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001519 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001520 F->addFnAttr(Attribute::InlineHint);
Rong Xu6090afd2016-03-28 17:08:56 +00001521 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1522 << "\n");
1523 }
1524 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001525 F->addFnAttr(Attribute::Cold);
Rong Xu6090afd2016-03-28 17:08:56 +00001526 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1527 }
Rong Xuf430ae42015-12-09 18:08:16 +00001528 return true;
1529}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001530
Xinliang David Lida195582016-05-10 21:59:52 +00001531PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001532 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001533 if (!PGOTestProfileFile.empty())
1534 ProfileFileName = PGOTestProfileFile;
1535}
1536
1537PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001538 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001539
1540 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001541 auto LookupBPI = [&FAM](Function &F) {
1542 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1543 };
Xinliang David Lida195582016-05-10 21:59:52 +00001544
1545 auto LookupBFI = [&FAM](Function &F) {
1546 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1547 };
1548
Xinliang David Lid91057b2017-12-08 19:38:07 +00001549 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
Xinliang David Lida195582016-05-10 21:59:52 +00001550 return PreservedAnalyses::all();
1551
1552 return PreservedAnalyses::none();
1553}
1554
Xinliang David Lid55827f2016-05-07 05:39:12 +00001555bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1556 if (skipModule(M))
1557 return false;
1558
Xinliang David Lid91057b2017-12-08 19:38:07 +00001559 auto LookupBPI = [this](Function &F) {
1560 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1561 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001562 auto LookupBFI = [this](Function &F) {
1563 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001564 };
1565
Xinliang David Lid91057b2017-12-08 19:38:07 +00001566 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001567}
Xinliang David Lid289e452017-01-27 19:06:25 +00001568
Eugene Zelenkofce43572017-10-21 00:57:46 +00001569static std::string getSimpleNodeName(const BasicBlock *Node) {
1570 if (!Node->getName().empty())
1571 return Node->getName();
1572
1573 std::string SimpleNodeName;
1574 raw_string_ostream OS(SimpleNodeName);
1575 Node->printAsOperand(OS, false);
1576 return OS.str();
1577}
1578
1579void llvm::setProfMetadata(Module *M, Instruction *TI,
1580 ArrayRef<uint64_t> EdgeCounts,
1581 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001582 MDBuilder MDB(M->getContext());
1583 assert(MaxCount > 0 && "Bad max count");
1584 uint64_t Scale = calculateCountScale(MaxCount);
1585 SmallVector<unsigned, 4> Weights;
1586 for (const auto &ECI : EdgeCounts)
1587 Weights.push_back(scaleBranchCount(ECI, Scale));
1588
1589 DEBUG(dbgs() << "Weight is: ";
1590 for (const auto &W : Weights) { dbgs() << W << " "; }
1591 dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001592 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001593 if (EmitBranchProbability) {
1594 std::string BrCondStr = getBranchCondString(TI);
1595 if (BrCondStr.empty())
1596 return;
1597
1598 unsigned WSum =
1599 std::accumulate(Weights.begin(), Weights.end(), 0,
1600 [](unsigned w1, unsigned w2) { return w1 + w2; });
1601 uint64_t TotalCount =
1602 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1603 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1604 BranchProbability BP(Weights[0], WSum);
1605 std::string BranchProbStr;
1606 raw_string_ostream OS(BranchProbStr);
1607 OS << BP;
1608 OS << " (total count : " << TotalCount << ")";
1609 OS.flush();
1610 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001611 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001612 ORE.emit([&]() {
1613 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1614 << BrCondStr << " is true with probability : " << BranchProbStr;
1615 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001616 }
Rong Xu48596b62017-04-04 16:42:20 +00001617}
1618
Eugene Zelenkofce43572017-10-21 00:57:46 +00001619namespace llvm {
1620
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001621void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1622 MDBuilder MDB(M->getContext());
1623 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1624 MDB.createIrrLoopHeaderWeight(Count));
1625}
1626
Xinliang David Lid289e452017-01-27 19:06:25 +00001627template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001628 using NodeRef = const BasicBlock *;
1629 using ChildIteratorType = succ_const_iterator;
1630 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001631
1632 static NodeRef getEntryNode(const PGOUseFunc *G) {
1633 return &G->getFunc().front();
1634 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001635
Xinliang David Lid289e452017-01-27 19:06:25 +00001636 static ChildIteratorType child_begin(const NodeRef N) {
1637 return succ_begin(N);
1638 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001639
Xinliang David Lid289e452017-01-27 19:06:25 +00001640 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001641
Xinliang David Lid289e452017-01-27 19:06:25 +00001642 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1643 return nodes_iterator(G->getFunc().begin());
1644 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001645
Xinliang David Lid289e452017-01-27 19:06:25 +00001646 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1647 return nodes_iterator(G->getFunc().end());
1648 }
1649};
1650
1651template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1652 explicit DOTGraphTraits(bool isSimple = false)
1653 : DefaultDOTGraphTraits(isSimple) {}
1654
1655 static std::string getGraphName(const PGOUseFunc *G) {
1656 return G->getFunc().getName();
1657 }
1658
1659 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1660 std::string Result;
1661 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001662
1663 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001664 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001665 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001666 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001667 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001668 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001669 OS << "Unknown\\l";
1670
1671 if (!PGOInstrSelect)
1672 return Result;
1673
1674 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1675 auto *I = &*BI;
1676 if (!isa<SelectInst>(I))
1677 continue;
1678 // Display scaled counts for SELECT instruction:
1679 OS << "SELECT : { T = ";
1680 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001681 bool HasProf = I->extractProfMetadata(TC, FC);
1682 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001683 OS << "Unknown, F = Unknown }\\l";
1684 else
1685 OS << TC << ", F = " << FC << " }\\l";
1686 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001687 return Result;
1688 }
1689};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001690
1691} // end namespace llvm