blob: 776060743a63e0e67ae858111570b91d4693a322 [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
Zachary Turner8065f0b2017-12-01 00:53:10 +000025static llvm::cl::opt<bool>
26 EnableValueProfiling("enable-value-profiling", llvm::cl::ZeroOrMore,
27 llvm::cl::desc("Enable value profiling"),
28 llvm::cl::Hidden, llvm::cl::init(false));
Betul Buyukkurt518276a2016-01-23 22:50:44 +000029
Justin Bogneref512b92014-01-06 22:27:43 +000030using namespace clang;
31using namespace CodeGen;
32
Alex Lorenzee024992014-08-04 18:41:51 +000033void CodeGenPGO::setFuncName(StringRef Name,
34 llvm::GlobalValue::LinkageTypes Linkage) {
Xinliang David Lia569e242015-12-05 05:37:15 +000035 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
36 FuncName = llvm::getPGOFuncName(
37 Name, Linkage, CGM.getCodeGenOpts().MainFileName,
38 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
Justin Bogner970ac602014-12-08 19:04:51 +000039
40 // If we're generating a profile, create a variable for the name.
Rong Xu9837ef52016-02-04 18:39:09 +000041 if (CGM.getCodeGenOpts().hasProfileClangInstr())
Xinliang David Li2d7ec5a2015-11-09 00:04:16 +000042 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +000043}
44
Alex Lorenzee024992014-08-04 18:41:51 +000045void CodeGenPGO::setFuncName(llvm::Function *Fn) {
46 setFuncName(Fn->getName(), Fn->getLinkage());
Rong Xuf932f542016-04-22 21:19:05 +000047 // Create PGOFuncName meta data.
48 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
Alex Lorenzee024992014-08-04 18:41:51 +000049}
50
Vedant Kumar61869712017-11-14 23:56:53 +000051/// The version of the PGO hash algorithm.
52enum PGOHashVersion : unsigned {
53 PGO_HASH_V1,
54 PGO_HASH_V2,
55
56 // Keep this set to the latest hash version.
57 PGO_HASH_LATEST = PGO_HASH_V2
58};
59
Justin Bogneref512b92014-01-06 22:27:43 +000060namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000061/// Stable hasher for PGO region counters.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000062///
63/// PGOHash produces a stable hash of a given function's control flow.
64///
65/// Changing the output of this hash will invalidate all previously generated
66/// profiles -- i.e., don't do it.
67///
68/// \note When this hash does eventually change (years?), we still need to
69/// support old hashes. We'll need to pull in the version number from the
70/// profile data format and use the matching hash function.
71class PGOHash {
72 uint64_t Working;
73 unsigned Count;
Vedant Kumar61869712017-11-14 23:56:53 +000074 PGOHashVersion HashVersion;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000075 llvm::MD5 MD5;
76
77 static const int NumBitsPerType = 6;
78 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
79 static const unsigned TooBig = 1u << NumBitsPerType;
80
81public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Hash values for AST nodes.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000083 ///
84 /// Distinct values for AST nodes that have region counters attached.
85 ///
86 /// These values must be stable. All new members must be added at the end,
87 /// and no members should be removed. Changing the enumeration value for an
88 /// AST node will affect the hash of every function that contains that node.
89 enum HashType : unsigned char {
90 None = 0,
91 LabelStmt = 1,
92 WhileStmt,
93 DoStmt,
94 ForStmt,
95 CXXForRangeStmt,
96 ObjCForCollectionStmt,
97 SwitchStmt,
98 CaseStmt,
99 DefaultStmt,
100 IfStmt,
101 CXXTryStmt,
102 CXXCatchStmt,
103 ConditionalOperator,
104 BinaryOperatorLAnd,
105 BinaryOperatorLOr,
106 BinaryConditionalOperator,
Vedant Kumar61869712017-11-14 23:56:53 +0000107 // The preceding values are available with PGO_HASH_V1.
108
109 EndOfScope,
110 IfThenBranch,
111 IfElseBranch,
112 GotoStmt,
113 IndirectGotoStmt,
114 BreakStmt,
115 ContinueStmt,
116 ReturnStmt,
117 ThrowExpr,
118 UnaryOperatorLNot,
119 BinaryOperatorLT,
120 BinaryOperatorGT,
121 BinaryOperatorLE,
122 BinaryOperatorGE,
123 BinaryOperatorEQ,
124 BinaryOperatorNE,
125 // The preceding values are available with PGO_HASH_V2.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000126
127 // Keep this last. It's for the static assert that follows.
128 LastHashType
129 };
130 static_assert(LastHashType <= TooBig, "Too many types in HashType");
131
Vedant Kumar61869712017-11-14 23:56:53 +0000132 PGOHash(PGOHashVersion HashVersion)
133 : Working(0), Count(0), HashVersion(HashVersion), MD5() {}
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000134 void combine(HashType Type);
135 uint64_t finalize();
Vedant Kumar61869712017-11-14 23:56:53 +0000136 PGOHashVersion getHashVersion() const { return HashVersion; }
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000137};
138const int PGOHash::NumBitsPerType;
139const unsigned PGOHash::NumTypesPerWord;
140const unsigned PGOHash::TooBig;
141
Vedant Kumar61869712017-11-14 23:56:53 +0000142/// Get the PGO hash version used in the given indexed profile.
143static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
144 CodeGenModule &CGM) {
145 if (PGOReader->getVersion() <= 4)
146 return PGO_HASH_V1;
147 return PGO_HASH_V2;
148}
149
Justin Bognere4ca4412015-02-23 19:27:00 +0000150/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
151struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
Vedant Kumar61869712017-11-14 23:56:53 +0000152 using Base = RecursiveASTVisitor<MapRegionCounters>;
153
Justin Bognere4ca4412015-02-23 19:27:00 +0000154 /// The next counter value to assign.
155 unsigned NextCounter;
156 /// The function hash.
157 PGOHash Hash;
158 /// The map of statements to counters.
159 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000160
Vedant Kumar61869712017-11-14 23:56:53 +0000161 MapRegionCounters(PGOHashVersion HashVersion,
162 llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
163 : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000164
Justin Bognere4ca4412015-02-23 19:27:00 +0000165 // Blocks and lambdas are handled as separate functions, so we need not
166 // traverse them in the parent context.
167 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
Sam McCalle60151c2019-01-14 10:31:42 +0000168 bool TraverseLambdaExpr(LambdaExpr *LE) {
169 // Traverse the captures, but not the body.
170 for (const auto &C : zip(LE->captures(), LE->capture_inits()))
171 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
172 return true;
173 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000174 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000175
Justin Bognere4ca4412015-02-23 19:27:00 +0000176 bool VisitDecl(const Decl *D) {
177 switch (D->getKind()) {
178 default:
179 break;
180 case Decl::Function:
181 case Decl::CXXMethod:
182 case Decl::CXXConstructor:
183 case Decl::CXXDestructor:
184 case Decl::CXXConversion:
185 case Decl::ObjCMethod:
186 case Decl::Block:
187 case Decl::Captured:
188 CounterMap[D->getBody()] = NextCounter++;
189 break;
190 }
191 return true;
192 }
193
Vedant Kumar61869712017-11-14 23:56:53 +0000194 /// If \p S gets a fresh counter, update the counter mappings. Return the
195 /// V1 hash of \p S.
196 PGOHash::HashType updateCounterMappings(Stmt *S) {
197 auto Type = getHashType(PGO_HASH_V1, S);
198 if (Type != PGOHash::None)
199 CounterMap[S] = NextCounter++;
200 return Type;
201 }
Bob Wilsond8931422014-04-11 17:16:13 +0000202
Vedant Kumar61869712017-11-14 23:56:53 +0000203 /// Include \p S in the function hash.
204 bool VisitStmt(Stmt *S) {
205 auto Type = updateCounterMappings(S);
206 if (Hash.getHashVersion() != PGO_HASH_V1)
207 Type = getHashType(Hash.getHashVersion(), S);
208 if (Type != PGOHash::None)
209 Hash.combine(Type);
Justin Bognere4ca4412015-02-23 19:27:00 +0000210 return true;
211 }
Vedant Kumar61869712017-11-14 23:56:53 +0000212
213 bool TraverseIfStmt(IfStmt *If) {
214 // If we used the V1 hash, use the default traversal.
215 if (Hash.getHashVersion() == PGO_HASH_V1)
216 return Base::TraverseIfStmt(If);
217
218 // Otherwise, keep track of which branch we're in while traversing.
219 VisitStmt(If);
220 for (Stmt *CS : If->children()) {
221 if (!CS)
222 continue;
223 if (CS == If->getThen())
224 Hash.combine(PGOHash::IfThenBranch);
225 else if (CS == If->getElse())
226 Hash.combine(PGOHash::IfElseBranch);
227 TraverseStmt(CS);
228 }
229 Hash.combine(PGOHash::EndOfScope);
230 return true;
231 }
232
233// If the statement type \p N is nestable, and its nesting impacts profile
234// stability, define a custom traversal which tracks the end of the statement
235// in the hash (provided we're not using the V1 hash).
236#define DEFINE_NESTABLE_TRAVERSAL(N) \
237 bool Traverse##N(N *S) { \
238 Base::Traverse##N(S); \
239 if (Hash.getHashVersion() != PGO_HASH_V1) \
240 Hash.combine(PGOHash::EndOfScope); \
241 return true; \
242 }
243
244 DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
245 DEFINE_NESTABLE_TRAVERSAL(DoStmt)
246 DEFINE_NESTABLE_TRAVERSAL(ForStmt)
247 DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
248 DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
249 DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
250 DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
251
252 /// Get version \p HashVersion of the PGO hash for \p S.
253 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000254 switch (S->getStmtClass()) {
255 default:
256 break;
257 case Stmt::LabelStmtClass:
258 return PGOHash::LabelStmt;
259 case Stmt::WhileStmtClass:
260 return PGOHash::WhileStmt;
261 case Stmt::DoStmtClass:
262 return PGOHash::DoStmt;
263 case Stmt::ForStmtClass:
264 return PGOHash::ForStmt;
265 case Stmt::CXXForRangeStmtClass:
266 return PGOHash::CXXForRangeStmt;
267 case Stmt::ObjCForCollectionStmtClass:
268 return PGOHash::ObjCForCollectionStmt;
269 case Stmt::SwitchStmtClass:
270 return PGOHash::SwitchStmt;
271 case Stmt::CaseStmtClass:
272 return PGOHash::CaseStmt;
273 case Stmt::DefaultStmtClass:
274 return PGOHash::DefaultStmt;
275 case Stmt::IfStmtClass:
276 return PGOHash::IfStmt;
277 case Stmt::CXXTryStmtClass:
278 return PGOHash::CXXTryStmt;
279 case Stmt::CXXCatchStmtClass:
280 return PGOHash::CXXCatchStmt;
281 case Stmt::ConditionalOperatorClass:
282 return PGOHash::ConditionalOperator;
283 case Stmt::BinaryConditionalOperatorClass:
284 return PGOHash::BinaryConditionalOperator;
285 case Stmt::BinaryOperatorClass: {
286 const BinaryOperator *BO = cast<BinaryOperator>(S);
287 if (BO->getOpcode() == BO_LAnd)
288 return PGOHash::BinaryOperatorLAnd;
289 if (BO->getOpcode() == BO_LOr)
290 return PGOHash::BinaryOperatorLOr;
Vedant Kumar61869712017-11-14 23:56:53 +0000291 if (HashVersion == PGO_HASH_V2) {
292 switch (BO->getOpcode()) {
293 default:
294 break;
295 case BO_LT:
296 return PGOHash::BinaryOperatorLT;
297 case BO_GT:
298 return PGOHash::BinaryOperatorGT;
299 case BO_LE:
300 return PGOHash::BinaryOperatorLE;
301 case BO_GE:
302 return PGOHash::BinaryOperatorGE;
303 case BO_EQ:
304 return PGOHash::BinaryOperatorEQ;
305 case BO_NE:
306 return PGOHash::BinaryOperatorNE;
307 }
308 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000309 break;
310 }
311 }
Vedant Kumar61869712017-11-14 23:56:53 +0000312
313 if (HashVersion == PGO_HASH_V2) {
314 switch (S->getStmtClass()) {
315 default:
316 break;
317 case Stmt::GotoStmtClass:
318 return PGOHash::GotoStmt;
319 case Stmt::IndirectGotoStmtClass:
320 return PGOHash::IndirectGotoStmt;
321 case Stmt::BreakStmtClass:
322 return PGOHash::BreakStmt;
323 case Stmt::ContinueStmtClass:
324 return PGOHash::ContinueStmt;
325 case Stmt::ReturnStmtClass:
326 return PGOHash::ReturnStmt;
327 case Stmt::CXXThrowExprClass:
328 return PGOHash::ThrowExpr;
329 case Stmt::UnaryOperatorClass: {
330 const UnaryOperator *UO = cast<UnaryOperator>(S);
331 if (UO->getOpcode() == UO_LNot)
332 return PGOHash::UnaryOperatorLNot;
333 break;
334 }
335 }
336 }
337
Justin Bognere4ca4412015-02-23 19:27:00 +0000338 return PGOHash::None;
339 }
340};
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000341
Justin Bognere4ca4412015-02-23 19:27:00 +0000342/// A StmtVisitor that propagates the raw counts through the AST and
343/// records the count at statements where the value may change.
344struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
345 /// PGO state.
346 CodeGenPGO &PGO;
347
348 /// A flag that is set when the current count should be recorded on the
349 /// next statement, such as at the exit of a loop.
350 bool RecordNextStmtCount;
351
Justin Bognera909abf2015-05-02 00:48:27 +0000352 /// The count at the current location in the traversal.
353 uint64_t CurrentCount;
354
Justin Bognere4ca4412015-02-23 19:27:00 +0000355 /// The map of statements to count values.
356 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
357
358 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
359 struct BreakContinue {
360 uint64_t BreakCount;
361 uint64_t ContinueCount;
362 BreakContinue() : BreakCount(0), ContinueCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000363 };
Justin Bognere4ca4412015-02-23 19:27:00 +0000364 SmallVector<BreakContinue, 8> BreakContinueStack;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000365
Justin Bognere4ca4412015-02-23 19:27:00 +0000366 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
367 CodeGenPGO &PGO)
368 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000369
Justin Bognere4ca4412015-02-23 19:27:00 +0000370 void RecordStmtCount(const Stmt *S) {
371 if (RecordNextStmtCount) {
Justin Bognera909abf2015-05-02 00:48:27 +0000372 CountMap[S] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000373 RecordNextStmtCount = false;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000374 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000375 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000376
Justin Bogner07193cc2015-05-01 23:41:09 +0000377 /// Set and return the current count.
378 uint64_t setCount(uint64_t Count) {
Justin Bognera909abf2015-05-02 00:48:27 +0000379 CurrentCount = Count;
Justin Bogner07193cc2015-05-01 23:41:09 +0000380 return Count;
381 }
382
Justin Bognere4ca4412015-02-23 19:27:00 +0000383 void VisitStmt(const Stmt *S) {
384 RecordStmtCount(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000385 for (const Stmt *Child : S->children())
386 if (Child)
387 this->Visit(Child);
Justin Bognere4ca4412015-02-23 19:27:00 +0000388 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000389
Justin Bognere4ca4412015-02-23 19:27:00 +0000390 void VisitFunctionDecl(const FunctionDecl *D) {
391 // Counter tracks entry to the function body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000392 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
393 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000394 Visit(D->getBody());
395 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000396
Justin Bognere4ca4412015-02-23 19:27:00 +0000397 // Skip lambda expressions. We visit these as FunctionDecls when we're
398 // generating them and aren't interested in the body when generating a
399 // parent context.
400 void VisitLambdaExpr(const LambdaExpr *LE) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000401
Justin Bognere4ca4412015-02-23 19:27:00 +0000402 void VisitCapturedDecl(const CapturedDecl *D) {
403 // Counter tracks entry to the capture body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000404 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
405 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000406 Visit(D->getBody());
407 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000408
Justin Bognere4ca4412015-02-23 19:27:00 +0000409 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
410 // Counter tracks entry to the method body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000411 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
412 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000413 Visit(D->getBody());
414 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000415
Justin Bognere4ca4412015-02-23 19:27:00 +0000416 void VisitBlockDecl(const BlockDecl *D) {
417 // Counter tracks entry to the block body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000418 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
419 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000420 Visit(D->getBody());
421 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000422
Justin Bognere4ca4412015-02-23 19:27:00 +0000423 void VisitReturnStmt(const ReturnStmt *S) {
424 RecordStmtCount(S);
425 if (S->getRetValue())
426 Visit(S->getRetValue());
Justin Bognera909abf2015-05-02 00:48:27 +0000427 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000428 RecordNextStmtCount = true;
429 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000430
Justin Bognerf959feb2015-04-28 06:31:55 +0000431 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
432 RecordStmtCount(E);
433 if (E->getSubExpr())
434 Visit(E->getSubExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000435 CurrentCount = 0;
Justin Bognerf959feb2015-04-28 06:31:55 +0000436 RecordNextStmtCount = true;
437 }
438
Justin Bognere4ca4412015-02-23 19:27:00 +0000439 void VisitGotoStmt(const GotoStmt *S) {
440 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000441 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000442 RecordNextStmtCount = true;
443 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000444
Justin Bognere4ca4412015-02-23 19:27:00 +0000445 void VisitLabelStmt(const LabelStmt *S) {
446 RecordNextStmtCount = false;
447 // Counter tracks the block following the label.
Justin Bogner07193cc2015-05-01 23:41:09 +0000448 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
449 CountMap[S] = BlockCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000450 Visit(S->getSubStmt());
451 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000452
Justin Bognere4ca4412015-02-23 19:27:00 +0000453 void VisitBreakStmt(const BreakStmt *S) {
454 RecordStmtCount(S);
455 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
Justin Bognera909abf2015-05-02 00:48:27 +0000456 BreakContinueStack.back().BreakCount += CurrentCount;
457 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000458 RecordNextStmtCount = true;
459 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000460
Justin Bognere4ca4412015-02-23 19:27:00 +0000461 void VisitContinueStmt(const ContinueStmt *S) {
462 RecordStmtCount(S);
463 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
Justin Bognera909abf2015-05-02 00:48:27 +0000464 BreakContinueStack.back().ContinueCount += CurrentCount;
465 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000466 RecordNextStmtCount = true;
467 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000468
Justin Bognere4ca4412015-02-23 19:27:00 +0000469 void VisitWhileStmt(const WhileStmt *S) {
470 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000471 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000472
Justin Bognere4ca4412015-02-23 19:27:00 +0000473 BreakContinueStack.push_back(BreakContinue());
474 // Visit the body region first so the break/continue adjustments can be
475 // included when visiting the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000476 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
Justin Bognera909abf2015-05-02 00:48:27 +0000477 CountMap[S->getBody()] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000478 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000479 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000480
481 // ...then go back and propagate counts through the condition. The count
482 // at the start of the condition is the sum of the incoming edges,
483 // the backedge from the end of the loop body, and the edges from
484 // continue statements.
485 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000486 uint64_t CondCount =
487 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
488 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000489 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000490 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000491 RecordNextStmtCount = true;
492 }
493
494 void VisitDoStmt(const DoStmt *S) {
495 RecordStmtCount(S);
Justin Bogner07193cc2015-05-01 23:41:09 +0000496 uint64_t LoopCount = PGO.getRegionCount(S);
497
Justin Bognere4ca4412015-02-23 19:27:00 +0000498 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000499 // The count doesn't include the fallthrough from the parent scope. Add it.
Justin Bognera909abf2015-05-02 00:48:27 +0000500 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000501 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000502 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000503 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000504
505 BreakContinue BC = BreakContinueStack.pop_back_val();
506 // The count at the start of the condition is equal to the count at the
Justin Bogner07193cc2015-05-01 23:41:09 +0000507 // end of the body, plus any continues.
508 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
509 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000510 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000511 setCount(BC.BreakCount + CondCount - LoopCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000512 RecordNextStmtCount = true;
513 }
514
515 void VisitForStmt(const ForStmt *S) {
516 RecordStmtCount(S);
517 if (S->getInit())
518 Visit(S->getInit());
Justin Bogner07193cc2015-05-01 23:41:09 +0000519
Justin Bognera909abf2015-05-02 00:48:27 +0000520 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000521
Justin Bognere4ca4412015-02-23 19:27:00 +0000522 BreakContinueStack.push_back(BreakContinue());
523 // Visit the body region first. (This is basically the same as a while
524 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000525 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
526 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000527 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000528 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000529 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognere4ca4412015-02-23 19:27:00 +0000530
531 // The increment is essentially part of the body but it needs to include
532 // the count for all the continue statements.
533 if (S->getInc()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000534 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
535 CountMap[S->getInc()] = IncCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000536 Visit(S->getInc());
Justin Bognere4ca4412015-02-23 19:27:00 +0000537 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000538
Justin Bognere4ca4412015-02-23 19:27:00 +0000539 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000540 uint64_t CondCount =
541 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000542 if (S->getCond()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000543 CountMap[S->getCond()] = CondCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000544 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000545 }
Justin Bogner07193cc2015-05-01 23:41:09 +0000546 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000547 RecordNextStmtCount = true;
548 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000549
Justin Bognere4ca4412015-02-23 19:27:00 +0000550 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
551 RecordStmtCount(S);
Richard Smith8baa5002018-09-28 18:44:09 +0000552 if (S->getInit())
553 Visit(S->getInit());
Justin Bogner2e5d4842015-04-30 22:58:28 +0000554 Visit(S->getLoopVarStmt());
Justin Bognere4ca4412015-02-23 19:27:00 +0000555 Visit(S->getRangeStmt());
Richard Smith01694c32016-03-20 10:33:40 +0000556 Visit(S->getBeginStmt());
557 Visit(S->getEndStmt());
Justin Bogner07193cc2015-05-01 23:41:09 +0000558
Justin Bognera909abf2015-05-02 00:48:27 +0000559 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000560 BreakContinueStack.push_back(BreakContinue());
561 // Visit the body region first. (This is basically the same as a while
562 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000563 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
564 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000565 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000566 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000567 BreakContinue BC = BreakContinueStack.pop_back_val();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000568
Justin Bognere4ca4412015-02-23 19:27:00 +0000569 // The increment is essentially part of the body but it needs to include
570 // the count for all the continue statements.
Justin Bogner07193cc2015-05-01 23:41:09 +0000571 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
572 CountMap[S->getInc()] = IncCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000573 Visit(S->getInc());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000574
Justin Bognere4ca4412015-02-23 19:27:00 +0000575 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000576 uint64_t CondCount =
577 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
578 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000579 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000580 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000581 RecordNextStmtCount = true;
582 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000583
Justin Bognere4ca4412015-02-23 19:27:00 +0000584 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
585 RecordStmtCount(S);
586 Visit(S->getElement());
Justin Bognera909abf2015-05-02 00:48:27 +0000587 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000588 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000589 // Counter tracks the body of the loop.
590 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
591 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000592 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000593 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000594 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000595
596 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
597 BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000598 RecordNextStmtCount = true;
599 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000600
Justin Bognere4ca4412015-02-23 19:27:00 +0000601 void VisitSwitchStmt(const SwitchStmt *S) {
602 RecordStmtCount(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000603 if (S->getInit())
604 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000605 Visit(S->getCond());
Justin Bognera909abf2015-05-02 00:48:27 +0000606 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000607 BreakContinueStack.push_back(BreakContinue());
608 Visit(S->getBody());
609 // If the switch is inside a loop, add the continue counts.
610 BreakContinue BC = BreakContinueStack.pop_back_val();
611 if (!BreakContinueStack.empty())
612 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
613 // Counter tracks the exit block of the switch.
Justin Bogner07193cc2015-05-01 23:41:09 +0000614 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000615 RecordNextStmtCount = true;
616 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000617
Justin Bogner07193cc2015-05-01 23:41:09 +0000618 void VisitSwitchCase(const SwitchCase *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000619 RecordNextStmtCount = false;
620 // Counter for this particular case. This counts only jumps from the
621 // switch header and does not include fallthrough from the case before
622 // this one.
Justin Bogner07193cc2015-05-01 23:41:09 +0000623 uint64_t CaseCount = PGO.getRegionCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000624 setCount(CurrentCount + CaseCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000625 // We need the count without fallthrough in the mapping, so it's more useful
626 // for branch probabilities.
627 CountMap[S] = CaseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000628 RecordNextStmtCount = true;
629 Visit(S->getSubStmt());
630 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000631
Justin Bognere4ca4412015-02-23 19:27:00 +0000632 void VisitIfStmt(const IfStmt *S) {
633 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000634 uint64_t ParentCount = CurrentCount;
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000635 if (S->getInit())
636 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000637 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000638
Justin Bogner07193cc2015-05-01 23:41:09 +0000639 // Counter tracks the "then" part of an if statement. The count for
640 // the "else" part, if it exists, will be calculated from this counter.
641 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
642 CountMap[S->getThen()] = ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000643 Visit(S->getThen());
Justin Bognera909abf2015-05-02 00:48:27 +0000644 uint64_t OutCount = CurrentCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000645
Justin Bogner07193cc2015-05-01 23:41:09 +0000646 uint64_t ElseCount = ParentCount - ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000647 if (S->getElse()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000648 setCount(ElseCount);
649 CountMap[S->getElse()] = ElseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000650 Visit(S->getElse());
Justin Bognera909abf2015-05-02 00:48:27 +0000651 OutCount += CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000652 } else
653 OutCount += ElseCount;
654 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000655 RecordNextStmtCount = true;
656 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000657
Justin Bognere4ca4412015-02-23 19:27:00 +0000658 void VisitCXXTryStmt(const CXXTryStmt *S) {
659 RecordStmtCount(S);
660 Visit(S->getTryBlock());
661 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
662 Visit(S->getHandler(I));
663 // Counter tracks the continuation block of the try statement.
Justin Bogner07193cc2015-05-01 23:41:09 +0000664 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000665 RecordNextStmtCount = true;
666 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000667
Justin Bognere4ca4412015-02-23 19:27:00 +0000668 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
669 RecordNextStmtCount = false;
670 // Counter tracks the catch statement's handler block.
Justin Bogner07193cc2015-05-01 23:41:09 +0000671 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
672 CountMap[S] = CatchCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000673 Visit(S->getHandlerBlock());
674 }
675
676 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
677 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000678 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000679 Visit(E->getCond());
680
Justin Bogner07193cc2015-05-01 23:41:09 +0000681 // Counter tracks the "true" part of a conditional operator. The
682 // count in the "false" part will be calculated from this counter.
683 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
684 CountMap[E->getTrueExpr()] = TrueCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000685 Visit(E->getTrueExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000686 uint64_t OutCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000687
Justin Bogner07193cc2015-05-01 23:41:09 +0000688 uint64_t FalseCount = setCount(ParentCount - TrueCount);
689 CountMap[E->getFalseExpr()] = FalseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000690 Visit(E->getFalseExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000691 OutCount += CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000692
Justin Bogner07193cc2015-05-01 23:41:09 +0000693 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000694 RecordNextStmtCount = true;
695 }
696
697 void VisitBinLAnd(const BinaryOperator *E) {
698 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000699 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000700 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000701 // Counter tracks the right hand side of a logical and operator.
702 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
703 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000704 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000705 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000706 RecordNextStmtCount = true;
707 }
708
709 void VisitBinLOr(const BinaryOperator *E) {
710 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000711 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000712 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000713 // Counter tracks the right hand side of a logical or operator.
714 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
715 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000716 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000717 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000718 RecordNextStmtCount = true;
719 }
720};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000721} // end anonymous namespace
Justin Bogneref512b92014-01-06 22:27:43 +0000722
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000723void PGOHash::combine(HashType Type) {
724 // Check that we never combine 0 and only have six bits.
725 assert(Type && "Hash is invalid: unexpected type 0");
726 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
727
728 // Pass through MD5 if enough work has built up.
729 if (Count && Count % NumTypesPerWord == 0) {
730 using namespace llvm::support;
731 uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
732 MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
733 Working = 0;
734 }
735
736 // Accumulate the current type.
737 ++Count;
738 Working = Working << NumBitsPerType | Type;
739}
740
741uint64_t PGOHash::finalize() {
742 // Use Working as the hash directly if we never used MD5.
743 if (Count <= NumTypesPerWord)
744 // No need to byte swap here, since none of the math was endian-dependent.
745 // This number will be byte-swapped as required on endianness transitions,
746 // so we will see the same value on the other side.
747 return Working;
748
749 // Check for remaining work in Working.
750 if (Working)
751 MD5.update(Working);
752
753 // Finalize the MD5 and return the hash.
754 llvm::MD5::MD5Result Result;
755 MD5.final(Result);
756 using namespace llvm::support;
Zachary Turner82a0c972017-03-20 23:33:18 +0000757 return Result.low();
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000758}
759
Serge Pavlov3a561452015-12-06 14:32:39 +0000760void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
761 const Decl *D = GD.getDecl();
Vedant Kumar33d0a1c2017-06-30 21:02:14 +0000762 if (!D->hasBody())
763 return;
764
Rong Xu9837ef52016-02-04 18:39:09 +0000765 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
Justin Bogner837a6f62014-04-18 21:52:00 +0000766 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
767 if (!InstrumentRegions && !PGOReader)
Justin Bogneref512b92014-01-06 22:27:43 +0000768 return;
Justin Bogner3212b182014-04-25 07:20:05 +0000769 if (D->isImplicit())
Justin Bogneref512b92014-01-06 22:27:43 +0000770 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000771 // Constructors and destructors may be represented by several functions in IR.
772 // If so, instrument only base variant, others are implemented by delegation
773 // to the base one, it would be counted twice otherwise.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000774 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
775 if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
776 return;
777
778 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
779 if (GD.getCtorType() != Ctor_Base &&
780 CodeGenFunction::IsConstructorDelegationValid(CCD))
781 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000782 }
Alex Lorenzee024992014-08-04 18:41:51 +0000783 CGM.ClearUnusedCoverageMapping(D);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000784 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000785
Justin Bogneref512b92014-01-06 22:27:43 +0000786 mapRegionCounters(D);
Justin Bogner970ac602014-12-08 19:04:51 +0000787 if (CGM.getCodeGenOpts().CoverageMapping)
788 emitCounterRegionMapping(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000789 if (PGOReader) {
Justin Bogner40b8ba12014-06-26 01:45:07 +0000790 SourceManager &SM = CGM.getContext().getSourceManager();
791 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000792 computeRegionCounts(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000793 applyFunctionAttributes(PGOReader, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000794 }
Justin Bogneref512b92014-01-06 22:27:43 +0000795}
796
797void CodeGenPGO::mapRegionCounters(const Decl *D) {
Vedant Kumar61869712017-11-14 23:56:53 +0000798 // Use the latest hash version when inserting instrumentation, but use the
799 // version in the indexed profile if we're reading PGO data.
800 PGOHashVersion HashVersion = PGO_HASH_LATEST;
801 if (auto *PGOReader = CGM.getPGOReader())
802 HashVersion = getPGOHashVersion(PGOReader, CGM);
803
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000804 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Vedant Kumar61869712017-11-14 23:56:53 +0000805 MapRegionCounters Walker(HashVersion, *RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000806 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000807 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000808 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000809 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000810 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000811 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000812 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
813 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogner3212b182014-04-25 07:20:05 +0000814 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
Justin Bogneref512b92014-01-06 22:27:43 +0000815 NumRegionCounters = Walker.NextCounter;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000816 FunctionHash = Walker.Hash.finalize();
Justin Bogneref512b92014-01-06 22:27:43 +0000817}
818
Vedant Kumarc468bb82016-07-11 22:57:44 +0000819bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
Vedant Kumarbc370f02017-04-24 20:52:04 +0000820 if (!D->getBody())
821 return true;
822
Vedant Kumarc468bb82016-07-11 22:57:44 +0000823 // Don't map the functions in system headers.
824 const auto &SM = CGM.getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000825 auto Loc = D->getBody()->getBeginLoc();
Vedant Kumarc468bb82016-07-11 22:57:44 +0000826 return SM.isInSystemHeader(Loc);
827}
828
829void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
830 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000831 return;
832
Justin Bogner970ac602014-12-08 19:04:51 +0000833 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000834 llvm::raw_string_ostream OS(CoverageMapping);
835 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
836 CGM.getContext().getSourceManager(),
Justin Bognere5ee6c52014-10-02 16:44:01 +0000837 CGM.getLangOpts(), RegionCounterMap.get());
Alex Lorenzee024992014-08-04 18:41:51 +0000838 MappingGen.emitCounterMapping(D, OS);
839 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000840
841 if (CoverageMapping.empty())
842 return;
843
844 CGM.getCoverageMapping()->addFunctionMappingRecord(
845 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
Alex Lorenzee024992014-08-04 18:41:51 +0000846}
847
848void
Justin Bogner60d852b2015-04-23 00:31:16 +0000849CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
Alex Lorenzee024992014-08-04 18:41:51 +0000850 llvm::GlobalValue::LinkageTypes Linkage) {
Vedant Kumarc468bb82016-07-11 22:57:44 +0000851 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000852 return;
853
Justin Bogner970ac602014-12-08 19:04:51 +0000854 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000855 llvm::raw_string_ostream OS(CoverageMapping);
856 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
857 CGM.getContext().getSourceManager(),
858 CGM.getLangOpts());
859 MappingGen.emitEmptyMapping(D, OS);
860 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000861
862 if (CoverageMapping.empty())
863 return;
864
Justin Bogner60d852b2015-04-23 00:31:16 +0000865 setFuncName(Name, Linkage);
Justin Bogner970ac602014-12-08 19:04:51 +0000866 CGM.getCoverageMapping()->addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000867 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
Alex Lorenzee024992014-08-04 18:41:51 +0000868}
869
Bob Wilsonbf854f02014-02-17 19:21:09 +0000870void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000871 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000872 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000873 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
874 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000875 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
876 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000877 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
878 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000879 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
880 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000881}
882
Justin Bogner837a6f62014-04-18 21:52:00 +0000883void
884CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
885 llvm::Function *Fn) {
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000886 if (!haveRegionCounts())
887 return;
888
Hans Wennborgdcfba332015-10-06 23:40:43 +0000889 uint64_t FunctionCount = getRegionCount(nullptr);
Diego Novilloaa8b1cb2015-05-27 21:58:42 +0000890 Fn->setEntryCount(FunctionCount);
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000891}
892
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000893void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
894 llvm::Value *StepV) {
Rong Xu9837ef52016-02-04 18:39:09 +0000895 if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000896 return;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000897 if (!Builder.GetInsertBlock())
Justin Bogner203f91e2015-01-09 01:46:40 +0000898 return;
Justin Bogner66242d62015-04-23 23:06:47 +0000899
900 unsigned Counter = (*RegionCounterMap)[S];
Justin Bogner970ac602014-12-08 19:04:51 +0000901 auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000902
903 llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
904 Builder.getInt64(FunctionHash),
905 Builder.getInt32(NumRegionCounters),
906 Builder.getInt32(Counter), StepV};
907 if (!StepV)
908 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
909 makeArrayRef(Args, 4));
910 else
911 Builder.CreateCall(
912 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
913 makeArrayRef(Args));
Justin Bogneref512b92014-01-06 22:27:43 +0000914}
915
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000916// This method either inserts a call to the profile run-time during
917// instrumentation or puts profile data into metadata for PGO use.
918void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
919 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
920
921 if (!EnableValueProfiling)
922 return;
923
924 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
925 return;
926
Betul Buyukkurt3da993c2016-03-31 18:41:34 +0000927 if (isa<llvm::Constant>(ValuePtr))
928 return;
929
Rong Xu9837ef52016-02-04 18:39:09 +0000930 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000931 if (InstrumentValueSites && RegionCounterMap) {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000932 auto BuilderInsertPoint = Builder.saveIP();
933 Builder.SetInsertPoint(ValueSite);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000934 llvm::Value *Args[5] = {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000935 llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000936 Builder.getInt64(FunctionHash),
937 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
938 Builder.getInt32(ValueKind),
939 Builder.getInt32(NumValueSites[ValueKind]++)
940 };
941 Builder.CreateCall(
942 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000943 Builder.restoreIP(BuilderInsertPoint);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000944 return;
945 }
946
947 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
948 if (PGOReader && haveRegionCounts()) {
949 // We record the top most called three functions at each call site.
950 // Profile metadata contains "VP" string identifying this metadata
951 // as value profiling data, then a uint32_t value for the value profiling
952 // kind, a uint64_t value for the total number of times the call is
953 // executed, followed by the function hash and execution count (uint64_t)
954 // pairs for each function.
955 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
956 return;
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000957
Xinliang David Li5527a9d2016-02-04 19:54:17 +0000958 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
959 (llvm::InstrProfValueKind)ValueKind,
960 NumValueSites[ValueKind]);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000961
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000962 NumValueSites[ValueKind]++;
963 }
964}
965
Justin Bogner40b8ba12014-06-26 01:45:07 +0000966void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
967 bool IsInMainFile) {
968 CGM.getPGOStats().addVisited(IsInMainFile);
Justin Bogner7f8cf5b2014-12-02 22:38:52 +0000969 RegionCounts.clear();
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000970 llvm::Expected<llvm::InstrProfRecord> RecordExpected =
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000971 PGOReader->getInstrProfRecord(FuncName, FunctionHash);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000972 if (auto E = RecordExpected.takeError()) {
973 auto IPE = llvm::InstrProfError::take(std::move(E));
974 if (IPE == llvm::instrprof_error::unknown_function)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000975 CGM.getPGOStats().addMissing(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000976 else if (IPE == llvm::instrprof_error::hash_mismatch)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000977 CGM.getPGOStats().addMismatched(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000978 else if (IPE == llvm::instrprof_error::malformed)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000979 // TODO: Consider a more specific warning for this case.
980 CGM.getPGOStats().addMismatched(IsInMainFile);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000981 return;
Justin Bognere2ef2a02014-04-15 21:22:35 +0000982 }
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000983 ProfRecord =
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000984 llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000985 RegionCounts = ProfRecord->Counts;
Justin Bogneref512b92014-01-06 22:27:43 +0000986}
987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000988/// Calculate what to divide by to scale weights.
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000989///
990/// Given the maximum weight, calculate a divisor that will scale all the
991/// weights to strictly less than UINT32_MAX.
992static uint64_t calculateWeightScale(uint64_t MaxWeight) {
993 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
994}
995
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000996/// Scale an individual branch weight (and add 1).
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000997///
998/// Scale a 64-bit weight down to 32-bits using \c Scale.
999///
1000/// According to Laplace's Rule of Succession, it is better to compute the
1001/// weight based on the count plus 1, so universally add 1 to the value.
1002///
1003/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1004/// greater than \c Weight.
1005static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1006 assert(Scale && "scale by 0?");
1007 uint64_t Scaled = Weight / Scale + 1;
1008 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1009 return Scaled;
1010}
1011
Justin Bogner65512642015-05-02 05:00:55 +00001012llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1013 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001014 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +00001015 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001016 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +00001017
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001018 // Calculate how to scale down to 32-bits.
1019 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1020
Justin Bogneref512b92014-01-06 22:27:43 +00001021 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001022 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1023 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +00001024}
1025
Justin Bogner65512642015-05-02 05:00:55 +00001026llvm::MDNode *
1027CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001028 // We need at least two elements to create meaningful weights.
1029 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001030 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001031
Justin Bognerf3aefca2014-04-04 02:48:51 +00001032 // Check for empty weights.
1033 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1034 if (MaxWeight == 0)
1035 return nullptr;
1036
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001037 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +00001038 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001039
Justin Bogneref512b92014-01-06 22:27:43 +00001040 SmallVector<uint32_t, 16> ScaledWeights;
1041 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001042 for (uint64_t W : Weights)
1043 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1044
1045 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +00001046 return MDHelper.createBranchWeights(ScaledWeights);
1047}
Bob Wilsonbf854f02014-02-17 19:21:09 +00001048
Justin Bogner65512642015-05-02 05:00:55 +00001049llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1050 uint64_t LoopCount) {
1051 if (!PGO.haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001052 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001053 Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
Justin Bogner1c21c282015-04-13 12:23:19 +00001054 assert(CondCount.hasValue() && "missing expected loop condition count");
1055 if (*CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001056 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001057 return createProfileWeights(LoopCount,
1058 std::max(*CondCount, LoopCount) - LoopCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +00001059}