blob: c19321b51290f2297a281d2cf55594b0be413dee [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based profile-guided optimization
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenPGO.h"
15#include "CodeGenFunction.h"
Alex Lorenzee024992014-08-04 18:41:51 +000016#include "CoverageMappingGen.h"
Justin Bogneref512b92014-01-06 22:27:43 +000017#include "clang/AST/RecursiveASTVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Justin Bogner970ac602014-12-08 19:04:51 +000019#include "llvm/IR/Intrinsics.h"
Justin Bogneref512b92014-01-06 22:27:43 +000020#include "llvm/IR/MDBuilder.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000021#include "llvm/Support/Endian.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "llvm/Support/FileSystem.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000023#include "llvm/Support/MD5.h"
Justin Bogneref512b92014-01-06 22:27:43 +000024
Betul Buyukkurt518276a2016-01-23 22:50:44 +000025static llvm::cl::opt<bool> EnableValueProfiling(
26 "enable-value-profiling", llvm::cl::ZeroOrMore,
27 llvm::cl::desc("Enable value profiling"), llvm::cl::init(false));
28
Justin Bogneref512b92014-01-06 22:27:43 +000029using namespace clang;
30using namespace CodeGen;
31
Alex Lorenzee024992014-08-04 18:41:51 +000032void CodeGenPGO::setFuncName(StringRef Name,
33 llvm::GlobalValue::LinkageTypes Linkage) {
Xinliang David Lia569e242015-12-05 05:37:15 +000034 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
35 FuncName = llvm::getPGOFuncName(
36 Name, Linkage, CGM.getCodeGenOpts().MainFileName,
37 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
Justin Bogner970ac602014-12-08 19:04:51 +000038
39 // If we're generating a profile, create a variable for the name.
Rong Xu9837ef52016-02-04 18:39:09 +000040 if (CGM.getCodeGenOpts().hasProfileClangInstr())
Xinliang David Li2d7ec5a2015-11-09 00:04:16 +000041 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +000042}
43
Alex Lorenzee024992014-08-04 18:41:51 +000044void CodeGenPGO::setFuncName(llvm::Function *Fn) {
45 setFuncName(Fn->getName(), Fn->getLinkage());
Rong Xuf932f542016-04-22 21:19:05 +000046 // Create PGOFuncName meta data.
47 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
Alex Lorenzee024992014-08-04 18:41:51 +000048}
49
Justin Bogneref512b92014-01-06 22:27:43 +000050namespace {
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000051/// \brief Stable hasher for PGO region counters.
52///
53/// PGOHash produces a stable hash of a given function's control flow.
54///
55/// Changing the output of this hash will invalidate all previously generated
56/// profiles -- i.e., don't do it.
57///
58/// \note When this hash does eventually change (years?), we still need to
59/// support old hashes. We'll need to pull in the version number from the
60/// profile data format and use the matching hash function.
61class PGOHash {
62 uint64_t Working;
63 unsigned Count;
64 llvm::MD5 MD5;
65
66 static const int NumBitsPerType = 6;
67 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
68 static const unsigned TooBig = 1u << NumBitsPerType;
69
70public:
71 /// \brief Hash values for AST nodes.
72 ///
73 /// Distinct values for AST nodes that have region counters attached.
74 ///
75 /// These values must be stable. All new members must be added at the end,
76 /// and no members should be removed. Changing the enumeration value for an
77 /// AST node will affect the hash of every function that contains that node.
78 enum HashType : unsigned char {
79 None = 0,
80 LabelStmt = 1,
81 WhileStmt,
82 DoStmt,
83 ForStmt,
84 CXXForRangeStmt,
85 ObjCForCollectionStmt,
86 SwitchStmt,
87 CaseStmt,
88 DefaultStmt,
89 IfStmt,
90 CXXTryStmt,
91 CXXCatchStmt,
92 ConditionalOperator,
93 BinaryOperatorLAnd,
94 BinaryOperatorLOr,
95 BinaryConditionalOperator,
96
97 // Keep this last. It's for the static assert that follows.
98 LastHashType
99 };
100 static_assert(LastHashType <= TooBig, "Too many types in HashType");
101
102 // TODO: When this format changes, take in a version number here, and use the
103 // old hash calculation for file formats that used the old hash.
104 PGOHash() : Working(0), Count(0) {}
105 void combine(HashType Type);
106 uint64_t finalize();
107};
108const int PGOHash::NumBitsPerType;
109const unsigned PGOHash::NumTypesPerWord;
110const unsigned PGOHash::TooBig;
111
Justin Bognere4ca4412015-02-23 19:27:00 +0000112/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
113struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
114 /// The next counter value to assign.
115 unsigned NextCounter;
116 /// The function hash.
117 PGOHash Hash;
118 /// The map of statements to counters.
119 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000120
Justin Bognere4ca4412015-02-23 19:27:00 +0000121 MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
122 : NextCounter(0), CounterMap(CounterMap) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000123
Justin Bognere4ca4412015-02-23 19:27:00 +0000124 // Blocks and lambdas are handled as separate functions, so we need not
125 // traverse them in the parent context.
126 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
127 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
128 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000129
Justin Bognere4ca4412015-02-23 19:27:00 +0000130 bool VisitDecl(const Decl *D) {
131 switch (D->getKind()) {
132 default:
133 break;
134 case Decl::Function:
135 case Decl::CXXMethod:
136 case Decl::CXXConstructor:
137 case Decl::CXXDestructor:
138 case Decl::CXXConversion:
139 case Decl::ObjCMethod:
140 case Decl::Block:
141 case Decl::Captured:
142 CounterMap[D->getBody()] = NextCounter++;
143 break;
144 }
145 return true;
146 }
147
148 bool VisitStmt(const Stmt *S) {
149 auto Type = getHashType(S);
150 if (Type == PGOHash::None)
Bob Wilsond8931422014-04-11 17:16:13 +0000151 return true;
Bob Wilsond8931422014-04-11 17:16:13 +0000152
Justin Bognere4ca4412015-02-23 19:27:00 +0000153 CounterMap[S] = NextCounter++;
154 Hash.combine(Type);
155 return true;
156 }
157 PGOHash::HashType getHashType(const Stmt *S) {
158 switch (S->getStmtClass()) {
159 default:
160 break;
161 case Stmt::LabelStmtClass:
162 return PGOHash::LabelStmt;
163 case Stmt::WhileStmtClass:
164 return PGOHash::WhileStmt;
165 case Stmt::DoStmtClass:
166 return PGOHash::DoStmt;
167 case Stmt::ForStmtClass:
168 return PGOHash::ForStmt;
169 case Stmt::CXXForRangeStmtClass:
170 return PGOHash::CXXForRangeStmt;
171 case Stmt::ObjCForCollectionStmtClass:
172 return PGOHash::ObjCForCollectionStmt;
173 case Stmt::SwitchStmtClass:
174 return PGOHash::SwitchStmt;
175 case Stmt::CaseStmtClass:
176 return PGOHash::CaseStmt;
177 case Stmt::DefaultStmtClass:
178 return PGOHash::DefaultStmt;
179 case Stmt::IfStmtClass:
180 return PGOHash::IfStmt;
181 case Stmt::CXXTryStmtClass:
182 return PGOHash::CXXTryStmt;
183 case Stmt::CXXCatchStmtClass:
184 return PGOHash::CXXCatchStmt;
185 case Stmt::ConditionalOperatorClass:
186 return PGOHash::ConditionalOperator;
187 case Stmt::BinaryConditionalOperatorClass:
188 return PGOHash::BinaryConditionalOperator;
189 case Stmt::BinaryOperatorClass: {
190 const BinaryOperator *BO = cast<BinaryOperator>(S);
191 if (BO->getOpcode() == BO_LAnd)
192 return PGOHash::BinaryOperatorLAnd;
193 if (BO->getOpcode() == BO_LOr)
194 return PGOHash::BinaryOperatorLOr;
195 break;
196 }
197 }
198 return PGOHash::None;
199 }
200};
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000201
Justin Bognere4ca4412015-02-23 19:27:00 +0000202/// A StmtVisitor that propagates the raw counts through the AST and
203/// records the count at statements where the value may change.
204struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
205 /// PGO state.
206 CodeGenPGO &PGO;
207
208 /// A flag that is set when the current count should be recorded on the
209 /// next statement, such as at the exit of a loop.
210 bool RecordNextStmtCount;
211
Justin Bognera909abf2015-05-02 00:48:27 +0000212 /// The count at the current location in the traversal.
213 uint64_t CurrentCount;
214
Justin Bognere4ca4412015-02-23 19:27:00 +0000215 /// The map of statements to count values.
216 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
217
218 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
219 struct BreakContinue {
220 uint64_t BreakCount;
221 uint64_t ContinueCount;
222 BreakContinue() : BreakCount(0), ContinueCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000223 };
Justin Bognere4ca4412015-02-23 19:27:00 +0000224 SmallVector<BreakContinue, 8> BreakContinueStack;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000225
Justin Bognere4ca4412015-02-23 19:27:00 +0000226 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
227 CodeGenPGO &PGO)
228 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000229
Justin Bognere4ca4412015-02-23 19:27:00 +0000230 void RecordStmtCount(const Stmt *S) {
231 if (RecordNextStmtCount) {
Justin Bognera909abf2015-05-02 00:48:27 +0000232 CountMap[S] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000233 RecordNextStmtCount = false;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000234 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000235 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000236
Justin Bogner07193cc2015-05-01 23:41:09 +0000237 /// Set and return the current count.
238 uint64_t setCount(uint64_t Count) {
Justin Bognera909abf2015-05-02 00:48:27 +0000239 CurrentCount = Count;
Justin Bogner07193cc2015-05-01 23:41:09 +0000240 return Count;
241 }
242
Justin Bognere4ca4412015-02-23 19:27:00 +0000243 void VisitStmt(const Stmt *S) {
244 RecordStmtCount(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000245 for (const Stmt *Child : S->children())
246 if (Child)
247 this->Visit(Child);
Justin Bognere4ca4412015-02-23 19:27:00 +0000248 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000249
Justin Bognere4ca4412015-02-23 19:27:00 +0000250 void VisitFunctionDecl(const FunctionDecl *D) {
251 // Counter tracks entry to the function body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000252 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
253 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000254 Visit(D->getBody());
255 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000256
Justin Bognere4ca4412015-02-23 19:27:00 +0000257 // Skip lambda expressions. We visit these as FunctionDecls when we're
258 // generating them and aren't interested in the body when generating a
259 // parent context.
260 void VisitLambdaExpr(const LambdaExpr *LE) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000261
Justin Bognere4ca4412015-02-23 19:27:00 +0000262 void VisitCapturedDecl(const CapturedDecl *D) {
263 // Counter tracks entry to the capture body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000264 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
265 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000266 Visit(D->getBody());
267 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000268
Justin Bognere4ca4412015-02-23 19:27:00 +0000269 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
270 // Counter tracks entry to the method body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000271 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
272 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000273 Visit(D->getBody());
274 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000275
Justin Bognere4ca4412015-02-23 19:27:00 +0000276 void VisitBlockDecl(const BlockDecl *D) {
277 // Counter tracks entry to the block body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000278 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
279 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000280 Visit(D->getBody());
281 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000282
Justin Bognere4ca4412015-02-23 19:27:00 +0000283 void VisitReturnStmt(const ReturnStmt *S) {
284 RecordStmtCount(S);
285 if (S->getRetValue())
286 Visit(S->getRetValue());
Justin Bognera909abf2015-05-02 00:48:27 +0000287 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000288 RecordNextStmtCount = true;
289 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000290
Justin Bognerf959feb2015-04-28 06:31:55 +0000291 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
292 RecordStmtCount(E);
293 if (E->getSubExpr())
294 Visit(E->getSubExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000295 CurrentCount = 0;
Justin Bognerf959feb2015-04-28 06:31:55 +0000296 RecordNextStmtCount = true;
297 }
298
Justin Bognere4ca4412015-02-23 19:27:00 +0000299 void VisitGotoStmt(const GotoStmt *S) {
300 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000301 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000302 RecordNextStmtCount = true;
303 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000304
Justin Bognere4ca4412015-02-23 19:27:00 +0000305 void VisitLabelStmt(const LabelStmt *S) {
306 RecordNextStmtCount = false;
307 // Counter tracks the block following the label.
Justin Bogner07193cc2015-05-01 23:41:09 +0000308 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
309 CountMap[S] = BlockCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000310 Visit(S->getSubStmt());
311 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000312
Justin Bognere4ca4412015-02-23 19:27:00 +0000313 void VisitBreakStmt(const BreakStmt *S) {
314 RecordStmtCount(S);
315 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
Justin Bognera909abf2015-05-02 00:48:27 +0000316 BreakContinueStack.back().BreakCount += CurrentCount;
317 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000318 RecordNextStmtCount = true;
319 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000320
Justin Bognere4ca4412015-02-23 19:27:00 +0000321 void VisitContinueStmt(const ContinueStmt *S) {
322 RecordStmtCount(S);
323 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
Justin Bognera909abf2015-05-02 00:48:27 +0000324 BreakContinueStack.back().ContinueCount += CurrentCount;
325 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000326 RecordNextStmtCount = true;
327 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000328
Justin Bognere4ca4412015-02-23 19:27:00 +0000329 void VisitWhileStmt(const WhileStmt *S) {
330 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000331 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000332
Justin Bognere4ca4412015-02-23 19:27:00 +0000333 BreakContinueStack.push_back(BreakContinue());
334 // Visit the body region first so the break/continue adjustments can be
335 // included when visiting the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000336 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
Justin Bognera909abf2015-05-02 00:48:27 +0000337 CountMap[S->getBody()] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000338 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000339 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000340
341 // ...then go back and propagate counts through the condition. The count
342 // at the start of the condition is the sum of the incoming edges,
343 // the backedge from the end of the loop body, and the edges from
344 // continue statements.
345 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000346 uint64_t CondCount =
347 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
348 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000349 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000350 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000351 RecordNextStmtCount = true;
352 }
353
354 void VisitDoStmt(const DoStmt *S) {
355 RecordStmtCount(S);
Justin Bogner07193cc2015-05-01 23:41:09 +0000356 uint64_t LoopCount = PGO.getRegionCount(S);
357
Justin Bognere4ca4412015-02-23 19:27:00 +0000358 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000359 // The count doesn't include the fallthrough from the parent scope. Add it.
Justin Bognera909abf2015-05-02 00:48:27 +0000360 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000361 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000362 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000363 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000364
365 BreakContinue BC = BreakContinueStack.pop_back_val();
366 // The count at the start of the condition is equal to the count at the
Justin Bogner07193cc2015-05-01 23:41:09 +0000367 // end of the body, plus any continues.
368 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
369 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000370 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000371 setCount(BC.BreakCount + CondCount - LoopCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000372 RecordNextStmtCount = true;
373 }
374
375 void VisitForStmt(const ForStmt *S) {
376 RecordStmtCount(S);
377 if (S->getInit())
378 Visit(S->getInit());
Justin Bogner07193cc2015-05-01 23:41:09 +0000379
Justin Bognera909abf2015-05-02 00:48:27 +0000380 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000381
Justin Bognere4ca4412015-02-23 19:27:00 +0000382 BreakContinueStack.push_back(BreakContinue());
383 // Visit the body region first. (This is basically the same as a while
384 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000385 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
386 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000387 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000388 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000389 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognere4ca4412015-02-23 19:27:00 +0000390
391 // The increment is essentially part of the body but it needs to include
392 // the count for all the continue statements.
393 if (S->getInc()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000394 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
395 CountMap[S->getInc()] = IncCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000396 Visit(S->getInc());
Justin Bognere4ca4412015-02-23 19:27:00 +0000397 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000398
Justin Bognere4ca4412015-02-23 19:27:00 +0000399 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000400 uint64_t CondCount =
401 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000402 if (S->getCond()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000403 CountMap[S->getCond()] = CondCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000404 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000405 }
Justin Bogner07193cc2015-05-01 23:41:09 +0000406 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000407 RecordNextStmtCount = true;
408 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000409
Justin Bognere4ca4412015-02-23 19:27:00 +0000410 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
411 RecordStmtCount(S);
Justin Bogner2e5d4842015-04-30 22:58:28 +0000412 Visit(S->getLoopVarStmt());
Justin Bognere4ca4412015-02-23 19:27:00 +0000413 Visit(S->getRangeStmt());
Richard Smith01694c32016-03-20 10:33:40 +0000414 Visit(S->getBeginStmt());
415 Visit(S->getEndStmt());
Justin Bogner07193cc2015-05-01 23:41:09 +0000416
Justin Bognera909abf2015-05-02 00:48:27 +0000417 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000418 BreakContinueStack.push_back(BreakContinue());
419 // Visit the body region first. (This is basically the same as a while
420 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000421 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
422 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000423 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000424 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000425 BreakContinue BC = BreakContinueStack.pop_back_val();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000426
Justin Bognere4ca4412015-02-23 19:27:00 +0000427 // The increment is essentially part of the body but it needs to include
428 // the count for all the continue statements.
Justin Bogner07193cc2015-05-01 23:41:09 +0000429 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
430 CountMap[S->getInc()] = IncCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000431 Visit(S->getInc());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000432
Justin Bognere4ca4412015-02-23 19:27:00 +0000433 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000434 uint64_t CondCount =
435 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
436 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000437 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000438 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000439 RecordNextStmtCount = true;
440 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000441
Justin Bognere4ca4412015-02-23 19:27:00 +0000442 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
443 RecordStmtCount(S);
444 Visit(S->getElement());
Justin Bognera909abf2015-05-02 00:48:27 +0000445 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000446 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000447 // Counter tracks the body of the loop.
448 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
449 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000450 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000451 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000452 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000453
454 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
455 BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000456 RecordNextStmtCount = true;
457 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000458
Justin Bognere4ca4412015-02-23 19:27:00 +0000459 void VisitSwitchStmt(const SwitchStmt *S) {
460 RecordStmtCount(S);
461 Visit(S->getCond());
Justin Bognera909abf2015-05-02 00:48:27 +0000462 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000463 BreakContinueStack.push_back(BreakContinue());
464 Visit(S->getBody());
465 // If the switch is inside a loop, add the continue counts.
466 BreakContinue BC = BreakContinueStack.pop_back_val();
467 if (!BreakContinueStack.empty())
468 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
469 // Counter tracks the exit block of the switch.
Justin Bogner07193cc2015-05-01 23:41:09 +0000470 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000471 RecordNextStmtCount = true;
472 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000473
Justin Bogner07193cc2015-05-01 23:41:09 +0000474 void VisitSwitchCase(const SwitchCase *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000475 RecordNextStmtCount = false;
476 // Counter for this particular case. This counts only jumps from the
477 // switch header and does not include fallthrough from the case before
478 // this one.
Justin Bogner07193cc2015-05-01 23:41:09 +0000479 uint64_t CaseCount = PGO.getRegionCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000480 setCount(CurrentCount + CaseCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000481 // We need the count without fallthrough in the mapping, so it's more useful
482 // for branch probabilities.
483 CountMap[S] = CaseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000484 RecordNextStmtCount = true;
485 Visit(S->getSubStmt());
486 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000487
Justin Bognere4ca4412015-02-23 19:27:00 +0000488 void VisitIfStmt(const IfStmt *S) {
489 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000490 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000491 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000492
Justin Bogner07193cc2015-05-01 23:41:09 +0000493 // Counter tracks the "then" part of an if statement. The count for
494 // the "else" part, if it exists, will be calculated from this counter.
495 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
496 CountMap[S->getThen()] = ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000497 Visit(S->getThen());
Justin Bognera909abf2015-05-02 00:48:27 +0000498 uint64_t OutCount = CurrentCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000499
Justin Bogner07193cc2015-05-01 23:41:09 +0000500 uint64_t ElseCount = ParentCount - ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000501 if (S->getElse()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000502 setCount(ElseCount);
503 CountMap[S->getElse()] = ElseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000504 Visit(S->getElse());
Justin Bognera909abf2015-05-02 00:48:27 +0000505 OutCount += CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000506 } else
507 OutCount += ElseCount;
508 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000509 RecordNextStmtCount = true;
510 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000511
Justin Bognere4ca4412015-02-23 19:27:00 +0000512 void VisitCXXTryStmt(const CXXTryStmt *S) {
513 RecordStmtCount(S);
514 Visit(S->getTryBlock());
515 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
516 Visit(S->getHandler(I));
517 // Counter tracks the continuation block of the try statement.
Justin Bogner07193cc2015-05-01 23:41:09 +0000518 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000519 RecordNextStmtCount = true;
520 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000521
Justin Bognere4ca4412015-02-23 19:27:00 +0000522 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
523 RecordNextStmtCount = false;
524 // Counter tracks the catch statement's handler block.
Justin Bogner07193cc2015-05-01 23:41:09 +0000525 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
526 CountMap[S] = CatchCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000527 Visit(S->getHandlerBlock());
528 }
529
530 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
531 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000532 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000533 Visit(E->getCond());
534
Justin Bogner07193cc2015-05-01 23:41:09 +0000535 // Counter tracks the "true" part of a conditional operator. The
536 // count in the "false" part will be calculated from this counter.
537 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
538 CountMap[E->getTrueExpr()] = TrueCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000539 Visit(E->getTrueExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000540 uint64_t OutCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000541
Justin Bogner07193cc2015-05-01 23:41:09 +0000542 uint64_t FalseCount = setCount(ParentCount - TrueCount);
543 CountMap[E->getFalseExpr()] = FalseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000544 Visit(E->getFalseExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000545 OutCount += CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000546
Justin Bogner07193cc2015-05-01 23:41:09 +0000547 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000548 RecordNextStmtCount = true;
549 }
550
551 void VisitBinLAnd(const BinaryOperator *E) {
552 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000553 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000554 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000555 // Counter tracks the right hand side of a logical and operator.
556 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
557 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000558 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000559 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000560 RecordNextStmtCount = true;
561 }
562
563 void VisitBinLOr(const BinaryOperator *E) {
564 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000565 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000566 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000567 // Counter tracks the right hand side of a logical or operator.
568 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
569 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000570 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000571 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000572 RecordNextStmtCount = true;
573 }
574};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000575} // end anonymous namespace
Justin Bogneref512b92014-01-06 22:27:43 +0000576
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000577void PGOHash::combine(HashType Type) {
578 // Check that we never combine 0 and only have six bits.
579 assert(Type && "Hash is invalid: unexpected type 0");
580 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
581
582 // Pass through MD5 if enough work has built up.
583 if (Count && Count % NumTypesPerWord == 0) {
584 using namespace llvm::support;
585 uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
586 MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
587 Working = 0;
588 }
589
590 // Accumulate the current type.
591 ++Count;
592 Working = Working << NumBitsPerType | Type;
593}
594
595uint64_t PGOHash::finalize() {
596 // Use Working as the hash directly if we never used MD5.
597 if (Count <= NumTypesPerWord)
598 // No need to byte swap here, since none of the math was endian-dependent.
599 // This number will be byte-swapped as required on endianness transitions,
600 // so we will see the same value on the other side.
601 return Working;
602
603 // Check for remaining work in Working.
604 if (Working)
605 MD5.update(Working);
606
607 // Finalize the MD5 and return the hash.
608 llvm::MD5::MD5Result Result;
609 MD5.final(Result);
610 using namespace llvm::support;
611 return endian::read<uint64_t, little, unaligned>(Result);
612}
613
Serge Pavlov3a561452015-12-06 14:32:39 +0000614void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
615 const Decl *D = GD.getDecl();
Rong Xu9837ef52016-02-04 18:39:09 +0000616 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
Justin Bogner837a6f62014-04-18 21:52:00 +0000617 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
618 if (!InstrumentRegions && !PGOReader)
Justin Bogneref512b92014-01-06 22:27:43 +0000619 return;
Justin Bogner3212b182014-04-25 07:20:05 +0000620 if (D->isImplicit())
Justin Bogneref512b92014-01-06 22:27:43 +0000621 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000622 // Constructors and destructors may be represented by several functions in IR.
623 // If so, instrument only base variant, others are implemented by delegation
624 // to the base one, it would be counted twice otherwise.
625 if (CGM.getTarget().getCXXABI().hasConstructorVariants() &&
626 ((isa<CXXConstructorDecl>(GD.getDecl()) &&
627 GD.getCtorType() != Ctor_Base) ||
628 (isa<CXXDestructorDecl>(GD.getDecl()) &&
629 GD.getDtorType() != Dtor_Base))) {
630 return;
631 }
Alex Lorenzee024992014-08-04 18:41:51 +0000632 CGM.ClearUnusedCoverageMapping(D);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000633 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000634
Justin Bogneref512b92014-01-06 22:27:43 +0000635 mapRegionCounters(D);
Justin Bogner970ac602014-12-08 19:04:51 +0000636 if (CGM.getCodeGenOpts().CoverageMapping)
637 emitCounterRegionMapping(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000638 if (PGOReader) {
Justin Bogner40b8ba12014-06-26 01:45:07 +0000639 SourceManager &SM = CGM.getContext().getSourceManager();
640 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000641 computeRegionCounts(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000642 applyFunctionAttributes(PGOReader, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000643 }
Justin Bogneref512b92014-01-06 22:27:43 +0000644}
645
646void CodeGenPGO::mapRegionCounters(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000647 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000648 MapRegionCounters Walker(*RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000649 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000650 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000651 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000652 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000653 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000654 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000655 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
656 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogner3212b182014-04-25 07:20:05 +0000657 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
Justin Bogneref512b92014-01-06 22:27:43 +0000658 NumRegionCounters = Walker.NextCounter;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000659 FunctionHash = Walker.Hash.finalize();
Justin Bogneref512b92014-01-06 22:27:43 +0000660}
661
Alex Lorenzee024992014-08-04 18:41:51 +0000662void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
663 if (SkipCoverageMapping)
664 return;
665 // Don't map the functions inside the system headers
666 auto Loc = D->getBody()->getLocStart();
667 if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
668 return;
669
Justin Bogner970ac602014-12-08 19:04:51 +0000670 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000671 llvm::raw_string_ostream OS(CoverageMapping);
672 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
673 CGM.getContext().getSourceManager(),
Justin Bognere5ee6c52014-10-02 16:44:01 +0000674 CGM.getLangOpts(), RegionCounterMap.get());
Alex Lorenzee024992014-08-04 18:41:51 +0000675 MappingGen.emitCounterMapping(D, OS);
676 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000677
678 if (CoverageMapping.empty())
679 return;
680
681 CGM.getCoverageMapping()->addFunctionMappingRecord(
682 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
Alex Lorenzee024992014-08-04 18:41:51 +0000683}
684
685void
Justin Bogner60d852b2015-04-23 00:31:16 +0000686CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
Alex Lorenzee024992014-08-04 18:41:51 +0000687 llvm::GlobalValue::LinkageTypes Linkage) {
688 if (SkipCoverageMapping)
689 return;
Alex Lorenzee024992014-08-04 18:41:51 +0000690 // Don't map the functions inside the system headers
691 auto Loc = D->getBody()->getLocStart();
692 if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
693 return;
694
Justin Bogner970ac602014-12-08 19:04:51 +0000695 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000696 llvm::raw_string_ostream OS(CoverageMapping);
697 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
698 CGM.getContext().getSourceManager(),
699 CGM.getLangOpts());
700 MappingGen.emitEmptyMapping(D, OS);
701 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000702
703 if (CoverageMapping.empty())
704 return;
705
Justin Bogner60d852b2015-04-23 00:31:16 +0000706 setFuncName(Name, Linkage);
Justin Bogner970ac602014-12-08 19:04:51 +0000707 CGM.getCoverageMapping()->addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000708 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
Alex Lorenzee024992014-08-04 18:41:51 +0000709}
710
Bob Wilsonbf854f02014-02-17 19:21:09 +0000711void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000712 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000713 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000714 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
715 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000716 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
717 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000718 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
719 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000720 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
721 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000722}
723
Justin Bogner837a6f62014-04-18 21:52:00 +0000724void
725CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
726 llvm::Function *Fn) {
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000727 if (!haveRegionCounts())
728 return;
729
Hans Wennborgdcfba332015-10-06 23:40:43 +0000730 uint64_t FunctionCount = getRegionCount(nullptr);
Diego Novilloaa8b1cb2015-05-27 21:58:42 +0000731 Fn->setEntryCount(FunctionCount);
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000732}
733
Justin Bogner66242d62015-04-23 23:06:47 +0000734void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
Rong Xu9837ef52016-02-04 18:39:09 +0000735 if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000736 return;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000737 if (!Builder.GetInsertBlock())
Justin Bogner203f91e2015-01-09 01:46:40 +0000738 return;
Justin Bogner66242d62015-04-23 23:06:47 +0000739
740 unsigned Counter = (*RegionCounterMap)[S];
Justin Bogner970ac602014-12-08 19:04:51 +0000741 auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
David Blaikie43f9bb72015-05-18 22:14:03 +0000742 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
743 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Justin Bogner970ac602014-12-08 19:04:51 +0000744 Builder.getInt64(FunctionHash),
745 Builder.getInt32(NumRegionCounters),
David Blaikie43f9bb72015-05-18 22:14:03 +0000746 Builder.getInt32(Counter)});
Justin Bogneref512b92014-01-06 22:27:43 +0000747}
748
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000749// This method either inserts a call to the profile run-time during
750// instrumentation or puts profile data into metadata for PGO use.
751void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
752 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
753
754 if (!EnableValueProfiling)
755 return;
756
757 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
758 return;
759
Betul Buyukkurt3da993c2016-03-31 18:41:34 +0000760 if (isa<llvm::Constant>(ValuePtr))
761 return;
762
Rong Xu9837ef52016-02-04 18:39:09 +0000763 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000764 if (InstrumentValueSites && RegionCounterMap) {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000765 auto BuilderInsertPoint = Builder.saveIP();
766 Builder.SetInsertPoint(ValueSite);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000767 llvm::Value *Args[5] = {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000768 llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000769 Builder.getInt64(FunctionHash),
770 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
771 Builder.getInt32(ValueKind),
772 Builder.getInt32(NumValueSites[ValueKind]++)
773 };
774 Builder.CreateCall(
775 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000776 Builder.restoreIP(BuilderInsertPoint);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000777 return;
778 }
779
780 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
781 if (PGOReader && haveRegionCounts()) {
782 // We record the top most called three functions at each call site.
783 // Profile metadata contains "VP" string identifying this metadata
784 // as value profiling data, then a uint32_t value for the value profiling
785 // kind, a uint64_t value for the total number of times the call is
786 // executed, followed by the function hash and execution count (uint64_t)
787 // pairs for each function.
788 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
789 return;
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000790
Xinliang David Li5527a9d2016-02-04 19:54:17 +0000791 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
792 (llvm::InstrProfValueKind)ValueKind,
793 NumValueSites[ValueKind]);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000794
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000795 NumValueSites[ValueKind]++;
796 }
797}
798
Justin Bogner40b8ba12014-06-26 01:45:07 +0000799void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
800 bool IsInMainFile) {
801 CGM.getPGOStats().addVisited(IsInMainFile);
Justin Bogner7f8cf5b2014-12-02 22:38:52 +0000802 RegionCounts.clear();
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000803 llvm::Expected<llvm::InstrProfRecord> RecordExpected =
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000804 PGOReader->getInstrProfRecord(FuncName, FunctionHash);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000805 if (auto E = RecordExpected.takeError()) {
806 auto IPE = llvm::InstrProfError::take(std::move(E));
807 if (IPE == llvm::instrprof_error::unknown_function)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000808 CGM.getPGOStats().addMissing(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000809 else if (IPE == llvm::instrprof_error::hash_mismatch)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000810 CGM.getPGOStats().addMismatched(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000811 else if (IPE == llvm::instrprof_error::malformed)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000812 // TODO: Consider a more specific warning for this case.
813 CGM.getPGOStats().addMismatched(IsInMainFile);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000814 return;
Justin Bognere2ef2a02014-04-15 21:22:35 +0000815 }
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000816 ProfRecord =
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000817 llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000818 RegionCounts = ProfRecord->Counts;
Justin Bogneref512b92014-01-06 22:27:43 +0000819}
820
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000821/// \brief Calculate what to divide by to scale weights.
822///
823/// Given the maximum weight, calculate a divisor that will scale all the
824/// weights to strictly less than UINT32_MAX.
825static uint64_t calculateWeightScale(uint64_t MaxWeight) {
826 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
827}
828
829/// \brief Scale an individual branch weight (and add 1).
830///
831/// Scale a 64-bit weight down to 32-bits using \c Scale.
832///
833/// According to Laplace's Rule of Succession, it is better to compute the
834/// weight based on the count plus 1, so universally add 1 to the value.
835///
836/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
837/// greater than \c Weight.
838static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
839 assert(Scale && "scale by 0?");
840 uint64_t Scaled = Weight / Scale + 1;
841 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
842 return Scaled;
843}
844
Justin Bogner65512642015-05-02 05:00:55 +0000845llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
846 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000847 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +0000848 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000849 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +0000850
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000851 // Calculate how to scale down to 32-bits.
852 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
853
Justin Bogneref512b92014-01-06 22:27:43 +0000854 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000855 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
856 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +0000857}
858
Justin Bogner65512642015-05-02 05:00:55 +0000859llvm::MDNode *
860CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000861 // We need at least two elements to create meaningful weights.
862 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000863 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000864
Justin Bognerf3aefca2014-04-04 02:48:51 +0000865 // Check for empty weights.
866 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
867 if (MaxWeight == 0)
868 return nullptr;
869
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000870 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +0000871 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000872
Justin Bogneref512b92014-01-06 22:27:43 +0000873 SmallVector<uint32_t, 16> ScaledWeights;
874 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000875 for (uint64_t W : Weights)
876 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
877
878 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +0000879 return MDHelper.createBranchWeights(ScaledWeights);
880}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000881
Justin Bogner65512642015-05-02 05:00:55 +0000882llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
883 uint64_t LoopCount) {
884 if (!PGO.haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000885 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +0000886 Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
Justin Bogner1c21c282015-04-13 12:23:19 +0000887 assert(CondCount.hasValue() && "missing expected loop condition count");
888 if (*CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000889 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +0000890 return createProfileWeights(LoopCount,
891 std::max(*CondCount, LoopCount) - LoopCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000892}