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