clang 23.0.0git
CodeGenPGO.cpp
Go to the documentation of this file.
1//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based profile-guided optimization
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenPGO.h"
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CoverageMappingGen.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/MDBuilder.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Endian.h"
24#include "llvm/Support/MD5.h"
25#include <optional>
26
27namespace llvm {
28extern cl::opt<bool> EnableSingleByteCoverage;
29} // namespace llvm
30
31static llvm::cl::opt<bool>
32 EnableValueProfiling("enable-value-profiling",
33 llvm::cl::desc("Enable value profiling"),
34 llvm::cl::Hidden, llvm::cl::init(false));
35
36using namespace clang;
37using namespace CodeGen;
38
39void CodeGenPGO::setFuncName(StringRef Name,
40 llvm::GlobalValue::LinkageTypes Linkage) {
41 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
42 FuncName = llvm::getPGOFuncName(
44 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
45
46 // If we're generating a profile, create a variable for the name.
48 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
49}
50
51void CodeGenPGO::setFuncName(llvm::Function *Fn) {
52 setFuncName(Fn->getName(), Fn->getLinkage());
53 // Create PGOFuncName meta data.
54 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
55}
56
57/// The version of the PGO hash algorithm.
58enum PGOHashVersion : unsigned {
63
64 // Keep this set to the latest hash version.
66};
67
68namespace {
69/// Stable hasher for PGO region counters.
70///
71/// PGOHash produces a stable hash of a given function's control flow.
72///
73/// Changing the output of this hash will invalidate all previously generated
74/// profiles -- i.e., don't do it.
75///
76/// \note When this hash does eventually change (years?), we still need to
77/// support old hashes. We'll need to pull in the version number from the
78/// profile data format and use the matching hash function.
79class PGOHash {
80 uint64_t Working;
81 unsigned Count;
82 PGOHashVersion HashVersion;
83 llvm::MD5 MD5;
84
85 static const int NumBitsPerType = 6;
86 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
87 static const unsigned TooBig = 1u << NumBitsPerType;
88
89public:
90 /// Hash values for AST nodes.
91 ///
92 /// Distinct values for AST nodes that have region counters attached.
93 ///
94 /// These values must be stable. All new members must be added at the end,
95 /// and no members should be removed. Changing the enumeration value for an
96 /// AST node will affect the hash of every function that contains that node.
97 enum HashType : unsigned char {
98 None = 0,
99 LabelStmt = 1,
100 WhileStmt,
101 DoStmt,
102 ForStmt,
103 CXXForRangeStmt,
104 ObjCForCollectionStmt,
105 SwitchStmt,
106 CaseStmt,
107 DefaultStmt,
108 IfStmt,
109 CXXTryStmt,
110 CXXCatchStmt,
111 ConditionalOperator,
112 BinaryOperatorLAnd,
113 BinaryOperatorLOr,
114 BinaryConditionalOperator,
115 // The preceding values are available with PGO_HASH_V1.
116
117 EndOfScope,
118 IfThenBranch,
119 IfElseBranch,
120 GotoStmt,
121 IndirectGotoStmt,
122 BreakStmt,
123 ContinueStmt,
124 ReturnStmt,
125 ThrowExpr,
126 UnaryOperatorLNot,
127 BinaryOperatorLT,
128 BinaryOperatorGT,
129 BinaryOperatorLE,
130 BinaryOperatorGE,
131 BinaryOperatorEQ,
132 BinaryOperatorNE,
133 // The preceding values are available since PGO_HASH_V2.
134
135 // Keep this last. It's for the static assert that follows.
136 LastHashType
137 };
138 static_assert(LastHashType <= TooBig, "Too many types in HashType");
139
140 PGOHash(PGOHashVersion HashVersion)
141 : Working(0), Count(0), HashVersion(HashVersion) {}
142 void combine(HashType Type);
144 PGOHashVersion getHashVersion() const { return HashVersion; }
145};
146const int PGOHash::NumBitsPerType;
147const unsigned PGOHash::NumTypesPerWord;
148const unsigned PGOHash::TooBig;
149
150/// Get the PGO hash version used in the given indexed profile.
151static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
152 CodeGenModule &CGM) {
153 if (PGOReader->getVersion() <= 4)
154 return PGO_HASH_V1;
155 if (PGOReader->getVersion() <= 5)
156 return PGO_HASH_V2;
157 if (PGOReader->getVersion() <= 12)
158 return PGO_HASH_V3;
159 return PGO_HASH_V4;
160}
161
162/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
163struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
164 using Base = RecursiveASTVisitor<MapRegionCounters>;
165
166 /// The next counter value to assign.
167 unsigned NextCounter;
168 /// The function hash.
169 PGOHash Hash;
170 /// The map of statements to counters.
171 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap;
172 /// The state of MC/DC Coverage in this function.
173 MCDC::State &MCDCState;
174 /// Maximum number of supported MC/DC conditions in a boolean expression.
175 unsigned MCDCMaxCond;
176 /// The profile version.
177 uint64_t ProfileVersion;
178 /// Diagnostics Engine used to report warnings.
179 DiagnosticsEngine &Diag;
180
181 MapRegionCounters(PGOHashVersion HashVersion, uint64_t ProfileVersion,
182 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap,
183 MCDC::State &MCDCState, unsigned MCDCMaxCond,
184 DiagnosticsEngine &Diag)
185 : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap),
186 MCDCState(MCDCState), MCDCMaxCond(MCDCMaxCond),
187 ProfileVersion(ProfileVersion), Diag(Diag) {}
188
189 // Blocks and lambdas are handled as separate functions, so we need not
190 // traverse them in the parent context.
191 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
192 bool TraverseLambdaExpr(LambdaExpr *LE) {
193 // Traverse the captures, but not the body.
194 for (auto C : zip(LE->captures(), LE->capture_inits()))
195 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
196 return true;
197 }
198 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
199
200 bool VisitDecl(const Decl *D) {
201 switch (D->getKind()) {
202 default:
203 break;
204 case Decl::Function:
205 case Decl::CXXMethod:
206 case Decl::CXXConstructor:
207 case Decl::CXXDestructor:
208 case Decl::CXXConversion:
209 case Decl::ObjCMethod:
210 case Decl::Block:
211 case Decl::Captured:
212 CounterMap[D->getBody()] = NextCounter++;
213 break;
214 }
215 return true;
216 }
217
218 /// If \p S gets a fresh counter, update the counter mappings. Return the
219 /// V1 hash of \p S.
220 PGOHash::HashType updateCounterMappings(Stmt *S) {
221 auto Type = getHashType(PGO_HASH_V1, S);
222 if (Type != PGOHash::None)
223 CounterMap[S] = NextCounter++;
224 return Type;
225 }
226
227 /// The following stacks are used with dataTraverseStmtPre() and
228 /// dataTraverseStmtPost() to track the depth of nested logical operators in a
229 /// boolean expression in a function. The ultimate purpose is to keep track
230 /// of the number of leaf-level conditions in the boolean expression so that a
231 /// profile bitmap can be allocated based on that number.
232 ///
233 /// The stacks are also used to find error cases and notify the user. A
234 /// standard logical operator nest for a boolean expression could be in a form
235 /// similar to this: "x = a && b && c && (d || f)"
236 unsigned NumCond = 0;
237 bool SplitNestedLogicalOp = false;
238 SmallVector<const Stmt *, 16> NonLogOpStack;
239 SmallVector<const BinaryOperator *, 16> LogOpStack;
240
241 // Hook: dataTraverseStmtPre() is invoked prior to visiting an AST Stmt node.
242 bool dataTraverseStmtPre(Stmt *S) {
243 /// If MC/DC is not enabled, MCDCMaxCond will be set to 0. Do nothing.
244 if (MCDCMaxCond == 0)
245 return true;
246
247 /// At the top of the logical operator nest, reset the number of conditions,
248 /// also forget previously seen split nesting cases.
249 if (LogOpStack.empty()) {
250 NumCond = 0;
251 SplitNestedLogicalOp = false;
252 }
253
254 if (const Expr *E = dyn_cast<Expr>(S)) {
255 if (const auto *BinOp =
256 dyn_cast<BinaryOperator>(CodeGenFunction::stripCond(E));
257 BinOp && BinOp->isLogicalOp()) {
258 /// Check for "split-nested" logical operators. This happens when a new
259 /// boolean expression logical-op nest is encountered within an existing
260 /// boolean expression, separated by a non-logical operator. For
261 /// example, in "x = (a && b && c && foo(d && f))", the "d && f" case
262 /// starts a new boolean expression that is separated from the other
263 /// conditions by the operator foo(). Split-nested cases are not
264 /// supported by MC/DC.
265 SplitNestedLogicalOp = SplitNestedLogicalOp || !NonLogOpStack.empty();
266
267 LogOpStack.push_back(BinOp);
268 return true;
269 }
270 }
271
272 /// Keep track of non-logical operators. These are OK as long as we don't
273 /// encounter a new logical operator after seeing one.
274 if (!LogOpStack.empty())
275 NonLogOpStack.push_back(S);
276
277 return true;
278 }
279
280 // Hook: dataTraverseStmtPost() is invoked by the AST visitor after visiting
281 // an AST Stmt node. MC/DC will use it to to signal when the top of a
282 // logical operation (boolean expression) nest is encountered.
283 bool dataTraverseStmtPost(Stmt *S) {
284 /// If MC/DC is not enabled, MCDCMaxCond will be set to 0. Do nothing.
285 if (MCDCMaxCond == 0)
286 return true;
287
288 if (const Expr *E = dyn_cast<Expr>(S)) {
289 const BinaryOperator *BinOp =
290 dyn_cast<BinaryOperator>(CodeGenFunction::stripCond(E));
291 if (BinOp && BinOp->isLogicalOp()) {
292 assert(LogOpStack.back() == BinOp);
293 LogOpStack.pop_back();
294
295 /// At the top of logical operator nest:
296 if (LogOpStack.empty()) {
297 /// Was the "split-nested" logical operator case encountered?
298 if (SplitNestedLogicalOp) {
299 Diag.Report(S->getBeginLoc(), diag::warn_pgo_nested_boolean_expr);
300 return true;
301 }
302
303 /// Was the maximum number of conditions encountered?
304 if (NumCond > MCDCMaxCond) {
305 Diag.Report(S->getBeginLoc(), diag::warn_pgo_condition_limit)
306 << NumCond << MCDCMaxCond;
307 return true;
308 }
309
310 // Otherwise, allocate the Decision.
311 MCDCState.DecisionByStmt[BinOp].ID = MCDCState.DecisionByStmt.size();
312 }
313 return true;
314 }
315 }
316
317 if (!LogOpStack.empty())
318 NonLogOpStack.pop_back();
319
320 return true;
321 }
322
323 /// The RHS of all logical operators gets a fresh counter in order to count
324 /// how many times the RHS evaluates to true or false, depending on the
325 /// semantics of the operator. This is only valid for ">= v7" of the profile
326 /// version so that we facilitate backward compatibility. In addition, in
327 /// order to use MC/DC, count the number of total LHS and RHS conditions.
328 bool VisitBinaryOperator(BinaryOperator *S) {
329 if (S->isLogicalOp()) {
331 NumCond++;
332
334 if (ProfileVersion >= llvm::IndexedInstrProf::Version7)
335 CounterMap[S->getRHS()] = NextCounter++;
336
337 NumCond++;
338 }
339 }
340 return Base::VisitBinaryOperator(S);
341 }
342
343 bool VisitConditionalOperator(ConditionalOperator *S) {
345 CounterMap[S->getTrueExpr()] = NextCounter++;
347 CounterMap[S->getFalseExpr()] = NextCounter++;
348 return Base::VisitConditionalOperator(S);
349 }
350
351 /// Include \p S in the function hash.
352 bool VisitStmt(Stmt *S) {
353 auto Type = updateCounterMappings(S);
354 if (Hash.getHashVersion() != PGO_HASH_V1)
355 Type = getHashType(Hash.getHashVersion(), S);
356 if (Type != PGOHash::None)
357 Hash.combine(Type);
358 return true;
359 }
360
361 bool TraverseIfStmt(IfStmt *If) {
362 // If we used the V1 hash, use the default traversal.
363 if (Hash.getHashVersion() == PGO_HASH_V1)
364 return Base::TraverseIfStmt(If);
365
366 // When single byte coverage mode is enabled, add a counter to then and
367 // else.
368 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
369 for (Stmt *CS : If->children()) {
370 if (!CS || NoSingleByteCoverage)
371 continue;
372 if (CS == If->getThen())
373 CounterMap[If->getThen()] = NextCounter++;
374 else if (CS == If->getElse())
375 CounterMap[If->getElse()] = NextCounter++;
376 }
377
378 // Otherwise, keep track of which branch we're in while traversing.
379 VisitStmt(If);
380
381 for (Stmt *CS : If->children()) {
382 if (!CS)
383 continue;
384 if (CS == If->getThen())
385 Hash.combine(PGOHash::IfThenBranch);
386 else if (CS == If->getElse())
387 Hash.combine(PGOHash::IfElseBranch);
388 TraverseStmt(CS);
389 }
390 Hash.combine(PGOHash::EndOfScope);
391 return true;
392 }
393
394 bool TraverseWhileStmt(WhileStmt *While) {
395 // When single byte coverage mode is enabled, add a counter to condition and
396 // body.
397 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
398 for (Stmt *CS : While->children()) {
399 if (!CS || NoSingleByteCoverage)
400 continue;
401 if (CS == While->getCond())
402 CounterMap[While->getCond()] = NextCounter++;
403 else if (CS == While->getBody())
404 CounterMap[While->getBody()] = NextCounter++;
405 }
406
407 Base::TraverseWhileStmt(While);
408 if (Hash.getHashVersion() != PGO_HASH_V1)
409 Hash.combine(PGOHash::EndOfScope);
410 return true;
411 }
412
413 bool TraverseDoStmt(DoStmt *Do) {
414 // When single byte coverage mode is enabled, add a counter to condition and
415 // body.
416 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
417 for (Stmt *CS : Do->children()) {
418 if (!CS || NoSingleByteCoverage)
419 continue;
420 if (CS == Do->getCond())
421 CounterMap[Do->getCond()] = NextCounter++;
422 else if (CS == Do->getBody())
423 CounterMap[Do->getBody()] = NextCounter++;
424 }
425
426 Base::TraverseDoStmt(Do);
427 if (Hash.getHashVersion() != PGO_HASH_V1)
428 Hash.combine(PGOHash::EndOfScope);
429 return true;
430 }
431
432 bool TraverseForStmt(ForStmt *For) {
433 // When single byte coverage mode is enabled, add a counter to condition,
434 // increment and body.
435 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
436 for (Stmt *CS : For->children()) {
437 if (!CS || NoSingleByteCoverage)
438 continue;
439 if (CS == For->getCond())
440 CounterMap[For->getCond()] = NextCounter++;
441 else if (CS == For->getInc())
442 CounterMap[For->getInc()] = NextCounter++;
443 else if (CS == For->getBody())
444 CounterMap[For->getBody()] = NextCounter++;
445 }
446
447 Base::TraverseForStmt(For);
448 if (Hash.getHashVersion() != PGO_HASH_V1)
449 Hash.combine(PGOHash::EndOfScope);
450 return true;
451 }
452
453 bool TraverseCXXForRangeStmt(CXXForRangeStmt *ForRange) {
454 // When single byte coverage mode is enabled, add a counter to body.
455 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
456 for (Stmt *CS : ForRange->children()) {
457 if (!CS || NoSingleByteCoverage)
458 continue;
459 if (CS == ForRange->getBody())
460 CounterMap[ForRange->getBody()] = NextCounter++;
461 }
462
463 Base::TraverseCXXForRangeStmt(ForRange);
464 if (Hash.getHashVersion() != PGO_HASH_V1)
465 Hash.combine(PGOHash::EndOfScope);
466 return true;
467 }
468
469// If the statement type \p N is nestable, and its nesting impacts profile
470// stability, define a custom traversal which tracks the end of the statement
471// in the hash (provided we're not using the V1 hash).
472#define DEFINE_NESTABLE_TRAVERSAL(N) \
473 bool Traverse##N(N *S) { \
474 Base::Traverse##N(S); \
475 if (Hash.getHashVersion() != PGO_HASH_V1) \
476 Hash.combine(PGOHash::EndOfScope); \
477 return true; \
478 }
479
483
484 /// Get version \p HashVersion of the PGO hash for \p S.
485 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
486 switch (S->getStmtClass()) {
487 default:
488 break;
489 case Stmt::LabelStmtClass:
490 return PGOHash::LabelStmt;
491 case Stmt::WhileStmtClass:
492 return PGOHash::WhileStmt;
493 case Stmt::DoStmtClass:
494 return PGOHash::DoStmt;
495 case Stmt::ForStmtClass:
496 return PGOHash::ForStmt;
497 case Stmt::CXXForRangeStmtClass:
498 return PGOHash::CXXForRangeStmt;
499 case Stmt::ObjCForCollectionStmtClass:
500 return PGOHash::ObjCForCollectionStmt;
501 case Stmt::SwitchStmtClass:
502 return PGOHash::SwitchStmt;
503 case Stmt::CaseStmtClass:
504 return PGOHash::CaseStmt;
505 case Stmt::DefaultStmtClass:
506 return PGOHash::DefaultStmt;
507 case Stmt::IfStmtClass:
508 return PGOHash::IfStmt;
509 case Stmt::CXXTryStmtClass:
510 return PGOHash::CXXTryStmt;
511 case Stmt::CXXCatchStmtClass:
512 return PGOHash::CXXCatchStmt;
513 case Stmt::ConditionalOperatorClass:
514 return PGOHash::ConditionalOperator;
515 case Stmt::BinaryConditionalOperatorClass:
516 return PGOHash::BinaryConditionalOperator;
517 case Stmt::BinaryOperatorClass: {
519 if (BO->getOpcode() == BO_LAnd)
520 return PGOHash::BinaryOperatorLAnd;
521 if (BO->getOpcode() == BO_LOr)
522 return PGOHash::BinaryOperatorLOr;
523 if (HashVersion >= PGO_HASH_V2) {
524 switch (BO->getOpcode()) {
525 default:
526 break;
527 case BO_LT:
528 return PGOHash::BinaryOperatorLT;
529 case BO_GT:
530 return PGOHash::BinaryOperatorGT;
531 case BO_LE:
532 return PGOHash::BinaryOperatorLE;
533 case BO_GE:
534 return PGOHash::BinaryOperatorGE;
535 case BO_EQ:
536 return PGOHash::BinaryOperatorEQ;
537 case BO_NE:
538 return PGOHash::BinaryOperatorNE;
539 }
540 }
541 break;
542 }
543 }
544
545 if (HashVersion >= PGO_HASH_V2) {
546 switch (S->getStmtClass()) {
547 default:
548 break;
549 case Stmt::GotoStmtClass:
550 return PGOHash::GotoStmt;
551 case Stmt::IndirectGotoStmtClass:
552 return PGOHash::IndirectGotoStmt;
553 case Stmt::BreakStmtClass:
554 return PGOHash::BreakStmt;
555 case Stmt::ContinueStmtClass:
556 return PGOHash::ContinueStmt;
557 case Stmt::ReturnStmtClass:
558 return PGOHash::ReturnStmt;
559 case Stmt::CXXThrowExprClass:
560 return PGOHash::ThrowExpr;
561 case Stmt::UnaryOperatorClass: {
562 const UnaryOperator *UO = cast<UnaryOperator>(S);
563 if (UO->getOpcode() == UO_LNot)
564 return PGOHash::UnaryOperatorLNot;
565 break;
566 }
567 }
568 }
569
570 return PGOHash::None;
571 }
572};
573
574/// A StmtVisitor that propagates the raw counts through the AST and
575/// records the count at statements where the value may change.
576struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
577 /// PGO state.
578 CodeGenPGO &PGO;
579
580 /// A flag that is set when the current count should be recorded on the
581 /// next statement, such as at the exit of a loop.
582 bool RecordNextStmtCount;
583
584 /// The count at the current location in the traversal.
585 uint64_t CurrentCount;
586
587 /// The map of statements to count values.
588 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
589
590 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
591 struct BreakContinue {
592 uint64_t BreakCount = 0;
593 uint64_t ContinueCount = 0;
594 BreakContinue() = default;
595 };
596 SmallVector<BreakContinue, 8> BreakContinueStack;
597
598 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
599 CodeGenPGO &PGO)
600 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
601
602 void RecordStmtCount(const Stmt *S) {
603 if (RecordNextStmtCount) {
604 CountMap[S] = CurrentCount;
605 RecordNextStmtCount = false;
606 }
607 }
608
609 /// Set and return the current count.
610 uint64_t setCount(uint64_t Count) {
611 CurrentCount = Count;
612 return Count;
613 }
614
615 void VisitStmt(const Stmt *S) {
616 RecordStmtCount(S);
617 for (const Stmt *Child : S->children())
618 if (Child)
619 this->Visit(Child);
620 }
621
622 void VisitFunctionDecl(const FunctionDecl *D) {
623 // Counter tracks entry to the function body.
624 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
625 CountMap[D->getBody()] = BodyCount;
626 Visit(D->getBody());
627 }
628
629 // Skip lambda expressions. We visit these as FunctionDecls when we're
630 // generating them and aren't interested in the body when generating a
631 // parent context.
632 void VisitLambdaExpr(const LambdaExpr *LE) {}
633
634 void VisitCapturedDecl(const CapturedDecl *D) {
635 // Counter tracks entry to the capture body.
636 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
637 CountMap[D->getBody()] = BodyCount;
638 Visit(D->getBody());
639 }
640
641 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
642 // Counter tracks entry to the method body.
643 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
644 CountMap[D->getBody()] = BodyCount;
645 Visit(D->getBody());
646 }
647
648 void VisitBlockDecl(const BlockDecl *D) {
649 // Counter tracks entry to the block body.
650 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
651 CountMap[D->getBody()] = BodyCount;
652 Visit(D->getBody());
653 }
654
655 void VisitReturnStmt(const ReturnStmt *S) {
656 RecordStmtCount(S);
657 if (S->getRetValue())
658 Visit(S->getRetValue());
659 CurrentCount = 0;
660 RecordNextStmtCount = true;
661 }
662
663 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
664 RecordStmtCount(E);
665 if (E->getSubExpr())
666 Visit(E->getSubExpr());
667 CurrentCount = 0;
668 RecordNextStmtCount = true;
669 }
670
671 void VisitGotoStmt(const GotoStmt *S) {
672 RecordStmtCount(S);
673 CurrentCount = 0;
674 RecordNextStmtCount = true;
675 }
676
677 void VisitLabelStmt(const LabelStmt *S) {
678 RecordNextStmtCount = false;
679 // Counter tracks the block following the label.
680 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
681 CountMap[S] = BlockCount;
682 Visit(S->getSubStmt());
683 }
684
685 void VisitBreakStmt(const BreakStmt *S) {
686 RecordStmtCount(S);
687 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
688 BreakContinueStack.back().BreakCount += CurrentCount;
689 CurrentCount = 0;
690 RecordNextStmtCount = true;
691 }
692
693 void VisitContinueStmt(const ContinueStmt *S) {
694 RecordStmtCount(S);
695 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
696 BreakContinueStack.back().ContinueCount += CurrentCount;
697 CurrentCount = 0;
698 RecordNextStmtCount = true;
699 }
700
701 void VisitWhileStmt(const WhileStmt *S) {
702 RecordStmtCount(S);
703 uint64_t ParentCount = CurrentCount;
704
705 BreakContinueStack.push_back(BreakContinue());
706 // Visit the body region first so the break/continue adjustments can be
707 // included when visiting the condition.
708 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
709 CountMap[S->getBody()] = CurrentCount;
710 Visit(S->getBody());
711 uint64_t BackedgeCount = CurrentCount;
712
713 // ...then go back and propagate counts through the condition. The count
714 // at the start of the condition is the sum of the incoming edges,
715 // the backedge from the end of the loop body, and the edges from
716 // continue statements.
717 BreakContinue BC = BreakContinueStack.pop_back_val();
718 uint64_t CondCount =
719 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
720 CountMap[S->getCond()] = CondCount;
721 Visit(S->getCond());
722 setCount(BC.BreakCount + CondCount - BodyCount);
723 RecordNextStmtCount = true;
724 }
725
726 void VisitDoStmt(const DoStmt *S) {
727 RecordStmtCount(S);
728 uint64_t LoopCount = PGO.getRegionCount(S);
729
730 BreakContinueStack.push_back(BreakContinue());
731 // The count doesn't include the fallthrough from the parent scope. Add it.
732 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
733 CountMap[S->getBody()] = BodyCount;
734 Visit(S->getBody());
735 uint64_t BackedgeCount = CurrentCount;
736
737 BreakContinue BC = BreakContinueStack.pop_back_val();
738 // The count at the start of the condition is equal to the count at the
739 // end of the body, plus any continues.
740 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
741 CountMap[S->getCond()] = CondCount;
742 Visit(S->getCond());
743 setCount(BC.BreakCount + CondCount - LoopCount);
744 RecordNextStmtCount = true;
745 }
746
747 void VisitForStmt(const ForStmt *S) {
748 RecordStmtCount(S);
749 if (S->getInit())
750 Visit(S->getInit());
751
752 uint64_t ParentCount = CurrentCount;
753
754 BreakContinueStack.push_back(BreakContinue());
755 // Visit the body region first. (This is basically the same as a while
756 // loop; see further comments in VisitWhileStmt.)
757 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
758 CountMap[S->getBody()] = BodyCount;
759 Visit(S->getBody());
760 uint64_t BackedgeCount = CurrentCount;
761 BreakContinue BC = BreakContinueStack.pop_back_val();
762
763 // The increment is essentially part of the body but it needs to include
764 // the count for all the continue statements.
765 if (S->getInc()) {
766 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
767 CountMap[S->getInc()] = IncCount;
768 Visit(S->getInc());
769 }
770
771 // ...then go back and propagate counts through the condition.
772 uint64_t CondCount =
773 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
774 if (S->getCond()) {
775 CountMap[S->getCond()] = CondCount;
776 Visit(S->getCond());
777 }
778 setCount(BC.BreakCount + CondCount - BodyCount);
779 RecordNextStmtCount = true;
780 }
781
782 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
783 RecordStmtCount(S);
784 if (S->getInit())
785 Visit(S->getInit());
786 Visit(S->getLoopVarStmt());
787 Visit(S->getRangeStmt());
788 Visit(S->getBeginStmt());
789 Visit(S->getEndStmt());
790
791 uint64_t ParentCount = CurrentCount;
792 BreakContinueStack.push_back(BreakContinue());
793 // Visit the body region first. (This is basically the same as a while
794 // loop; see further comments in VisitWhileStmt.)
795 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
796 CountMap[S->getBody()] = BodyCount;
797 Visit(S->getBody());
798 uint64_t BackedgeCount = CurrentCount;
799 BreakContinue BC = BreakContinueStack.pop_back_val();
800
801 // The increment is essentially part of the body but it needs to include
802 // the count for all the continue statements.
803 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
804 CountMap[S->getInc()] = IncCount;
805 Visit(S->getInc());
806
807 // ...then go back and propagate counts through the condition.
808 uint64_t CondCount =
809 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
810 CountMap[S->getCond()] = CondCount;
811 Visit(S->getCond());
812 setCount(BC.BreakCount + CondCount - BodyCount);
813 RecordNextStmtCount = true;
814 }
815
816 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
817 RecordStmtCount(S);
818 Visit(S->getElement());
819 uint64_t ParentCount = CurrentCount;
820 BreakContinueStack.push_back(BreakContinue());
821 // Counter tracks the body of the loop.
822 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
823 CountMap[S->getBody()] = BodyCount;
824 Visit(S->getBody());
825 uint64_t BackedgeCount = CurrentCount;
826 BreakContinue BC = BreakContinueStack.pop_back_val();
827
828 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
829 BodyCount);
830 RecordNextStmtCount = true;
831 }
832
833 void VisitSwitchStmt(const SwitchStmt *S) {
834 RecordStmtCount(S);
835 if (S->getInit())
836 Visit(S->getInit());
837 Visit(S->getCond());
838 CurrentCount = 0;
839 BreakContinueStack.push_back(BreakContinue());
840 Visit(S->getBody());
841 // If the switch is inside a loop, add the continue counts.
842 BreakContinue BC = BreakContinueStack.pop_back_val();
843 if (!BreakContinueStack.empty())
844 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
845 // Counter tracks the exit block of the switch.
846 setCount(PGO.getRegionCount(S));
847 RecordNextStmtCount = true;
848 }
849
850 void VisitSwitchCase(const SwitchCase *S) {
851 RecordNextStmtCount = false;
852 // Counter for this particular case. This counts only jumps from the
853 // switch header and does not include fallthrough from the case before
854 // this one.
855 uint64_t CaseCount = PGO.getRegionCount(S);
856 setCount(CurrentCount + CaseCount);
857 // We need the count without fallthrough in the mapping, so it's more useful
858 // for branch probabilities.
859 CountMap[S] = CaseCount;
860 RecordNextStmtCount = true;
861 Visit(S->getSubStmt());
862 }
863
864 void VisitIfStmt(const IfStmt *S) {
865 RecordStmtCount(S);
866
867 if (S->isConsteval()) {
868 const Stmt *Stm = S->isNegatedConsteval() ? S->getThen() : S->getElse();
869 if (Stm)
870 Visit(Stm);
871 return;
872 }
873
874 uint64_t ParentCount = CurrentCount;
875 if (S->getInit())
876 Visit(S->getInit());
877 Visit(S->getCond());
878
879 // Counter tracks the "then" part of an if statement. The count for
880 // the "else" part, if it exists, will be calculated from this counter.
881 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
882 CountMap[S->getThen()] = ThenCount;
883 Visit(S->getThen());
884 uint64_t OutCount = CurrentCount;
885
886 uint64_t ElseCount = ParentCount - ThenCount;
887 if (S->getElse()) {
888 setCount(ElseCount);
889 CountMap[S->getElse()] = ElseCount;
890 Visit(S->getElse());
891 OutCount += CurrentCount;
892 } else
893 OutCount += ElseCount;
894 setCount(OutCount);
895 RecordNextStmtCount = true;
896 }
897
898 void VisitCXXTryStmt(const CXXTryStmt *S) {
899 RecordStmtCount(S);
900 Visit(S->getTryBlock());
901 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
902 Visit(S->getHandler(I));
903 // Counter tracks the continuation block of the try statement.
904 setCount(PGO.getRegionCount(S));
905 RecordNextStmtCount = true;
906 }
907
908 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
909 RecordNextStmtCount = false;
910 // Counter tracks the catch statement's handler block.
911 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
912 CountMap[S] = CatchCount;
913 Visit(S->getHandlerBlock());
914 }
915
916 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
917 RecordStmtCount(E);
918 uint64_t ParentCount = CurrentCount;
919 Visit(E->getCond());
920
921 // Counter tracks the "true" part of a conditional operator. The
922 // count in the "false" part will be calculated from this counter.
923 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
924 CountMap[E->getTrueExpr()] = TrueCount;
925 Visit(E->getTrueExpr());
926 uint64_t OutCount = CurrentCount;
927
928 uint64_t FalseCount = setCount(ParentCount - TrueCount);
929 CountMap[E->getFalseExpr()] = FalseCount;
930 Visit(E->getFalseExpr());
931 OutCount += CurrentCount;
932
933 setCount(OutCount);
934 RecordNextStmtCount = true;
935 }
936
937 void VisitBinLAnd(const BinaryOperator *E) {
938 RecordStmtCount(E);
939 uint64_t ParentCount = CurrentCount;
940 Visit(E->getLHS());
941 // Counter tracks the right hand side of a logical and operator.
942 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
943 CountMap[E->getRHS()] = RHSCount;
944 Visit(E->getRHS());
945 setCount(ParentCount + RHSCount - CurrentCount);
946 RecordNextStmtCount = true;
947 }
948
949 void VisitBinLOr(const BinaryOperator *E) {
950 RecordStmtCount(E);
951 uint64_t ParentCount = CurrentCount;
952 Visit(E->getLHS());
953 // Counter tracks the right hand side of a logical or operator.
954 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
955 CountMap[E->getRHS()] = RHSCount;
956 Visit(E->getRHS());
957 setCount(ParentCount + RHSCount - CurrentCount);
958 RecordNextStmtCount = true;
959 }
960};
961} // end anonymous namespace
962
963void PGOHash::combine(HashType Type) {
964 // Check that we never combine 0 and only have six bits.
965 assert(Type && "Hash is invalid: unexpected type 0");
966 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
967
968 // Pass through MD5 if enough work has built up.
969 if (Count && Count % NumTypesPerWord == 0) {
970 using namespace llvm::support;
971 uint64_t Swapped =
972 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
973 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
974 Working = 0;
975 }
976
977 // Accumulate the current type.
978 ++Count;
979 Working = Working << NumBitsPerType | Type;
980}
981
982uint64_t PGOHash::finalize() {
983 // Use Working as the hash directly if we never used MD5.
984 if (Count <= NumTypesPerWord)
985 // No need to byte swap here, since none of the math was endian-dependent.
986 // This number will be byte-swapped as required on endianness transitions,
987 // so we will see the same value on the other side.
988 return Working;
989
990 // Check for remaining work in Working.
991 if (Working) {
992 // Keep the buggy behavior from v1 and v2 for backward-compatibility. This
993 // is buggy because it converts a uint64_t into an array of uint8_t.
994 if (HashVersion < PGO_HASH_V3) {
995 MD5.update({(uint8_t)Working});
996 } else {
997 using namespace llvm::support;
998 uint64_t Swapped =
999 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
1000 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
1001 }
1002 }
1003
1004 // Finalize the MD5 and return the hash.
1005 llvm::MD5::MD5Result Result;
1006 MD5.final(Result);
1007 return Result.low();
1008}
1009
1010void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
1011 const Decl *D = GD.getDecl();
1012 if (!D->hasBody())
1013 return;
1014
1015 // Skip CUDA/HIP kernel launch stub functions.
1016 if (CGM.getLangOpts().CUDA && !CGM.getLangOpts().CUDAIsDevice &&
1017 D->hasAttr<CUDAGlobalAttr>())
1018 return;
1019
1020 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1021 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1022 if (!InstrumentRegions && !PGOReader)
1023 return;
1024 if (D->isImplicit())
1025 return;
1026 // Constructors and destructors may be represented by several functions in IR.
1027 // If so, instrument only base variant, others are implemented by delegation
1028 // to the base one, it would be counted twice otherwise.
1029 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1030 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
1031 if (GD.getCtorType() != Ctor_Base &&
1033 return;
1034 }
1036 return;
1037
1038 CGM.ClearUnusedCoverageMapping(D);
1039 if (Fn->hasFnAttribute(llvm::Attribute::NoProfile))
1040 return;
1041 if (Fn->hasFnAttribute(llvm::Attribute::SkipProfile))
1042 return;
1043
1044 SourceManager &SM = CGM.getContext().getSourceManager();
1046 SM.isInSystemHeader(D->getLocation()))
1047 return;
1048
1049 setFuncName(Fn);
1050
1051 mapRegionCounters(D);
1052 if (CGM.getCodeGenOpts().CoverageMapping)
1053 emitCounterRegionMapping(D);
1054 if (PGOReader) {
1055 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
1056 computeRegionCounts(D);
1057 applyFunctionAttributes(PGOReader, Fn);
1058 }
1059}
1060
1061void CodeGenPGO::mapRegionCounters(const Decl *D) {
1062 // Use the latest hash version when inserting instrumentation, but use the
1063 // version in the indexed profile if we're reading PGO data.
1064 PGOHashVersion HashVersion = PGO_HASH_LATEST;
1065 uint64_t ProfileVersion = llvm::IndexedInstrProf::Version;
1066 if (auto *PGOReader = CGM.getPGOReader()) {
1067 HashVersion = getPGOHashVersion(PGOReader, CGM);
1068 ProfileVersion = PGOReader->getVersion();
1069 }
1070
1071 // If MC/DC is enabled, set the MaxConditions to a preset value. Otherwise,
1072 // set it to zero. This value impacts the number of conditions accepted in a
1073 // given boolean expression, which impacts the size of the bitmap used to
1074 // track test vector execution for that boolean expression. Because the
1075 // bitmap scales exponentially (2^n) based on the number of conditions seen,
1076 // the maximum value is hard-coded at 6 conditions, which is more than enough
1077 // for most embedded applications. Setting a maximum value prevents the
1078 // bitmap footprint from growing too large without the user's knowledge. In
1079 // the future, this value could be adjusted with a command-line option.
1080 unsigned MCDCMaxConditions =
1081 (CGM.getCodeGenOpts().MCDCCoverage ? CGM.getCodeGenOpts().MCDCMaxConds
1082 : 0);
1083
1084 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, CounterPair>);
1085 RegionMCDCState.reset(new MCDC::State);
1086 MapRegionCounters Walker(HashVersion, ProfileVersion, *RegionCounterMap,
1087 *RegionMCDCState, MCDCMaxConditions, CGM.getDiags());
1088 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1089 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
1090 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1091 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
1092 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1093 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
1094 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1095 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
1096 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
1097 NumRegionCounters = Walker.NextCounter;
1098 FunctionHash = Walker.Hash.finalize();
1099 if (HashVersion >= PGO_HASH_V4)
1100 FunctionHash &= llvm::NamedInstrProfRecord::FUNC_HASH_MASK;
1101}
1102
1103bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
1104 if (!D->getBody())
1105 return true;
1106
1107 // Skip host-only functions in the CUDA device compilation and device-only
1108 // functions in the host compilation. Just roughly filter them out based on
1109 // the function attributes. If there are effectively host-only or device-only
1110 // ones, their coverage mapping may still be generated.
1111 if (CGM.getLangOpts().CUDA &&
1112 ((CGM.getLangOpts().CUDAIsDevice && !D->hasAttr<CUDADeviceAttr>() &&
1113 !D->hasAttr<CUDAGlobalAttr>()) ||
1114 (!CGM.getLangOpts().CUDAIsDevice &&
1115 (D->hasAttr<CUDAGlobalAttr>() ||
1116 (!D->hasAttr<CUDAHostAttr>() && D->hasAttr<CUDADeviceAttr>())))))
1117 return true;
1118
1119 // Don't map the functions in system headers.
1120 const auto &SM = CGM.getContext().getSourceManager();
1121 auto Loc = D->getBody()->getBeginLoc();
1122 return !llvm::coverage::SystemHeadersCoverage && SM.isInSystemHeader(Loc);
1123}
1124
1125void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
1126 if (skipRegionMappingForDecl(D))
1127 return;
1128
1129 std::string CoverageMapping;
1130 llvm::raw_string_ostream OS(CoverageMapping);
1131 RegionMCDCState->BranchByStmt.clear();
1132 CoverageMappingGen MappingGen(
1133 *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
1134 CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCState.get());
1135 MappingGen.emitCounterMapping(D, OS);
1136
1137 if (CoverageMapping.empty())
1138 return;
1139
1140 // Scan max(FalseCnt) and update NumRegionCounters.
1141 unsigned MaxNumCounters = NumRegionCounters;
1142 for (const auto &[_, V] : *RegionCounterMap) {
1143 assert((!V.Executed.hasValue() || MaxNumCounters > V.Executed) &&
1144 "TrueCnt should not be reassigned");
1145 if (V.Skipped.hasValue())
1146 MaxNumCounters = std::max(MaxNumCounters, V.Skipped + 1);
1147 }
1148 NumRegionCounters = MaxNumCounters;
1149
1150 CGM.getCoverageMapping()->addFunctionMappingRecord(
1151 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
1152}
1153
1154void
1156 llvm::GlobalValue::LinkageTypes Linkage) {
1157 if (skipRegionMappingForDecl(D))
1158 return;
1159
1160 std::string CoverageMapping;
1161 llvm::raw_string_ostream OS(CoverageMapping);
1162 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
1163 CGM.getContext().getSourceManager(),
1164 CGM.getLangOpts());
1165 MappingGen.emitEmptyMapping(D, OS);
1166
1167 if (CoverageMapping.empty())
1168 return;
1169
1170 setFuncName(Name, Linkage);
1171 CGM.getCoverageMapping()->addFunctionMappingRecord(
1172 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
1173}
1174
1175void CodeGenPGO::computeRegionCounts(const Decl *D) {
1176 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
1177 ComputeRegionCounts Walker(*StmtCountMap, *this);
1178 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1179 Walker.VisitFunctionDecl(FD);
1180 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1181 Walker.VisitObjCMethodDecl(MD);
1182 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1183 Walker.VisitBlockDecl(BD);
1184 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1185 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
1186}
1187
1188void
1189CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
1190 llvm::Function *Fn) {
1191 if (!haveRegionCounts())
1192 return;
1193
1194 uint64_t FunctionCount = getRegionCount(nullptr);
1195 Fn->setEntryCount(FunctionCount);
1196}
1197
1198std::pair<bool, bool> CodeGenPGO::getIsCounterPair(const Stmt *S) const {
1199 if (!RegionCounterMap)
1200 return {false, false};
1201
1202 auto I = RegionCounterMap->find(S);
1203 if (I == RegionCounterMap->end())
1204 return {false, false};
1205
1206 return {I->second.Executed.hasValue(), I->second.Skipped.hasValue()};
1207}
1208
1210 bool UseSkipPath, bool UseBoth,
1211 llvm::Value *StepV) {
1212 if (!RegionCounterMap)
1213 return;
1214
1215 // Allocate S in the Map regardless of emission.
1216 const auto &TheCounterPair = (*RegionCounterMap)[S];
1217
1218 if (!Builder.GetInsertBlock())
1219 return;
1220
1221 const CounterPair::ValueOpt &Counter =
1222 (UseSkipPath ? TheCounterPair.Skipped : TheCounterPair.Executed);
1223 if (!Counter.hasValue())
1224 return;
1225
1226 // Make sure that pointer to global is passed in with zero addrspace
1227 // This is relevant during GPU profiling
1228 auto *NormalizedFuncNameVarPtr =
1229 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1230 FuncNameVar, llvm::PointerType::get(CGM.getLLVMContext(), 0));
1231
1232 llvm::Value *Args[] = {
1233 NormalizedFuncNameVarPtr, Builder.getInt64(FunctionHash),
1234 Builder.getInt32(NumRegionCounters), Builder.getInt32(Counter), StepV};
1235
1237 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_cover),
1238 ArrayRef(Args, 4));
1239 else if (!StepV)
1240 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
1241 ArrayRef(Args, 4));
1242 else
1243 Builder.CreateCall(
1244 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step), Args);
1245}
1246
1247bool CodeGenPGO::canEmitMCDCCoverage(const CGBuilderTy &Builder) {
1248 return (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1249 CGM.getCodeGenOpts().MCDCCoverage && Builder.GetInsertBlock());
1250}
1251
1253 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1254 return;
1255
1256 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1257
1258 // Emit intrinsic representing MCDC bitmap parameters at function entry.
1259 // This is used by the instrumentation pass, but it isn't actually lowered to
1260 // anything.
1261 llvm::Value *Args[3] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1262 Builder.getInt64(FunctionHash),
1263 Builder.getInt32(RegionMCDCState->BitmapBits)};
1264 Builder.CreateCall(
1265 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_parameters), Args);
1266}
1267
1268/// Fill mcdc.addr order by ID.
1269std::vector<Address *>
1271 std::vector<Address *> Result;
1272
1273 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1274 return Result;
1275
1277 for (auto &[_, V] : RegionMCDCState->DecisionByStmt)
1278 if (V.isValid())
1279 SortedPair.emplace_back(V.ID, &V.MCDCCondBitmapAddr);
1280
1281 llvm::sort(SortedPair);
1282
1283 for (auto &[_, MCDCCondBitmapAddr] : SortedPair)
1284 Result.push_back(MCDCCondBitmapAddr);
1285
1286 return Result;
1287}
1288
1290 const Expr *S,
1291 CodeGenFunction &CGF) {
1292 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1293 return;
1294
1295 S = S->IgnoreParens();
1296
1297 auto DecisionStateIter = RegionMCDCState->DecisionByStmt.find(S);
1298 if (DecisionStateIter == RegionMCDCState->DecisionByStmt.end())
1299 return;
1300
1301 auto &MCDCCondBitmapAddr = DecisionStateIter->second.MCDCCondBitmapAddr;
1302 if (!MCDCCondBitmapAddr.isValid())
1303 return;
1304
1305 // Don't create tvbitmap_update if the record is allocated but excluded.
1306 // Or `bitmap |= (1 << 0)` would be wrongly executed to the next bitmap.
1307 if (DecisionStateIter->second.Indices.size() == 0)
1308 return;
1309
1310 // Extract the offset of the global bitmap associated with this expression.
1311 unsigned MCDCTestVectorBitmapOffset = DecisionStateIter->second.BitmapIdx;
1312 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1313
1314 // Emit intrinsic responsible for updating the global bitmap corresponding to
1315 // a boolean expression. The index being set is based on the value loaded
1316 // from a pointer to a dedicated temporary value on the stack that is itself
1317 // updated via emitMCDCCondBitmapReset() and emitMCDCCondBitmapUpdate(). The
1318 // index represents an executed test vector.
1319 llvm::Value *Args[4] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1320 Builder.getInt64(FunctionHash),
1321 Builder.getInt32(MCDCTestVectorBitmapOffset),
1322 MCDCCondBitmapAddr.emitRawPointer(CGF)};
1323 Builder.CreateCall(
1324 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_tvbitmap_update), Args);
1325}
1326
1328 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1329 return;
1330
1331 auto I = RegionMCDCState->DecisionByStmt.find(S->IgnoreParens());
1332 if (I == RegionMCDCState->DecisionByStmt.end())
1333 return;
1334
1335 auto &MCDCCondBitmapAddr = I->second.MCDCCondBitmapAddr;
1336 if (!MCDCCondBitmapAddr.isValid())
1337 return;
1338
1339 // Emit intrinsic that resets a dedicated temporary value on the stack to 0.
1340 Builder.CreateStore(Builder.getInt32(0), MCDCCondBitmapAddr);
1341}
1342
1344 llvm::Value *Val,
1345 CodeGenFunction &CGF) {
1346 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1347 return;
1348
1349 // Even though, for simplicity, parentheses and unary logical-NOT operators
1350 // are considered part of their underlying condition for both MC/DC and
1351 // branch coverage, the condition IDs themselves are assigned and tracked
1352 // using the underlying condition itself. This is done solely for
1353 // consistency since parentheses and logical-NOTs are ignored when checking
1354 // whether the condition is actually an instrumentable condition. This can
1355 // also make debugging a bit easier.
1357
1358 auto BranchStateIter = RegionMCDCState->BranchByStmt.find(S);
1359 if (BranchStateIter == RegionMCDCState->BranchByStmt.end())
1360 return;
1361
1362 // Extract the ID of the condition we are setting in the bitmap.
1363 const auto &Branch = BranchStateIter->second;
1364 assert(Branch.ID >= 0 && "Condition has no ID!");
1365 assert(Branch.DecisionStmt);
1366
1367 // Cancel the emission if the Decision is erased after the allocation.
1368 const auto DecisionIter =
1369 RegionMCDCState->DecisionByStmt.find(Branch.DecisionStmt);
1370 if (DecisionIter == RegionMCDCState->DecisionByStmt.end())
1371 return;
1372
1373 auto &MCDCCondBitmapAddr = DecisionIter->second.MCDCCondBitmapAddr;
1374 if (!MCDCCondBitmapAddr.isValid())
1375 return;
1376
1377 const auto &TVIdxs = DecisionIter->second.Indices[Branch.ID];
1378
1379 auto *CurTV = Builder.CreateLoad(MCDCCondBitmapAddr,
1380 "mcdc." + Twine(Branch.ID + 1) + ".cur");
1381 auto *NewTV = Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[true]));
1382 NewTV = Builder.CreateSelect(
1383 Val, NewTV, Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[false])));
1384 Builder.CreateStore(NewTV, MCDCCondBitmapAddr);
1385}
1386
1388 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1389 M.addModuleFlag(llvm::Module::Warning, "EnableValueProfiling",
1390 uint32_t(EnableValueProfiling));
1391}
1392
1393void CodeGenPGO::setProfileVersion(llvm::Module &M) {
1394 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1396 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1397 llvm::Type *IntTy64 = llvm::Type::getInt64Ty(M.getContext());
1398 uint64_t ProfileVersion =
1399 (INSTR_PROF_RAW_VERSION | VARIANT_MASK_BYTE_COVERAGE);
1400
1401 auto IRLevelVersionVariable = new llvm::GlobalVariable(
1402 M, IntTy64, true, llvm::GlobalValue::WeakAnyLinkage,
1403 llvm::Constant::getIntegerValue(IntTy64,
1404 llvm::APInt(64, ProfileVersion)),
1405 VarName);
1406
1407 IRLevelVersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1408 llvm::Triple TT(M.getTargetTriple());
1409 if (TT.isGPU())
1410 IRLevelVersionVariable->setVisibility(
1411 llvm::GlobalValue::ProtectedVisibility);
1412 if (TT.supportsCOMDAT()) {
1413 IRLevelVersionVariable->setLinkage(llvm::GlobalValue::ExternalLinkage);
1414 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1415 }
1416 IRLevelVersionVariable->setDSOLocal(true);
1417 }
1418}
1419
1420// This method either inserts a call to the profile run-time during
1421// instrumentation or puts profile data into metadata for PGO use.
1422void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
1423 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
1424
1426 return;
1427
1428 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
1429 return;
1430
1431 if (isa<llvm::Constant>(ValuePtr))
1432 return;
1433
1434 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
1435 if (InstrumentValueSites && RegionCounterMap) {
1436 auto BuilderInsertPoint = Builder.saveIP();
1437 Builder.SetInsertPoint(ValueSite);
1438 llvm::Value *Args[5] = {
1439 FuncNameVar,
1440 Builder.getInt64(FunctionHash),
1441 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
1442 Builder.getInt32(ValueKind),
1443 Builder.getInt32(NumValueSites[ValueKind]++)
1444 };
1445 Builder.CreateCall(
1446 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
1447 Builder.restoreIP(BuilderInsertPoint);
1448 return;
1449 }
1450
1451 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1452 if (PGOReader && haveRegionCounts()) {
1453 // We record the top most called three functions at each call site.
1454 // Profile metadata contains "VP" string identifying this metadata
1455 // as value profiling data, then a uint32_t value for the value profiling
1456 // kind, a uint64_t value for the total number of times the call is
1457 // executed, followed by the function hash and execution count (uint64_t)
1458 // pairs for each function.
1459 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
1460 return;
1461
1462 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
1463 (llvm::InstrProfValueKind)ValueKind,
1464 NumValueSites[ValueKind]);
1465
1466 NumValueSites[ValueKind]++;
1467 }
1468}
1469
1470void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
1471 bool IsInMainFile) {
1472 CGM.getPGOStats().addVisited(IsInMainFile);
1473 RegionCounts.clear();
1474 auto RecordExpected = PGOReader->getInstrProfRecord(FuncName, FunctionHash);
1475 if (auto E = RecordExpected.takeError()) {
1476 auto IPE = std::get<0>(llvm::InstrProfError::take(std::move(E)));
1477 if (IPE == llvm::instrprof_error::unknown_function)
1478 CGM.getPGOStats().addMissing(IsInMainFile);
1479 else if (IPE == llvm::instrprof_error::hash_mismatch)
1480 CGM.getPGOStats().addMismatched(IsInMainFile);
1481 else if (IPE == llvm::instrprof_error::malformed)
1482 // TODO: Consider a more specific warning for this case.
1483 CGM.getPGOStats().addMismatched(IsInMainFile);
1484 return;
1485 }
1486 ProfRecord =
1487 std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
1488 RegionCounts = ProfRecord->Counts;
1489}
1490
1491/// Calculate what to divide by to scale weights.
1492///
1493/// Given the maximum weight, calculate a divisor that will scale all the
1494/// weights to strictly less than UINT32_MAX.
1495static uint64_t calculateWeightScale(uint64_t MaxWeight) {
1496 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
1497}
1498
1499/// Scale an individual branch weight (and add 1).
1500///
1501/// Scale a 64-bit weight down to 32-bits using \c Scale.
1502///
1503/// According to Laplace's Rule of Succession, it is better to compute the
1504/// weight based on the count plus 1, so universally add 1 to the value.
1505///
1506/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1507/// greater than \c Weight.
1508static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1509 assert(Scale && "scale by 0?");
1510 uint64_t Scaled = Weight / Scale + 1;
1511 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1512 return Scaled;
1513}
1514
1515llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1516 uint64_t FalseCount) const {
1517 // Check for empty weights.
1518 if (!TrueCount && !FalseCount)
1519 return nullptr;
1520
1521 // Calculate how to scale down to 32-bits.
1522 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1523
1524 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1525 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1526 scaleBranchWeight(FalseCount, Scale));
1527}
1528
1529llvm::MDNode *
1530CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) const {
1531 // We need at least two elements to create meaningful weights.
1532 if (Weights.size() < 2)
1533 return nullptr;
1534
1535 // Check for empty weights.
1536 uint64_t MaxWeight = *llvm::max_element(Weights);
1537 if (MaxWeight == 0)
1538 return nullptr;
1539
1540 // Calculate how to scale down to 32-bits.
1541 uint64_t Scale = calculateWeightScale(MaxWeight);
1542
1543 SmallVector<uint32_t, 16> ScaledWeights;
1544 ScaledWeights.reserve(Weights.size());
1545 for (uint64_t W : Weights)
1546 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1547
1548 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1549 return MDHelper.createBranchWeights(ScaledWeights);
1550}
1551
1552llvm::MDNode *
1553CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1554 uint64_t LoopCount) const {
1555 if (!PGO->haveRegionCounts())
1556 return nullptr;
1557 std::optional<uint64_t> CondCount = PGO->getStmtCount(Cond);
1558 if (!CondCount || *CondCount == 0)
1559 return nullptr;
1560 return createProfileWeights(LoopCount,
1561 std::max(*CondCount, LoopCount) - LoopCount);
1562}
1563
1565 const Stmt *S, bool UseBoth,
1566 llvm::Value *StepV) {
1567 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1568 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1569 !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile)) {
1570 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1571 PGO->emitCounterSetOrIncrement(Builder, S, (ExecSkip == UseSkipPath),
1572 UseBoth, StepV);
1573 }
1574 PGO->setCurrentStmt(S);
1575}
1576
1577std::pair<bool, bool> CodeGenFunction::getIsCounterPair(const Stmt *S) const {
1578 return PGO->getIsCounterPair(S);
1579}
1580void CodeGenFunction::markStmtAsUsed(bool Skipped, const Stmt *S) {
1581 PGO->markStmtAsUsed(Skipped, S);
1582}
1584 PGO->markStmtMaybeUsed(S);
1585}
1586
1588 if (isMCDCCoverageEnabled()) {
1589 PGO->emitMCDCParameters(Builder);
1590
1591 // Set up MCDCCondBitmapAddr for each Decision.
1592 // Note: This doesn't initialize Addrs in invalidated Decisions.
1593 for (auto *MCDCCondBitmapAddr : PGO->getMCDCCondBitmapAddrArray(Builder))
1594 *MCDCCondBitmapAddr =
1595 CreateIRTemp(getContext().UnsignedIntTy, "mcdc.addr");
1596 }
1597}
1599 return PGO->isMCDCDecisionExpr(E);
1600}
1602 return PGO->isMCDCBranchExpr(E);
1603}
1606 PGO->emitMCDCCondBitmapReset(Builder, E);
1607 PGO->setCurrentStmt(E);
1608 }
1609}
1612 PGO->emitMCDCTestVectorBitmapUpdate(Builder, E, *this);
1613 PGO->setCurrentStmt(E);
1614 }
1615}
1616
1618 llvm::Value *Val) {
1619 if (isMCDCCoverageEnabled()) {
1620 PGO->emitMCDCCondBitmapUpdate(Builder, E, Val, *this);
1621 PGO->setCurrentStmt(E);
1622 }
1623}
1624
1626 return PGO->getStmtCount(S).value_or(0);
1627}
1628
1629/// Set the profiler's current count.
1631 PGO->setCurrentRegionCount(Count);
1632}
1633
1634/// Get the profiler's current count. This is generally the count for the most
1635/// recently incremented counter.
1637 return PGO->getCurrentRegionCount();
1638}
#define V(N, I)
llvm::ImmutableMap< CountKey, unsigned > CountMap
#define DEFINE_NESTABLE_TRAVERSAL(N)
static llvm::cl::opt< bool > EnableValueProfiling("enable-value-profiling", llvm::cl::desc("Enable value profiling"), llvm::cl::Hidden, llvm::cl::init(false))
PGOHashVersion
The version of the PGO hash algorithm.
@ PGO_HASH_LATEST
@ PGO_HASH_V1
@ PGO_HASH_V4
@ PGO_HASH_V3
@ PGO_HASH_V2
static uint64_t calculateWeightScale(uint64_t MaxWeight)
Calculate what to divide by to scale weights.
static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale)
Scale an individual branch weight (and add 1).
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
#define SM(sm)
SourceManager & getSourceManager()
Definition ASTContext.h:851
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4531
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4537
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4543
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
Expr * getRHS() const
Definition Expr.h:4090
Opcode getOpcode() const
Definition Expr.h:4083
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4671
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.h:4750
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Stmt * getHandlerBlock() const
Definition StmtCXX.h:51
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
child_range children()
Definition StmtCXX.h:217
const Expr * getSubExpr() const
Definition ExprCXX.h:1228
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CompoundStmt * getTryBlock()
Definition StmtCXX.h:100
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4943
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.cpp:5693
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string MainFileName
The user provided name for the "main file", if non-empty.
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
bool isBinaryLogicalOp(const Expr *E) const
CounterForIncrement
Used to specify which counter in a pair shall be incremented.
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:184
void maybeUpdateMCDCTestVectorBitmap(const Expr *E)
Increment the profiler's counter for the given expression by StepV.
static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor)
Checks whether the given constructor is a valid subject for the complete-to-base constructor delegati...
Definition CGClass.cpp:720
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
void maybeResetMCDCCondBitmap(const Expr *E)
Zero-init the MCDC temp value.
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
bool isMCDCBranchExpr(const Expr *E) const
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
uint64_t getCurrentProfileCount()
Get the profiler's current count.
void markStmtMaybeUsed(const Stmt *S)
std::pair< bool, bool > getIsCounterPair(const Stmt *S) const
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void markStmtAsUsed(bool Skipped, const Stmt *S)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
bool isMCDCDecisionExpr(const Expr *E) const
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
llvm::IndexedInstrProfReader * getPGOReader() const
InstrProfStats & getPGOStats()
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
std::pair< bool, bool > getIsCounterPair(const Stmt *S) const
uint64_t getRegionCount(const Stmt *S)
Return the region count for the counter at the given index.
Definition CodeGenPGO.h:152
void setValueProfilingFlag(llvm::Module &M)
void valueProfile(CGBuilderTy &Builder, uint32_t ValueKind, llvm::Instruction *ValueSite, llvm::Value *ValuePtr)
void emitMCDCCondBitmapUpdate(CGBuilderTy &Builder, const Expr *S, llvm::Value *Val, CodeGenFunction &CGF)
void emitMCDCCondBitmapReset(CGBuilderTy &Builder, const Expr *S)
std::vector< Address * > getMCDCCondBitmapAddrArray(CGBuilderTy &Builder)
Fill mcdc.addr order by ID.
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
void emitCounterSetOrIncrement(CGBuilderTy &Builder, const Stmt *S, bool UseFalsePath, bool UseBoth, llvm::Value *StepV)
void emitMCDCTestVectorBitmapUpdate(CGBuilderTy &Builder, const Expr *S, CodeGenFunction &CGF)
void emitMCDCParameters(CGBuilderTy &Builder)
bool haveRegionCounts() const
Whether or not we have PGO region data for the current function.
Definition CodeGenPGO.h:53
Organizes the per-function state that is used while generating code coverage mapping data.
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
void addMissing(bool MainFile)
Record that a function we've visited has no profile data.
void addMismatched(bool MainFile)
Record that a function we've visited has mismatched profile data.
void addVisited(bool MainFile)
Record that we've visited a function and whether or not that function was in the main source file.
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4423
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4418
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1087
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1093
SourceLocation getLocation() const
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:577
Kind getKind() const
Definition DeclBase.h:442
Stmt * getBody()
Definition Stmt.h:2849
Expr * getCond()
Definition Stmt.h:2842
child_range children()
Definition Stmt.h:2868
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
Stmt * getInit()
Definition Stmt.h:2895
child_range children()
Definition Stmt.h:2951
Stmt * getBody()
Definition Stmt.h:2924
Expr * getInc()
Definition Stmt.h:2923
Expr * getCond()
Definition Stmt.h:2922
Represents a function declaration or definition.
Definition Decl.h:2000
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
CXXCtorType getCtorType() const
Definition GlobalDecl.h:108
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
Stmt * getThen()
Definition Stmt.h:2340
Stmt * getInit()
Definition Stmt.h:2401
Expr * getCond()
Definition Stmt.h:2328
bool isNegatedConsteval() const
Definition Stmt.h:2440
Stmt * getElse()
Definition Stmt.h:2349
bool isConsteval() const
Definition Stmt.h:2431
Stmt * getSubStmt()
Definition Stmt.h:2160
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition DeclObjC.cpp:906
Expr * getRetValue()
Definition Stmt.h:3179
This class handles loading and caching of source files into memory.
Stmt - This represents one statement.
Definition Stmt.h:86
child_range children()
Definition Stmt.cpp:299
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Stmt * getSubStmt()
Definition Stmt.h:2105
Expr * getCond()
Definition Stmt.h:2564
Stmt * getBody()
Definition Stmt.h:2576
Stmt * getInit()
Definition Stmt.h:2581
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Opcode getOpcode() const
Definition Expr.h:2280
Expr * getCond()
Definition Stmt.h:2741
child_range children()
Definition Stmt.h:2812
Stmt * getBody()
Definition Stmt.h:2753
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1282
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
Expr * Cond
};
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Type
The name was classified as a type.
Definition Sema.h:563
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
unsigned long uint64_t
cl::opt< bool > SystemHeadersCoverage
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
#define false
Definition stdbool.h:26
Per-Function MC/DC state.
Definition MCDCState.h:32
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt
Definition MCDCState.h:53