blob: bb2e3359881c077bd2c7f4cf3f2f7c6e10495cf9 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Rong Xuf430ae42015-12-09 18:08:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements PGO instrumentation using a minimum spanning tree based
10// on the following paper:
11// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13// Issue 3, pp 313-322
14// The idea of the algorithm based on the fact that for each node (except for
15// the entry and exit), the sum of incoming edge counts equals the sum of
16// outgoing edge counts. The count of edge on spanning tree can be derived from
17// those edges not on the spanning tree. Knuth proves this method instruments
18// the minimum number of edges.
19//
20// The minimal spanning tree here is actually a maximum weight tree -- on-tree
21// edges have higher frequencies (more likely to execute). The idea is to
22// instrument those less frequently executed edges to reduce the runtime
23// overhead of instrumented binaries.
24//
25// This file contains two passes:
26// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000027// count profile, and generates the instrumentation for indirect call
28// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000029// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000030// annotates the branch weights. It also reads the indirect call value
31// profiling records and annotate the indirect call instructions.
32//
Rong Xuf430ae42015-12-09 18:08:16 +000033// To get the precise counter information, These two passes need to invoke at
34// the same compilation point (so they see the same IR). For pass
35// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37// the profile is opened in module level and passed to each PGOUseFunc instance.
38// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39// in class FuncPGOInstrumentation.
40//
41// Class PGOEdge represents a CFG edge and some auxiliary information. Class
42// BBInfo contains auxiliary information for each BB. These two classes are used
43// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44// class of PGOEdge and BBInfo, respectively. They contains extra data structure
45// used in populating profile counters.
46// The MST implementation is in Class CFGMST (CFGMST.h).
47//
48//===----------------------------------------------------------------------===//
49
David Blaikie4fe1fe12018-03-23 22:11:06 +000050#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000051#include "CFGMST.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000052#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
Rong Xuf430ae42015-12-09 18:08:16 +000054#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000055#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000056#include "llvm/ADT/Statistic.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000057#include "llvm/ADT/StringRef.h"
Rong Xu33c76c02016-02-10 17:18:30 +000058#include "llvm/ADT/Triple.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000059#include "llvm/ADT/Twine.h"
60#include "llvm/ADT/iterator.h"
61#include "llvm/ADT/iterator_range.h"
Rong Xuf430ae42015-12-09 18:08:16 +000062#include "llvm/Analysis/BlockFrequencyInfo.h"
63#include "llvm/Analysis/BranchProbabilityInfo.h"
64#include "llvm/Analysis/CFG.h"
Chandler Carruth57578aa2019-01-07 07:15:51 +000065#include "llvm/Analysis/IndirectCallVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000066#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000067#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000068#include "llvm/IR/Attributes.h"
69#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000071#include "llvm/IR/CallSite.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000072#include "llvm/IR/Comdat.h"
73#include "llvm/IR/Constant.h"
74#include "llvm/IR/Constants.h"
Rong Xuf430ae42015-12-09 18:08:16 +000075#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000076#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000077#include "llvm/IR/Function.h"
78#include "llvm/IR/GlobalAlias.h"
Rong Xu705f7772016-07-25 18:45:37 +000079#include "llvm/IR/GlobalValue.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000080#include "llvm/IR/GlobalVariable.h"
Rong Xuf430ae42015-12-09 18:08:16 +000081#include "llvm/IR/IRBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000082#include "llvm/IR/InstVisitor.h"
83#include "llvm/IR/InstrTypes.h"
84#include "llvm/IR/Instruction.h"
Rong Xuf430ae42015-12-09 18:08:16 +000085#include "llvm/IR/Instructions.h"
86#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000087#include "llvm/IR/Intrinsics.h"
88#include "llvm/IR/LLVMContext.h"
Rong Xuf430ae42015-12-09 18:08:16 +000089#include "llvm/IR/MDBuilder.h"
90#include "llvm/IR/Module.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000091#include "llvm/IR/PassManager.h"
92#include "llvm/IR/ProfileSummary.h"
93#include "llvm/IR/Type.h"
94#include "llvm/IR/Value.h"
Rong Xuf430ae42015-12-09 18:08:16 +000095#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000096#include "llvm/ProfileData/InstrProf.h"
Rong Xuf430ae42015-12-09 18:08:16 +000097#include "llvm/ProfileData/InstrProfReader.h"
98#include "llvm/Support/BranchProbability.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000099#include "llvm/Support/Casting.h"
100#include "llvm/Support/CommandLine.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000101#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000102#include "llvm/Support/Debug.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000103#include "llvm/Support/Error.h"
104#include "llvm/Support/ErrorHandling.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000105#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000106#include "llvm/Support/JamCRC.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000107#include "llvm/Support/raw_ostream.h"
Rong Xued9fec72016-01-21 18:11:44 +0000108#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000109#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +0000110#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000111#include <cassert>
112#include <cstdint>
113#include <memory>
114#include <numeric>
Rong Xuf430ae42015-12-09 18:08:16 +0000115#include <string>
Rong Xu705f7772016-07-25 18:45:37 +0000116#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +0000117#include <utility>
118#include <vector>
119
120using namespace llvm;
Easwaran Ramane5b8de22018-01-17 22:24:23 +0000121using ProfileCount = Function::ProfileCount;
Rong Xuf430ae42015-12-09 18:08:16 +0000122
123#define DEBUG_TYPE "pgo-instrumentation"
124
125STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000126STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +0000127STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +0000128STATISTIC(NumOfPGOEdge, "Number of edges.");
129STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
130STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
131STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
132STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
133STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000134STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000135
136// Command line option to specify the file to read profile from. This is
137// mainly used for testing.
138static cl::opt<std::string>
139 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
140 cl::value_desc("filename"),
141 cl::desc("Specify the path of profile data file. This is"
142 "mainly for test purpose."));
Richard Smith6c676622018-10-10 23:13:47 +0000143static cl::opt<std::string> PGOTestProfileRemappingFile(
144 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
145 cl::value_desc("filename"),
146 cl::desc("Specify the path of profile remapping file. This is mainly for "
147 "test purpose."));
Rong Xuf430ae42015-12-09 18:08:16 +0000148
Rong Xuecdc98f2016-03-04 22:08:44 +0000149// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000150// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000151static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
152 cl::Hidden,
153 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000154
Rong Xuecdc98f2016-03-04 22:08:44 +0000155// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000156// the metadata for a single indirect call callsite.
157static cl::opt<unsigned> MaxNumAnnotations(
158 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
159 cl::desc("Max number of annotations for a single indirect "
160 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000161
Rong Xue60343d2017-03-17 18:07:26 +0000162// Command line option to set the maximum number of value annotations
163// to write to the metadata for a single memop intrinsic.
164static cl::opt<unsigned> MaxNumMemOPAnnotations(
165 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
166 cl::desc("Max number of preicise value annotations for a single memop"
167 "intrinsic"));
168
Rong Xu705f7772016-07-25 18:45:37 +0000169// Command line option to control appending FunctionHash to the name of a COMDAT
170// function. This is to avoid the hash mismatch caused by the preinliner.
171static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000172 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000173 cl::desc("Append function hash to the name of COMDAT function to avoid "
174 "function hash mismatch due to the preinliner"));
175
Rong Xu0698de92016-05-13 17:26:06 +0000176// Command line option to enable/disable the warning about missing profile
177// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000178static cl::opt<bool>
179 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
180 cl::desc("Use this option to turn on/off "
181 "warnings about missing profile data for "
182 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000183
184// Command line option to enable/disable the warning about a hash mismatch in
185// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000186static cl::opt<bool>
187 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
188 cl::desc("Use this option to turn off/on "
189 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000190
Rong Xu20f5df12017-01-11 20:19:41 +0000191// Command line option to enable/disable the warning about a hash mismatch in
192// the profile data for Comdat functions, which often turns out to be false
193// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000194static cl::opt<bool>
195 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
196 cl::Hidden,
197 cl::desc("The option is used to turn on/off "
198 "warnings about hash mismatch for comdat "
199 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000200
Xinliang David Li4ca17332016-09-18 18:34:07 +0000201// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000202static cl::opt<bool>
203 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
204 cl::desc("Use this option to turn on/off SELECT "
205 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000206
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000207// Command line option to turn on CFG dot or text dump of raw profile counts
208static cl::opt<PGOViewCountsType> PGOViewRawCounts(
209 "pgo-view-raw-counts", cl::Hidden,
210 cl::desc("A boolean option to show CFG dag or text "
211 "with raw profile counts from "
212 "profile data. See also option "
213 "-pgo-view-counts. To limit graph "
214 "display to only one function, use "
215 "filtering option -view-bfi-func-name."),
216 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
217 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
218 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000219
Rong Xu8e06e802017-03-17 20:51:44 +0000220// Command line option to enable/disable memop intrinsic call.size profiling.
221static cl::opt<bool>
222 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
223 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000224 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000225
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000226// Emit branch probability as optimization remarks.
227static cl::opt<bool>
228 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
229 cl::desc("When this option is on, the annotated "
230 "branch probability will be emitted as "
Rong Xu662f38b2018-03-27 18:55:56 +0000231 "optimization remarks: -{Rpass|"
232 "pass-remarks}=pgo-instrumentation"));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000233
Xinliang David Licb253ce2017-01-23 18:58:24 +0000234// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000235// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000236extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000237
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000238// Command line option to specify the name of the function for CFG dump
239// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
240extern cl::opt<std::string> ViewBlockFreqFuncName;
241
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000242// Return a string describing the branch condition that can be
243// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000244static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000245 BranchInst *BI = dyn_cast<BranchInst>(TI);
246 if (!BI || !BI->isConditional())
247 return std::string();
248
249 Value *Cond = BI->getCondition();
250 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
251 if (!CI)
252 return std::string();
253
254 std::string result;
255 raw_string_ostream OS(result);
256 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
257 CI->getOperand(0)->getType()->print(OS, true);
258
259 Value *RHS = CI->getOperand(1);
260 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
261 if (CV) {
262 if (CV->isZero())
263 OS << "_Zero";
264 else if (CV->isOne())
265 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000266 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000267 OS << "_MinusOne";
268 else
269 OS << "_Const";
270 }
271 OS.flush();
272 return result;
273}
274
Eugene Zelenkofce43572017-10-21 00:57:46 +0000275namespace {
276
Xinliang David Li4ca17332016-09-18 18:34:07 +0000277/// The select instruction visitor plays three roles specified
278/// by the mode. In \c VM_counting mode, it simply counts the number of
279/// select instructions. In \c VM_instrument mode, it inserts code to count
280/// the number times TrueValue of select is taken. In \c VM_annotate mode,
281/// it reads the profile data and annotate the select instruction with metadata.
282enum VisitMode { VM_counting, VM_instrument, VM_annotate };
283class PGOUseFunc;
284
285/// Instruction Visitor class to visit select instructions.
286struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
287 Function &F;
288 unsigned NSIs = 0; // Number of select instructions instrumented.
289 VisitMode Mode = VM_counting; // Visiting mode.
290 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
291 unsigned TotalNumCtrs = 0; // Total number of counters
292 GlobalVariable *FuncNameVar = nullptr;
293 uint64_t FuncHash = 0;
294 PGOUseFunc *UseFunc = nullptr;
295
296 SelectInstVisitor(Function &Func) : F(Func) {}
297
298 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000299 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000300 Mode = VM_counting;
301 visit(Func);
302 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000303
Xinliang David Li4ca17332016-09-18 18:34:07 +0000304 // Visit the IR stream and instrument all select instructions. \p
305 // Ind is a pointer to the counter index variable; \p TotalNC
306 // is the total number of counters; \p FNV is the pointer to the
307 // PGO function name var; \p FHash is the function hash.
308 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
309 GlobalVariable *FNV, uint64_t FHash) {
310 Mode = VM_instrument;
311 CurCtrIdx = Ind;
312 TotalNumCtrs = TotalNC;
313 FuncHash = FHash;
314 FuncNameVar = FNV;
315 visit(Func);
316 }
317
318 // Visit the IR stream and annotate all select instructions.
319 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
320 Mode = VM_annotate;
321 UseFunc = UF;
322 CurCtrIdx = Ind;
323 visit(Func);
324 }
325
326 void instrumentOneSelectInst(SelectInst &SI);
327 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000328
Xinliang David Li4ca17332016-09-18 18:34:07 +0000329 // Visit \p SI instruction and perform tasks according to visit mode.
330 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000331
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000332 // Return the number of select instructions. This needs be called after
333 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000334 unsigned getNumOfSelectInsts() const { return NSIs; }
335};
336
Rong Xu60faea12017-03-16 21:15:48 +0000337/// Instruction Visitor class to visit memory intrinsic calls.
338struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
339 Function &F;
340 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
341 VisitMode Mode = VM_counting; // Visiting mode.
342 unsigned CurCtrId = 0; // Current counter index.
343 unsigned TotalNumCtrs = 0; // Total number of counters
344 GlobalVariable *FuncNameVar = nullptr;
345 uint64_t FuncHash = 0;
346 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000347 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000348
349 MemIntrinsicVisitor(Function &Func) : F(Func) {}
350
351 void countMemIntrinsics(Function &Func) {
352 NMemIs = 0;
353 Mode = VM_counting;
354 visit(Func);
355 }
Rong Xue60343d2017-03-17 18:07:26 +0000356
Rong Xu60faea12017-03-16 21:15:48 +0000357 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
358 GlobalVariable *FNV, uint64_t FHash) {
359 Mode = VM_instrument;
360 TotalNumCtrs = TotalNC;
361 FuncHash = FHash;
362 FuncNameVar = FNV;
363 visit(Func);
364 }
365
Rong Xue60343d2017-03-17 18:07:26 +0000366 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
367 Candidates.clear();
368 Mode = VM_annotate;
369 visit(Func);
370 return Candidates;
371 }
372
Rong Xu60faea12017-03-16 21:15:48 +0000373 // Visit the IR stream and annotate all mem intrinsic call instructions.
374 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000375
Rong Xu60faea12017-03-16 21:15:48 +0000376 // Visit \p MI instruction and perform tasks according to visit mode.
377 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000378
Rong Xu60faea12017-03-16 21:15:48 +0000379 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
380};
381
Xinliang David Li8aebf442016-05-06 05:49:19 +0000382class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000383public:
384 static char ID;
385
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000386 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000387 initializePGOInstrumentationGenLegacyPassPass(
388 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000389 }
390
Mehdi Amini117296c2016-10-01 02:56:57 +0000391 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000392
393private:
394 bool runOnModule(Module &M) override;
395
396 void getAnalysisUsage(AnalysisUsage &AU) const override {
397 AU.addRequired<BlockFrequencyInfoWrapperPass>();
398 }
399};
400
Xinliang David Lid55827f2016-05-07 05:39:12 +0000401class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000402public:
403 static char ID;
404
405 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000406 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000407 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000408 if (!PGOTestProfileFile.empty())
409 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000410 initializePGOInstrumentationUseLegacyPassPass(
411 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000412 }
413
Mehdi Amini117296c2016-10-01 02:56:57 +0000414 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000415
416private:
417 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000418
Xinliang David Lida195582016-05-10 21:59:52 +0000419 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000420
Rong Xuf430ae42015-12-09 18:08:16 +0000421 void getAnalysisUsage(AnalysisUsage &AU) const override {
422 AU.addRequired<BlockFrequencyInfoWrapperPass>();
423 }
424};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000425
Rong Xuf430ae42015-12-09 18:08:16 +0000426} // end anonymous namespace
427
Xinliang David Li8aebf442016-05-06 05:49:19 +0000428char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000429
Xinliang David Li8aebf442016-05-06 05:49:19 +0000430INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000431 "PGO instrumentation.", false, false)
432INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000433INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000434INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000435 "PGO instrumentation.", false, false)
436
Xinliang David Li8aebf442016-05-06 05:49:19 +0000437ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
438 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000439}
440
Xinliang David Lid55827f2016-05-07 05:39:12 +0000441char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000442
Xinliang David Lid55827f2016-05-07 05:39:12 +0000443INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000444 "Read PGO instrumentation profile.", false, false)
445INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000446INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000447INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000448 "Read PGO instrumentation profile.", false, false)
449
Xinliang David Lid55827f2016-05-07 05:39:12 +0000450ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
451 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000452}
453
454namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000455
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000456/// An MST based instrumentation for PGO
Rong Xuf430ae42015-12-09 18:08:16 +0000457///
458/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
459/// in the function level.
460struct PGOEdge {
461 // This class implements the CFG edges. Note the CFG can be a multi-graph.
462 // So there might be multiple edges with same SrcBB and DestBB.
463 const BasicBlock *SrcBB;
464 const BasicBlock *DestBB;
465 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000466 bool InMST = false;
467 bool Removed = false;
468 bool IsCritical = false;
469
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000470 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000471 : SrcBB(Src), DestBB(Dest), Weight(W) {}
472
Rong Xuf430ae42015-12-09 18:08:16 +0000473 // Return the information string of an edge.
474 const std::string infoString() const {
475 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
476 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
477 }
478};
479
480// This class stores the auxiliary information for each BB.
481struct BBInfo {
482 BBInfo *Group;
483 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000484 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000485
Eugene Zelenkofce43572017-10-21 00:57:46 +0000486 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000487
488 // Return the information string of this object.
489 const std::string infoString() const {
490 return (Twine("Index=") + Twine(Index)).str();
491 }
492};
493
494// This class implements the CFG edges. Note the CFG can be a multi-graph.
495template <class Edge, class BBInfo> class FuncPGOInstrumentation {
496private:
497 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000498
Rong Xu705f7772016-07-25 18:45:37 +0000499 // A map that stores the Comdat group in function F.
500 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000501
Eugene Zelenkofce43572017-10-21 00:57:46 +0000502 void computeCFGHash();
503 void renameComdatFunction();
504
Rong Xuf430ae42015-12-09 18:08:16 +0000505public:
Rong Xua3bbf962017-03-15 18:23:39 +0000506 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000507 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000508 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000509 std::string FuncName;
510 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000511
Rong Xuf430ae42015-12-09 18:08:16 +0000512 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000513 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000514
515 // The Minimum Spanning Tree of function CFG.
516 CFGMST<Edge, BBInfo> MST;
517
518 // Give an edge, find the BB that will be instrumented.
519 // Return nullptr if there is no BB to be instrumented.
520 BasicBlock *getInstrBB(Edge *E);
521
522 // Return the auxiliary BB information.
523 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
524
Rong Xua5b57452016-12-02 19:10:29 +0000525 // Return the auxiliary BB information if available.
526 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
527
Rong Xuf430ae42015-12-09 18:08:16 +0000528 // Dump edges and BB information.
529 void dumpInfo(std::string Str = "") const {
530 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000531 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000532 }
533
Rong Xu705f7772016-07-25 18:45:37 +0000534 FuncPGOInstrumentation(
535 Function &Func,
536 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000537 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
538 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000539 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000540 SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000541 // This should be done before CFG hash computation.
542 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000543 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000544 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000545 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Chandler Carruth57578aa2019-01-07 07:15:51 +0000546 ValueSites[IPVK_IndirectCallTarget] = findIndirectCalls(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000547 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000548
Rong Xuf430ae42015-12-09 18:08:16 +0000549 FuncName = getPGOFuncName(F);
550 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000551 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000552 renameComdatFunction();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000553 LLVM_DEBUG(dumpInfo("after CFGMST"));
Rong Xuf430ae42015-12-09 18:08:16 +0000554
555 NumOfPGOBB += MST.BBInfos.size();
556 for (auto &E : MST.AllEdges) {
557 if (E->Removed)
558 continue;
559 NumOfPGOEdge++;
560 if (!E->InMST)
561 NumOfPGOInstrument++;
562 }
563
564 if (CreateGlobalVar)
565 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000566 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000567
568 // Return the number of profile counters needed for the function.
569 unsigned getNumCounters() {
570 unsigned NumCounters = 0;
571 for (auto &E : this->MST.AllEdges) {
572 if (!E->InMST && !E->Removed)
573 NumCounters++;
574 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000575 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000576 }
Rong Xuf430ae42015-12-09 18:08:16 +0000577};
578
Eugene Zelenkofce43572017-10-21 00:57:46 +0000579} // end anonymous namespace
580
Rong Xuf430ae42015-12-09 18:08:16 +0000581// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
582// value of each BB in the CFG. The higher 32 bits record the number of edges.
583template <class Edge, class BBInfo>
584void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
585 std::vector<char> Indexes;
586 JamCRC JC;
587 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000588 const Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000589 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
590 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000591 auto BI = findBBInfo(Succ);
592 if (BI == nullptr)
593 continue;
594 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000595 for (int J = 0; J < 4; J++)
596 Indexes.push_back((char)(Index >> (J * 8)));
597 }
598 }
599 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000600 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000601 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000602 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000603 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
604 << " CRC = " << JC.getCRC()
605 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
606 << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
607 << ValueSites[IPVK_IndirectCallTarget].size()
608 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000609}
610
611// Check if we can safely rename this Comdat function.
612static bool canRenameComdat(
613 Function &F,
614 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000615 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000616 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000617
618 // FIXME: Current only handle those Comdat groups that only containing one
619 // function and function aliases.
620 // (1) For a Comdat group containing multiple functions, we need to have a
621 // unique postfix based on the hashes for each function. There is a
622 // non-trivial code refactoring to do this efficiently.
623 // (2) Variables can not be renamed, so we can not rename Comdat function in a
624 // group including global vars.
625 Comdat *C = F.getComdat();
626 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
627 if (dyn_cast<GlobalAlias>(CM.second))
628 continue;
629 Function *FM = dyn_cast<Function>(CM.second);
630 if (FM != &F)
631 return false;
632 }
633 return true;
634}
635
636// Append the CFGHash to the Comdat function name.
637template <class Edge, class BBInfo>
638void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
639 if (!canRenameComdat(F, ComdatMembers))
640 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000641 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000642 std::string NewFuncName =
643 Twine(F.getName() + "." + Twine(FunctionHash)).str();
644 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000645 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000646 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
647 Comdat *NewComdat;
648 Module *M = F.getParent();
649 // For AvailableExternallyLinkage functions, change the linkage to
650 // LinkOnceODR and put them into comdat. This is because after renaming, there
651 // is no backup external copy available for the function.
652 if (!F.hasComdat()) {
653 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
654 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
655 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
656 F.setComdat(NewComdat);
657 return;
658 }
659
660 // This function belongs to a single function Comdat group.
661 Comdat *OrigComdat = F.getComdat();
662 std::string NewComdatName =
663 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
664 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
665 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
666
667 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
668 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
669 // For aliases, change the name directly.
670 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000671 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000672 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000673 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000674 continue;
675 }
676 // Must be a function.
677 Function *CF = dyn_cast<Function>(CM.second);
678 assert(CF);
679 CF->setComdat(NewComdat);
680 }
Rong Xuf430ae42015-12-09 18:08:16 +0000681}
682
683// Given a CFG E to be instrumented, find which BB to place the instrumented
684// code. The function will split the critical edge if necessary.
685template <class Edge, class BBInfo>
686BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
687 if (E->InMST || E->Removed)
688 return nullptr;
689
690 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
691 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
692 // For a fake edge, instrument the real BB.
693 if (SrcBB == nullptr)
694 return DestBB;
695 if (DestBB == nullptr)
696 return SrcBB;
697
698 // Instrument the SrcBB if it has a single successor,
699 // otherwise, the DestBB if this is not a critical edge.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000700 Instruction *TI = SrcBB->getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000701 if (TI->getNumSuccessors() <= 1)
702 return SrcBB;
703 if (!E->IsCritical)
704 return DestBB;
705
706 // For a critical edge, we have to split. Instrument the newly
707 // created BB.
708 NumOfPGOSplit++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000709 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
710 << " --> " << getBBInfo(DestBB).Index << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000711 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
712 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
713 assert(InstrBB && "Critical edge is not split");
714
715 E->Removed = true;
716 return InstrBB;
717}
718
Rong Xued9fec72016-01-21 18:11:44 +0000719// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000720// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000721static void instrumentOneFunc(
Xinliang David Lid91057b2017-12-08 19:38:07 +0000722 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Rong Xu705f7772016-07-25 18:45:37 +0000723 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000724 // Split indirectbr critical edges here before computing the MST rather than
725 // later in getInstrBB() to avoid invalidating it.
726 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +0000727 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
728 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000729 unsigned NumCounters = FuncInfo.getNumCounters();
730
Rong Xuf430ae42015-12-09 18:08:16 +0000731 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000732 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000733 for (auto &E : FuncInfo.MST.AllEdges) {
734 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
735 if (!InstrBB)
736 continue;
737
738 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
739 assert(Builder.GetInsertPoint() != InstrBB->end() &&
740 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000741 Builder.CreateCall(
742 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000743 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000744 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
745 Builder.getInt32(I++)});
746 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000747
748 // Now instrument select instructions:
749 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
750 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000751 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000752
753 if (DisableValueProfiling)
754 return;
755
Chandler Carruth57578aa2019-01-07 07:15:51 +0000756 unsigned NumIndirectCalls = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000757 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000758 CallSite CS(I);
759 Value *Callee = CS.getCalledValue();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000760 LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
Chandler Carruth57578aa2019-01-07 07:15:51 +0000761 << NumIndirectCalls << "\n");
Rong Xued9fec72016-01-21 18:11:44 +0000762 IRBuilder<> Builder(I);
763 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
764 "Cannot get the Instrumentation point");
765 Builder.CreateCall(
766 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000767 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000768 Builder.getInt64(FuncInfo.FunctionHash),
769 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000770 Builder.getInt32(IPVK_IndirectCallTarget),
Chandler Carruth57578aa2019-01-07 07:15:51 +0000771 Builder.getInt32(NumIndirectCalls++)});
Rong Xued9fec72016-01-21 18:11:44 +0000772 }
Chandler Carruth57578aa2019-01-07 07:15:51 +0000773 NumOfPGOICall += NumIndirectCalls;
Rong Xu60faea12017-03-16 21:15:48 +0000774
775 // Now instrument memop intrinsic calls.
776 FuncInfo.MIVisitor.instrumentMemIntrinsics(
777 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000778}
779
Eugene Zelenkofce43572017-10-21 00:57:46 +0000780namespace {
781
Rong Xuf430ae42015-12-09 18:08:16 +0000782// This class represents a CFG edge in profile use compilation.
783struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000784 bool CountValid = false;
785 uint64_t CountValue = 0;
786
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000787 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000788 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000789
790 // Set edge count value
791 void setEdgeCount(uint64_t Value) {
792 CountValue = Value;
793 CountValid = true;
794 }
795
796 // Return the information string for this object.
797 const std::string infoString() const {
798 if (!CountValid)
799 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000800 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
801 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000802 }
803};
804
Eugene Zelenkofce43572017-10-21 00:57:46 +0000805using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000806
807// This class stores the auxiliary information for each BB.
808struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000809 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000810 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000811 int32_t UnknownCountInEdge = 0;
812 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000813 DirectEdges InEdges;
814 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000815
816 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
817
Rong Xuf430ae42015-12-09 18:08:16 +0000818 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000819 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000820
821 // Set the profile count value for this BB.
822 void setBBInfoCount(uint64_t Value) {
823 CountValue = Value;
824 CountValid = true;
825 }
826
827 // Return the information string of this object.
828 const std::string infoString() const {
829 if (!CountValid)
830 return BBInfo::infoString();
831 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
832 }
833};
834
Eugene Zelenkofce43572017-10-21 00:57:46 +0000835} // end anonymous namespace
836
Rong Xuf430ae42015-12-09 18:08:16 +0000837// Sum up the count values for all the edges.
838static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
839 uint64_t Total = 0;
840 for (auto &E : Edges) {
841 if (E->Removed)
842 continue;
843 Total += E->CountValue;
844 }
845 return Total;
846}
847
Eugene Zelenkofce43572017-10-21 00:57:46 +0000848namespace {
849
Rong Xuf430ae42015-12-09 18:08:16 +0000850class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000851public:
Rong Xu705f7772016-07-25 18:45:37 +0000852 PGOUseFunc(Function &Func, Module *Modu,
853 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000854 BranchProbabilityInfo *BPI = nullptr,
Xinliang David Li45c81902017-12-05 21:54:01 +0000855 BlockFrequencyInfo *BFIin = nullptr)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000856 : F(Func), M(Modu), BFI(BFIin),
Xinliang David Lid91057b2017-12-08 19:38:07 +0000857 FuncInfo(Func, ComdatMembers, false, BPI, BFIin),
858 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000859
860 // Read counts for the instrumented BB from profile.
Rong Xufb4bcc42018-11-07 23:51:20 +0000861 bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros);
Rong Xu6090afd2016-03-28 17:08:56 +0000862
863 // Populate the counts for all BBs.
864 void populateCounters();
865
866 // Set the branch weights based on the count values.
867 void setBranchWeights();
868
Hiroshi Inoueae179002018-04-14 08:59:00 +0000869 // Annotate the value profile call sites for all value kind.
Rong Xua3bbf962017-03-15 18:23:39 +0000870 void annotateValueSites();
871
872 // Annotate the value profile call sites for one value kind.
873 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000874
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000875 // Annotate the irreducible loop header weights.
876 void annotateIrrLoopHeaderWeights();
877
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000878 // The hotness of the function from the profile count.
879 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
880
881 // Return the function hotness from the profile.
882 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
883
Rong Xu705f7772016-07-25 18:45:37 +0000884 // Return the function hash.
885 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000886
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000887 // Return the profile record for this function;
888 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
889
Xinliang David Li4ca17332016-09-18 18:34:07 +0000890 // Return the auxiliary BB information.
891 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
892 return FuncInfo.getBBInfo(BB);
893 }
894
Rong Xua5b57452016-12-02 19:10:29 +0000895 // Return the auxiliary BB information if available.
896 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
897 return FuncInfo.findBBInfo(BB);
898 }
899
Xinliang David Lid289e452017-01-27 19:06:25 +0000900 Function &getFunc() const { return F; }
901
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000902 void dumpInfo(std::string Str = "") const {
903 FuncInfo.dumpInfo(Str);
904 }
905
Rong Xufb4bcc42018-11-07 23:51:20 +0000906 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
Rong Xuf430ae42015-12-09 18:08:16 +0000907private:
908 Function &F;
909 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000910 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000911
Rong Xuf430ae42015-12-09 18:08:16 +0000912 // This member stores the shared information with class PGOGenFunc.
913 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
914
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000915 // The maximum count value in the profile. This is only used in PGO use
916 // compilation.
917 uint64_t ProgramMaxCount;
918
Rong Xu33308f92016-10-25 21:47:24 +0000919 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000920 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000921
922 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000923 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000924
Rong Xu13b01dc2016-02-10 18:24:45 +0000925 // ProfileRecord for this function.
926 InstrProfRecord ProfileRecord;
927
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000928 // Function hotness info derived from profile.
929 FuncFreqAttr FreqAttr;
930
Rong Xuf430ae42015-12-09 18:08:16 +0000931 // Find the Instrumented BB and set the value.
932 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
933
934 // Set the edge counter value for the unknown edge -- there should be only
935 // one unknown edge.
936 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
937
938 // Return FuncName string;
939 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000940
941 // Set the hot/cold inline hints based on the count values.
942 // FIXME: This function should be removed once the functionality in
943 // the inliner is implemented.
944 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
945 if (ProgramMaxCount == 0)
946 return;
947 // Threshold of the hot functions.
948 const BranchProbability HotFunctionThreshold(1, 100);
949 // Threshold of the cold functions.
950 const BranchProbability ColdFunctionThreshold(2, 10000);
951 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
952 FreqAttr = FFA_Hot;
953 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
954 FreqAttr = FFA_Cold;
955 }
Rong Xuf430ae42015-12-09 18:08:16 +0000956};
957
Eugene Zelenkofce43572017-10-21 00:57:46 +0000958} // end anonymous namespace
959
Rong Xuf430ae42015-12-09 18:08:16 +0000960// Visit all the edges and assign the count value for the instrumented
961// edges and the BB.
962void PGOUseFunc::setInstrumentedCounts(
963 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +0000964 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000965 // Use a worklist as we will update the vector during the iteration.
966 std::vector<PGOUseEdge *> WorkList;
967 for (auto &E : FuncInfo.MST.AllEdges)
968 WorkList.push_back(E.get());
969
970 uint32_t I = 0;
971 for (auto &E : WorkList) {
972 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
973 if (!InstrBB)
974 continue;
975 uint64_t CountValue = CountFromProfile[I++];
976 if (!E->Removed) {
977 getBBInfo(InstrBB).setBBInfoCount(CountValue);
978 E->setEdgeCount(CountValue);
979 continue;
980 }
981
982 // Need to add two new edges.
983 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
984 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
985 // Add new edge of SrcBB->InstrBB.
986 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
987 NewEdge.setEdgeCount(CountValue);
988 // Add new edge of InstrBB->DestBB.
989 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
990 NewEdge1.setEdgeCount(CountValue);
991 NewEdge1.InMST = true;
992 getBBInfo(InstrBB).setBBInfoCount(CountValue);
993 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000994 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000995 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000996}
997
998// Set the count value for the unknown edge. There should be one and only one
999// unknown edge in Edges vector.
1000void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1001 for (auto &E : Edges) {
1002 if (E->CountValid)
1003 continue;
1004 E->setEdgeCount(Value);
1005
1006 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1007 getBBInfo(E->DestBB).UnknownCountInEdge--;
1008 return;
1009 }
1010 llvm_unreachable("Cannot find the unknown count edge");
1011}
1012
1013// Read the profile from ProfileFileName and assign the value to the
1014// instrumented BB and the edges. This function also updates ProgramMaxCount.
1015// Return true if the profile are successfully read, and false on errors.
Rong Xufb4bcc42018-11-07 23:51:20 +00001016bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros) {
Rong Xuf430ae42015-12-09 18:08:16 +00001017 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001018 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001019 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001020 if (Error E = Result.takeError()) {
1021 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1022 auto Err = IPE.get();
1023 bool SkipWarning = false;
1024 if (Err == instrprof_error::unknown_function) {
1025 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001026 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +00001027 } else if (Err == instrprof_error::hash_mismatch ||
1028 Err == instrprof_error::malformed) {
1029 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001030 SkipWarning =
1031 NoPGOWarnMismatch ||
1032 (NoPGOWarnMismatchComdat &&
1033 (F.hasComdat() ||
1034 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +00001035 }
Rong Xuf430ae42015-12-09 18:08:16 +00001036
Vedant Kumar9152fd12016-05-19 03:54:45 +00001037 if (SkipWarning)
1038 return;
1039
1040 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1041 Ctx.diagnose(
1042 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1043 });
Rong Xuf430ae42015-12-09 18:08:16 +00001044 return false;
1045 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001046 ProfileRecord = std::move(Result.get());
1047 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001048
1049 NumOfPGOFunc++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001050 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001051 uint64_t ValueSum = 0;
1052 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001053 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001054 ValueSum += CountFromProfile[I];
1055 }
Rong Xufb4bcc42018-11-07 23:51:20 +00001056 AllZeros = (ValueSum == 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001057
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001058 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001059
1060 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1061 getBBInfo(nullptr).UnknownCountInEdge = 2;
1062
1063 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001064 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +00001065 return true;
1066}
1067
1068// Populate the counters from instrumented BBs to all BBs.
1069// In the end of this operation, all BBs should have a valid count value.
1070void PGOUseFunc::populateCounters() {
1071 // First set up Count variable for all BBs.
1072 for (auto &E : FuncInfo.MST.AllEdges) {
1073 if (E->Removed)
1074 continue;
1075
1076 const BasicBlock *SrcBB = E->SrcBB;
1077 const BasicBlock *DestBB = E->DestBB;
1078 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1079 UseBBInfo &DestInfo = getBBInfo(DestBB);
1080 SrcInfo.OutEdges.push_back(E.get());
1081 DestInfo.InEdges.push_back(E.get());
1082 SrcInfo.UnknownCountOutEdge++;
1083 DestInfo.UnknownCountInEdge++;
1084
1085 if (!E->CountValid)
1086 continue;
1087 DestInfo.UnknownCountInEdge--;
1088 SrcInfo.UnknownCountOutEdge--;
1089 }
1090
1091 bool Changes = true;
1092 unsigned NumPasses = 0;
1093 while (Changes) {
1094 NumPasses++;
1095 Changes = false;
1096
1097 // For efficient traversal, it's better to start from the end as most
1098 // of the instrumented edges are at the end.
1099 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001100 UseBBInfo *Count = findBBInfo(&BB);
1101 if (Count == nullptr)
1102 continue;
1103 if (!Count->CountValid) {
1104 if (Count->UnknownCountOutEdge == 0) {
1105 Count->CountValue = sumEdgeCount(Count->OutEdges);
1106 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001107 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001108 } else if (Count->UnknownCountInEdge == 0) {
1109 Count->CountValue = sumEdgeCount(Count->InEdges);
1110 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001111 Changes = true;
1112 }
1113 }
Rong Xua5b57452016-12-02 19:10:29 +00001114 if (Count->CountValid) {
1115 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001116 uint64_t Total = 0;
1117 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1118 // If the one of the successor block can early terminate (no-return),
1119 // we can end up with situation where out edge sum count is larger as
1120 // the source BB's count is collected by a post-dominated block.
1121 if (Count->CountValue > OutSum)
1122 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001123 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001124 Changes = true;
1125 }
Rong Xua5b57452016-12-02 19:10:29 +00001126 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001127 uint64_t Total = 0;
1128 uint64_t InSum = sumEdgeCount(Count->InEdges);
1129 if (Count->CountValue > InSum)
1130 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001131 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001132 Changes = true;
1133 }
1134 }
1135 }
1136 }
1137
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001138 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001139#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001140 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001141 for (auto &BB : F) {
1142 auto BI = findBBInfo(&BB);
1143 if (BI == nullptr)
1144 continue;
1145 assert(BI->CountValid && "BB count is not valid");
1146 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001147#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001148 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001149 F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001150 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001151 for (auto &BB : F) {
1152 auto BI = findBBInfo(&BB);
1153 if (BI == nullptr)
1154 continue;
1155 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1156 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001157 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001158
Rong Xu33308f92016-10-25 21:47:24 +00001159 // Now annotate select instructions
1160 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1161 assert(CountPosition == ProfileCountSize);
1162
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001163 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
Rong Xuf430ae42015-12-09 18:08:16 +00001164}
1165
1166// Assign the scaled count values to the BB with multiple out edges.
1167void PGOUseFunc::setBranchWeights() {
1168 // Generate MD_prof metadata for every branch instruction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001169 LLVM_DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001170 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001171 Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +00001172 if (TI->getNumSuccessors() < 2)
1173 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001174 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1175 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001176 continue;
1177 if (getBBInfo(&BB).CountValue == 0)
1178 continue;
1179
1180 // We have a non-zero Branch BB.
1181 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1182 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001183 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001184 uint64_t MaxCount = 0;
1185 for (unsigned s = 0; s < Size; s++) {
1186 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1187 const BasicBlock *SrcBB = E->SrcBB;
1188 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001189 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001190 continue;
1191 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1192 uint64_t EdgeCount = E->CountValue;
1193 if (EdgeCount > MaxCount)
1194 MaxCount = EdgeCount;
1195 EdgeCounts[SuccNum] = EdgeCount;
1196 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001197 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001198 }
1199}
Rong Xu13b01dc2016-02-10 18:24:45 +00001200
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001201static bool isIndirectBrTarget(BasicBlock *BB) {
1202 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1203 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1204 return true;
1205 }
1206 return false;
1207}
1208
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001209void PGOUseFunc::annotateIrrLoopHeaderWeights() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001210 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001211 // Find irr loop headers
1212 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001213 // As a heuristic also annotate indrectbr targets as they have a high chance
1214 // to become an irreducible loop header after the indirectbr tail
1215 // duplication.
1216 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001217 Instruction *TI = BB.getTerminator();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001218 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1219 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1220 }
1221 }
1222}
1223
Xinliang David Li4ca17332016-09-18 18:34:07 +00001224void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1225 Module *M = F.getParent();
1226 IRBuilder<> Builder(&SI);
1227 Type *Int64Ty = Builder.getInt64Ty();
1228 Type *I8PtrTy = Builder.getInt8PtrTy();
1229 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1230 Builder.CreateCall(
1231 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001232 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001233 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1234 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001235 ++(*CurCtrIdx);
1236}
1237
1238void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1239 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1240 assert(*CurCtrIdx < CountFromProfile.size() &&
1241 "Out of bound access of counters");
1242 uint64_t SCounts[2];
1243 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1244 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001245 uint64_t TotalCount = 0;
1246 auto BI = UseFunc->findBBInfo(SI.getParent());
1247 if (BI != nullptr)
1248 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001249 // False Count
1250 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1251 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001252 if (MaxCount)
1253 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001254}
1255
1256void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1257 if (!PGOInstrSelect)
1258 return;
1259 // FIXME: do not handle this yet.
1260 if (SI.getCondition()->getType()->isVectorTy())
1261 return;
1262
Xinliang David Li4ca17332016-09-18 18:34:07 +00001263 switch (Mode) {
1264 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001265 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001266 return;
1267 case VM_instrument:
1268 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001269 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001270 case VM_annotate:
1271 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001272 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001273 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001274
1275 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001276}
1277
Rong Xu60faea12017-03-16 21:15:48 +00001278void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1279 Module *M = F.getParent();
1280 IRBuilder<> Builder(&MI);
1281 Type *Int64Ty = Builder.getInt64Ty();
1282 Type *I8PtrTy = Builder.getInt8PtrTy();
1283 Value *Length = MI.getLength();
1284 assert(!dyn_cast<ConstantInt>(Length));
1285 Builder.CreateCall(
1286 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001287 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001288 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001289 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1290 ++CurCtrId;
1291}
1292
1293void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1294 if (!PGOInstrMemOP)
1295 return;
1296 Value *Length = MI.getLength();
1297 // Not instrument constant length calls.
1298 if (dyn_cast<ConstantInt>(Length))
1299 return;
1300
1301 switch (Mode) {
1302 case VM_counting:
1303 NMemIs++;
1304 return;
1305 case VM_instrument:
1306 instrumentOneMemIntrinsic(MI);
1307 return;
1308 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001309 Candidates.push_back(&MI);
1310 return;
Rong Xu60faea12017-03-16 21:15:48 +00001311 }
1312 llvm_unreachable("Unknown visiting mode");
1313}
1314
Rong Xua3bbf962017-03-15 18:23:39 +00001315// Traverse all valuesites and annotate the instructions for all value kind.
1316void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001317 if (DisableValueProfiling)
1318 return;
1319
Rong Xu8e8fe852016-04-01 16:43:30 +00001320 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001321 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001322
Rong Xua3bbf962017-03-15 18:23:39 +00001323 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001324 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001325}
1326
1327// Annotate the instructions for a specific value kind.
1328void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1329 unsigned ValueSiteIndex = 0;
1330 auto &ValueSites = FuncInfo.ValueSites[Kind];
1331 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1332 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001333 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001334 Ctx.diagnose(DiagnosticInfoPGOProfile(
1335 M->getName().data(),
1336 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1337 " in " + F.getName().str(),
1338 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001339 return;
1340 }
1341
Rong Xua3bbf962017-03-15 18:23:39 +00001342 for (auto &I : ValueSites) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001343 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1344 << "): Index = " << ValueSiteIndex << " out of "
1345 << NumValueSites << "\n");
Rong Xua3bbf962017-03-15 18:23:39 +00001346 annotateValueSite(*M, *I, ProfileRecord,
1347 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001348 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1349 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001350 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001351 }
1352}
Rong Xuf430ae42015-12-09 18:08:16 +00001353
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001354// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001355// aware this is an ir_level profile so it can set the version flag.
1356static void createIRLevelProfileFlagVariable(Module &M) {
1357 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1358 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001359 auto IRLevelVersionVariable = new GlobalVariable(
1360 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1361 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001362 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001363 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1364 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001365 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001366 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001367 else
Rong Xu9e926e82016-02-29 19:16:04 +00001368 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001369 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001370}
1371
Rong Xu705f7772016-07-25 18:45:37 +00001372// Collect the set of members for each Comdat in module M and store
1373// in ComdatMembers.
1374static void collectComdatMembers(
1375 Module &M,
1376 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1377 if (!DoComdatRenaming)
1378 return;
1379 for (Function &F : M)
1380 if (Comdat *C = F.getComdat())
1381 ComdatMembers.insert(std::make_pair(C, &F));
1382 for (GlobalVariable &GV : M.globals())
1383 if (Comdat *C = GV.getComdat())
1384 ComdatMembers.insert(std::make_pair(C, &GV));
1385 for (GlobalAlias &GA : M.aliases())
1386 if (Comdat *C = GA.getComdat())
1387 ComdatMembers.insert(std::make_pair(C, &GA));
1388}
1389
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001390static bool InstrumentAllFunctions(
Xinliang David Lid91057b2017-12-08 19:38:07 +00001391 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1392 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001393 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001394 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1395 collectComdatMembers(M, ComdatMembers);
1396
Rong Xuf430ae42015-12-09 18:08:16 +00001397 for (auto &F : M) {
1398 if (F.isDeclaration())
1399 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001400 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001401 auto *BFI = LookupBFI(F);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001402 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001403 }
1404 return true;
1405}
1406
Xinliang David Li8aebf442016-05-06 05:49:19 +00001407bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001408 if (skipModule(M))
1409 return false;
1410
Xinliang David Lid91057b2017-12-08 19:38:07 +00001411 auto LookupBPI = [this](Function &F) {
1412 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1413 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001414 auto LookupBFI = [this](Function &F) {
1415 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001416 };
Xinliang David Lid91057b2017-12-08 19:38:07 +00001417 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001418}
1419
Xinliang David Li8aebf442016-05-06 05:49:19 +00001420PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001421 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001422 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001423 auto LookupBPI = [&FAM](Function &F) {
1424 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1425 };
Xinliang David Li8aebf442016-05-06 05:49:19 +00001426
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001427 auto LookupBFI = [&FAM](Function &F) {
1428 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001429 };
1430
Xinliang David Lid91057b2017-12-08 19:38:07 +00001431 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001432 return PreservedAnalyses::all();
1433
1434 return PreservedAnalyses::none();
1435}
1436
Xinliang David Lida195582016-05-10 21:59:52 +00001437static bool annotateAllFunctions(
Richard Smith6c676622018-10-10 23:13:47 +00001438 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
Xinliang David Lid91057b2017-12-08 19:38:07 +00001439 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Li45c81902017-12-05 21:54:01 +00001440 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001441 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
Rong Xuf430ae42015-12-09 18:08:16 +00001442 auto &Ctx = M.getContext();
1443 // Read the counter array from file.
Richard Smith6c676622018-10-10 23:13:47 +00001444 auto ReaderOrErr =
1445 IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001446 if (Error E = ReaderOrErr.takeError()) {
1447 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1448 Ctx.diagnose(
1449 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1450 });
Rong Xuf430ae42015-12-09 18:08:16 +00001451 return false;
1452 }
1453
Xinliang David Lida195582016-05-10 21:59:52 +00001454 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1455 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001456 if (!PGOReader) {
1457 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001458 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001459 return false;
1460 }
Rong Xu33c76c02016-02-10 17:18:30 +00001461 // TODO: might need to change the warning once the clang option is finalized.
1462 if (!PGOReader->isIRLevelProfile()) {
1463 Ctx.diagnose(DiagnosticInfoPGOProfile(
1464 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1465 return false;
1466 }
1467
Rong Xu705f7772016-07-25 18:45:37 +00001468 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1469 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001470 std::vector<Function *> HotFunctions;
1471 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001472 for (auto &F : M) {
1473 if (F.isDeclaration())
1474 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001475 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001476 auto *BFI = LookupBFI(F);
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +00001477 // Split indirectbr critical edges here before computing the MST rather than
1478 // later in getInstrBB() to avoid invalidating it.
1479 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Xinliang David Lid91057b2017-12-08 19:38:07 +00001480 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Rong Xufb4bcc42018-11-07 23:51:20 +00001481 bool AllZeros = false;
1482 if (!Func.readCounters(PGOReader.get(), AllZeros))
Sean Silva2e8f0952016-05-28 04:19:40 +00001483 continue;
Rong Xufb4bcc42018-11-07 23:51:20 +00001484 if (AllZeros) {
1485 F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1486 if (Func.getProgramMaxCount() != 0)
1487 ColdFunctions.push_back(&F);
1488 continue;
1489 }
Sean Silva2e8f0952016-05-28 04:19:40 +00001490 Func.populateCounters();
1491 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001492 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001493 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001494 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1495 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001496 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001497 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1498 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001499 if (PGOViewCounts != PGOVCT_None &&
1500 (ViewBlockFreqFuncName.empty() ||
1501 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001502 LoopInfo LI{DominatorTree(F)};
1503 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1504 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1505 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1506 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001507 if (PGOViewCounts == PGOVCT_Graph)
1508 NewBFI->view();
1509 else if (PGOViewCounts == PGOVCT_Text) {
1510 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1511 NewBFI->print(dbgs());
1512 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001513 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001514 if (PGOViewRawCounts != PGOVCT_None &&
1515 (ViewBlockFreqFuncName.empty() ||
1516 F.getName().equals(ViewBlockFreqFuncName))) {
1517 if (PGOViewRawCounts == PGOVCT_Graph)
1518 if (ViewBlockFreqFuncName.empty())
1519 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1520 else
1521 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1522 else if (PGOViewRawCounts == PGOVCT_Text) {
1523 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1524 Func.dumpInfo();
1525 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001526 }
Rong Xuf430ae42015-12-09 18:08:16 +00001527 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001528 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001529 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001530 // We have to apply these attributes at the end because their presence
1531 // can affect the BranchProbabilityInfo of any callers, resulting in an
1532 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001533 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001534 F->addFnAttr(Attribute::InlineHint);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001535 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1536 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001537 }
1538 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001539 F->addFnAttr(Attribute::Cold);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001540 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1541 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001542 }
Rong Xuf430ae42015-12-09 18:08:16 +00001543 return true;
1544}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001545
Richard Smith6c676622018-10-10 23:13:47 +00001546PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
1547 std::string RemappingFilename)
1548 : ProfileFileName(std::move(Filename)),
1549 ProfileRemappingFileName(std::move(RemappingFilename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001550 if (!PGOTestProfileFile.empty())
1551 ProfileFileName = PGOTestProfileFile;
Richard Smith6c676622018-10-10 23:13:47 +00001552 if (!PGOTestProfileRemappingFile.empty())
1553 ProfileRemappingFileName = PGOTestProfileRemappingFile;
Xinliang David Lida195582016-05-10 21:59:52 +00001554}
1555
1556PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001557 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001558
1559 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001560 auto LookupBPI = [&FAM](Function &F) {
1561 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1562 };
Xinliang David Lida195582016-05-10 21:59:52 +00001563
1564 auto LookupBFI = [&FAM](Function &F) {
1565 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1566 };
1567
Richard Smith6c676622018-10-10 23:13:47 +00001568 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1569 LookupBPI, LookupBFI))
Xinliang David Lida195582016-05-10 21:59:52 +00001570 return PreservedAnalyses::all();
1571
1572 return PreservedAnalyses::none();
1573}
1574
Xinliang David Lid55827f2016-05-07 05:39:12 +00001575bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1576 if (skipModule(M))
1577 return false;
1578
Xinliang David Lid91057b2017-12-08 19:38:07 +00001579 auto LookupBPI = [this](Function &F) {
1580 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1581 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001582 auto LookupBFI = [this](Function &F) {
1583 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001584 };
1585
Richard Smith6c676622018-10-10 23:13:47 +00001586 return annotateAllFunctions(M, ProfileFileName, "", LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001587}
Xinliang David Lid289e452017-01-27 19:06:25 +00001588
Eugene Zelenkofce43572017-10-21 00:57:46 +00001589static std::string getSimpleNodeName(const BasicBlock *Node) {
1590 if (!Node->getName().empty())
1591 return Node->getName();
1592
1593 std::string SimpleNodeName;
1594 raw_string_ostream OS(SimpleNodeName);
1595 Node->printAsOperand(OS, false);
1596 return OS.str();
1597}
1598
1599void llvm::setProfMetadata(Module *M, Instruction *TI,
1600 ArrayRef<uint64_t> EdgeCounts,
1601 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001602 MDBuilder MDB(M->getContext());
1603 assert(MaxCount > 0 && "Bad max count");
1604 uint64_t Scale = calculateCountScale(MaxCount);
1605 SmallVector<unsigned, 4> Weights;
1606 for (const auto &ECI : EdgeCounts)
1607 Weights.push_back(scaleBranchCount(ECI, Scale));
1608
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001609 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1610 : Weights) {
1611 dbgs() << W << " ";
1612 } dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001613 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001614 if (EmitBranchProbability) {
1615 std::string BrCondStr = getBranchCondString(TI);
1616 if (BrCondStr.empty())
1617 return;
1618
Rong Xu662f38b2018-03-27 18:55:56 +00001619 uint64_t WSum =
1620 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1621 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001622 uint64_t TotalCount =
Rong Xu662f38b2018-03-27 18:55:56 +00001623 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001624 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
Rong Xu662f38b2018-03-27 18:55:56 +00001625 Scale = calculateCountScale(WSum);
1626 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1627 scaleBranchCount(WSum, Scale));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001628 std::string BranchProbStr;
1629 raw_string_ostream OS(BranchProbStr);
1630 OS << BP;
1631 OS << " (total count : " << TotalCount << ")";
1632 OS.flush();
1633 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001634 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001635 ORE.emit([&]() {
1636 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1637 << BrCondStr << " is true with probability : " << BranchProbStr;
1638 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001639 }
Rong Xu48596b62017-04-04 16:42:20 +00001640}
1641
Eugene Zelenkofce43572017-10-21 00:57:46 +00001642namespace llvm {
1643
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001644void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1645 MDBuilder MDB(M->getContext());
1646 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1647 MDB.createIrrLoopHeaderWeight(Count));
1648}
1649
Xinliang David Lid289e452017-01-27 19:06:25 +00001650template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001651 using NodeRef = const BasicBlock *;
1652 using ChildIteratorType = succ_const_iterator;
1653 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001654
1655 static NodeRef getEntryNode(const PGOUseFunc *G) {
1656 return &G->getFunc().front();
1657 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001658
Xinliang David Lid289e452017-01-27 19:06:25 +00001659 static ChildIteratorType child_begin(const NodeRef N) {
1660 return succ_begin(N);
1661 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001662
Xinliang David Lid289e452017-01-27 19:06:25 +00001663 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001664
Xinliang David Lid289e452017-01-27 19:06:25 +00001665 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1666 return nodes_iterator(G->getFunc().begin());
1667 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001668
Xinliang David Lid289e452017-01-27 19:06:25 +00001669 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1670 return nodes_iterator(G->getFunc().end());
1671 }
1672};
1673
1674template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1675 explicit DOTGraphTraits(bool isSimple = false)
1676 : DefaultDOTGraphTraits(isSimple) {}
1677
1678 static std::string getGraphName(const PGOUseFunc *G) {
1679 return G->getFunc().getName();
1680 }
1681
1682 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1683 std::string Result;
1684 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001685
1686 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001687 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001688 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001689 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001690 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001691 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001692 OS << "Unknown\\l";
1693
1694 if (!PGOInstrSelect)
1695 return Result;
1696
1697 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1698 auto *I = &*BI;
1699 if (!isa<SelectInst>(I))
1700 continue;
1701 // Display scaled counts for SELECT instruction:
1702 OS << "SELECT : { T = ";
1703 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001704 bool HasProf = I->extractProfMetadata(TC, FC);
1705 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001706 OS << "Unknown, F = Unknown }\\l";
1707 else
1708 OS << TC << ", F = " << FC << " }\\l";
1709 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001710 return Result;
1711 }
1712};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001713
1714} // end namespace llvm