19#include "llvm/IR/Intrinsics.h"
20#include "llvm/IR/MDBuilder.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Endian.h"
23#include "llvm/Support/MD5.h"
30static llvm::cl::opt<bool>
32 llvm::cl::desc(
"Enable value profiling"),
33 llvm::cl::Hidden, llvm::cl::init(
false));
38void CodeGenPGO::setFuncName(StringRef Name,
39 llvm::GlobalValue::LinkageTypes
Linkage) {
40 llvm::IndexedInstrProfReader *PGOReader = CGM.
getPGOReader();
41 FuncName = llvm::getPGOFuncName(
43 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
47 FuncNameVar = llvm::createPGOFuncNameVar(CGM.
getModule(),
Linkage, FuncName);
50void CodeGenPGO::setFuncName(llvm::Function *Fn) {
51 setFuncName(
Fn->getName(),
Fn->getLinkage());
53 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
84 static const int NumBitsPerType = 6;
85 static const unsigned NumTypesPerWord =
sizeof(
uint64_t) * 8 / NumBitsPerType;
86 static const unsigned TooBig = 1u << NumBitsPerType;
96 enum HashType :
unsigned char {
103 ObjCForCollectionStmt,
113 BinaryConditionalOperator,
137 static_assert(LastHashType <= TooBig,
"Too many types in HashType");
140 : Working(0), Count(0), HashVersion(HashVersion) {}
141 void combine(HashType
Type);
145const int PGOHash::NumBitsPerType;
146const unsigned PGOHash::NumTypesPerWord;
147const unsigned PGOHash::TooBig;
150static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
152 if (PGOReader->getVersion() <= 4)
154 if (PGOReader->getVersion() <= 5)
156 if (PGOReader->getVersion() <= 12)
162struct MapRegionCounters :
public RecursiveASTVisitor<MapRegionCounters> {
163 using Base = RecursiveASTVisitor<MapRegionCounters>;
166 unsigned NextCounter;
170 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap;
172 MCDC::State &MCDCState;
174 unsigned MCDCMaxCond;
178 DiagnosticsEngine &
Diag;
180 MapRegionCounters(
PGOHashVersion HashVersion, uint64_t ProfileVersion,
181 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap,
182 MCDC::State &MCDCState,
unsigned MCDCMaxCond,
183 DiagnosticsEngine &
Diag)
184 : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap),
185 MCDCState(MCDCState), MCDCMaxCond(MCDCMaxCond),
186 ProfileVersion(ProfileVersion),
Diag(
Diag) {}
190 bool TraverseBlockExpr(BlockExpr *BE) {
return true; }
193 for (
auto C : zip(
LE->captures(),
LE->capture_inits()))
194 TraverseLambdaCapture(LE, &std::get<0>(
C), std::get<1>(
C));
197 bool TraverseCapturedStmt(CapturedStmt *CS) {
return true; }
199 bool VisitDecl(
const Decl *D) {
204 case Decl::CXXMethod:
205 case Decl::CXXConstructor:
206 case Decl::CXXDestructor:
207 case Decl::CXXConversion:
208 case Decl::ObjCMethod:
211 CounterMap[D->
getBody()] = NextCounter++;
219 PGOHash::HashType updateCounterMappings(Stmt *S) {
221 if (
Type != PGOHash::None)
222 CounterMap[S] = NextCounter++;
235 unsigned NumCond = 0;
236 bool SplitNestedLogicalOp =
false;
237 SmallVector<const Stmt *, 16> NonLogOpStack;
238 SmallVector<const BinaryOperator *, 16> LogOpStack;
241 bool dataTraverseStmtPre(Stmt *S) {
243 if (MCDCMaxCond == 0)
248 if (LogOpStack.empty()) {
250 SplitNestedLogicalOp =
false;
253 if (
const Expr *E = dyn_cast<Expr>(S)) {
254 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E->IgnoreParens());
263 SplitNestedLogicalOp = SplitNestedLogicalOp || !NonLogOpStack.empty();
265 LogOpStack.push_back(BinOp);
272 if (!LogOpStack.empty())
273 NonLogOpStack.push_back(S);
281 bool dataTraverseStmtPost(Stmt *S) {
283 if (MCDCMaxCond == 0)
286 if (
const Expr *E = dyn_cast<Expr>(S)) {
287 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E->IgnoreParens());
289 assert(LogOpStack.back() == BinOp);
290 LogOpStack.pop_back();
293 if (LogOpStack.empty()) {
295 if (SplitNestedLogicalOp) {
296 unsigned DiagID =
Diag.getCustomDiagID(
298 "unsupported MC/DC boolean expression; "
299 "contains an operation with a nested boolean expression. "
300 "Expression will not be covered");
306 if (NumCond > MCDCMaxCond) {
307 unsigned DiagID =
Diag.getCustomDiagID(
309 "unsupported MC/DC boolean expression; "
310 "number of conditions (%0) exceeds max (%1). "
311 "Expression will not be covered");
323 if (!LogOpStack.empty())
324 NonLogOpStack.pop_back();
334 bool VisitBinaryOperator(BinaryOperator *S) {
340 if (ProfileVersion >= llvm::IndexedInstrProf::Version7)
341 CounterMap[S->
getRHS()] = NextCounter++;
346 return Base::VisitBinaryOperator(S);
349 bool VisitConditionalOperator(ConditionalOperator *S) {
354 return Base::VisitConditionalOperator(S);
358 bool VisitStmt(Stmt *S) {
359 auto Type = updateCounterMappings(S);
361 Type = getHashType(Hash.getHashVersion(), S);
362 if (
Type != PGOHash::None)
367 bool TraverseIfStmt(IfStmt *
If) {
370 return Base::TraverseIfStmt(
If);
375 for (Stmt *CS :
If->children()) {
376 if (!CS || NoSingleByteCoverage)
378 if (CS ==
If->getThen())
379 CounterMap[
If->getThen()] = NextCounter++;
380 else if (CS ==
If->getElse())
381 CounterMap[
If->getElse()] = NextCounter++;
387 for (Stmt *CS :
If->children()) {
390 if (CS ==
If->getThen())
391 Hash.combine(PGOHash::IfThenBranch);
392 else if (CS ==
If->getElse())
393 Hash.combine(PGOHash::IfElseBranch);
396 Hash.combine(PGOHash::EndOfScope);
400 bool TraverseWhileStmt(WhileStmt *While) {
404 for (Stmt *CS : While->
children()) {
405 if (!CS || NoSingleByteCoverage)
408 CounterMap[While->
getCond()] = NextCounter++;
409 else if (CS == While->
getBody())
410 CounterMap[While->
getBody()] = NextCounter++;
413 Base::TraverseWhileStmt(While);
415 Hash.combine(PGOHash::EndOfScope);
419 bool TraverseDoStmt(DoStmt *Do) {
424 if (!CS || NoSingleByteCoverage)
427 CounterMap[Do->
getCond()] = NextCounter++;
429 CounterMap[Do->
getBody()] = NextCounter++;
432 Base::TraverseDoStmt(Do);
434 Hash.combine(PGOHash::EndOfScope);
438 bool TraverseForStmt(ForStmt *For) {
443 if (!CS || NoSingleByteCoverage)
446 CounterMap[For->
getCond()] = NextCounter++;
447 else if (CS == For->
getInc())
448 CounterMap[For->
getInc()] = NextCounter++;
450 CounterMap[For->
getBody()] = NextCounter++;
453 Base::TraverseForStmt(For);
455 Hash.combine(PGOHash::EndOfScope);
459 bool TraverseCXXForRangeStmt(CXXForRangeStmt *ForRange) {
462 for (Stmt *CS : ForRange->
children()) {
463 if (!CS || NoSingleByteCoverage)
466 CounterMap[ForRange->
getBody()] = NextCounter++;
469 Base::TraverseCXXForRangeStmt(ForRange);
471 Hash.combine(PGOHash::EndOfScope);
478#define DEFINE_NESTABLE_TRAVERSAL(N) \
479 bool Traverse##N(N *S) { \
480 Base::Traverse##N(S); \
481 if (Hash.getHashVersion() != PGO_HASH_V1) \
482 Hash.combine(PGOHash::EndOfScope); \
495 case Stmt::LabelStmtClass:
496 return PGOHash::LabelStmt;
497 case Stmt::WhileStmtClass:
498 return PGOHash::WhileStmt;
499 case Stmt::DoStmtClass:
500 return PGOHash::DoStmt;
501 case Stmt::ForStmtClass:
502 return PGOHash::ForStmt;
503 case Stmt::CXXForRangeStmtClass:
504 return PGOHash::CXXForRangeStmt;
505 case Stmt::ObjCForCollectionStmtClass:
506 return PGOHash::ObjCForCollectionStmt;
507 case Stmt::SwitchStmtClass:
508 return PGOHash::SwitchStmt;
509 case Stmt::CaseStmtClass:
510 return PGOHash::CaseStmt;
511 case Stmt::DefaultStmtClass:
512 return PGOHash::DefaultStmt;
513 case Stmt::IfStmtClass:
514 return PGOHash::IfStmt;
515 case Stmt::CXXTryStmtClass:
516 return PGOHash::CXXTryStmt;
517 case Stmt::CXXCatchStmtClass:
518 return PGOHash::CXXCatchStmt;
519 case Stmt::ConditionalOperatorClass:
520 return PGOHash::ConditionalOperator;
521 case Stmt::BinaryConditionalOperatorClass:
522 return PGOHash::BinaryConditionalOperator;
523 case Stmt::BinaryOperatorClass: {
526 return PGOHash::BinaryOperatorLAnd;
528 return PGOHash::BinaryOperatorLOr;
534 return PGOHash::BinaryOperatorLT;
536 return PGOHash::BinaryOperatorGT;
538 return PGOHash::BinaryOperatorLE;
540 return PGOHash::BinaryOperatorGE;
542 return PGOHash::BinaryOperatorEQ;
544 return PGOHash::BinaryOperatorNE;
555 case Stmt::GotoStmtClass:
556 return PGOHash::GotoStmt;
557 case Stmt::IndirectGotoStmtClass:
558 return PGOHash::IndirectGotoStmt;
559 case Stmt::BreakStmtClass:
560 return PGOHash::BreakStmt;
561 case Stmt::ContinueStmtClass:
562 return PGOHash::ContinueStmt;
563 case Stmt::ReturnStmtClass:
564 return PGOHash::ReturnStmt;
565 case Stmt::CXXThrowExprClass:
566 return PGOHash::ThrowExpr;
567 case Stmt::UnaryOperatorClass: {
570 return PGOHash::UnaryOperatorLNot;
576 return PGOHash::None;
582struct ComputeRegionCounts :
public ConstStmtVisitor<ComputeRegionCounts> {
588 bool RecordNextStmtCount;
594 llvm::DenseMap<const Stmt *, uint64_t> &
CountMap;
597 struct BreakContinue {
600 BreakContinue() =
default;
602 SmallVector<BreakContinue, 8> BreakContinueStack;
604 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &
CountMap,
608 void RecordStmtCount(
const Stmt *S) {
609 if (RecordNextStmtCount) {
611 RecordNextStmtCount =
false;
617 CurrentCount = Count;
621 void VisitStmt(
const Stmt *S) {
623 for (
const Stmt *Child : S->
children())
628 void VisitFunctionDecl(
const FunctionDecl *D) {
640 void VisitCapturedDecl(
const CapturedDecl *D) {
647 void VisitObjCMethodDecl(
const ObjCMethodDecl *D) {
654 void VisitBlockDecl(
const BlockDecl *D) {
661 void VisitReturnStmt(
const ReturnStmt *S) {
666 RecordNextStmtCount =
true;
669 void VisitCXXThrowExpr(
const CXXThrowExpr *E) {
674 RecordNextStmtCount =
true;
677 void VisitGotoStmt(
const GotoStmt *S) {
680 RecordNextStmtCount =
true;
683 void VisitLabelStmt(
const LabelStmt *S) {
684 RecordNextStmtCount =
false;
691 void VisitBreakStmt(
const BreakStmt *S) {
693 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
694 BreakContinueStack.back().BreakCount += CurrentCount;
696 RecordNextStmtCount =
true;
699 void VisitContinueStmt(
const ContinueStmt *S) {
701 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
702 BreakContinueStack.back().ContinueCount += CurrentCount;
704 RecordNextStmtCount =
true;
707 void VisitWhileStmt(
const WhileStmt *S) {
709 uint64_t ParentCount = CurrentCount;
711 BreakContinueStack.push_back(BreakContinue());
717 uint64_t BackedgeCount = CurrentCount;
723 BreakContinue BC = BreakContinueStack.pop_back_val();
725 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
728 setCount(BC.BreakCount + CondCount - BodyCount);
729 RecordNextStmtCount =
true;
732 void VisitDoStmt(
const DoStmt *S) {
736 BreakContinueStack.push_back(BreakContinue());
738 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
741 uint64_t BackedgeCount = CurrentCount;
743 BreakContinue BC = BreakContinueStack.pop_back_val();
746 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
749 setCount(BC.BreakCount + CondCount - LoopCount);
750 RecordNextStmtCount =
true;
753 void VisitForStmt(
const ForStmt *S) {
758 uint64_t ParentCount = CurrentCount;
760 BreakContinueStack.push_back(BreakContinue());
766 uint64_t BackedgeCount = CurrentCount;
767 BreakContinue BC = BreakContinueStack.pop_back_val();
772 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
779 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
784 setCount(BC.BreakCount + CondCount - BodyCount);
785 RecordNextStmtCount =
true;
788 void VisitCXXForRangeStmt(
const CXXForRangeStmt *S) {
797 uint64_t ParentCount = CurrentCount;
798 BreakContinueStack.push_back(BreakContinue());
804 uint64_t BackedgeCount = CurrentCount;
805 BreakContinue BC = BreakContinueStack.pop_back_val();
809 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
815 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
818 setCount(BC.BreakCount + CondCount - BodyCount);
819 RecordNextStmtCount =
true;
822 void VisitObjCForCollectionStmt(
const ObjCForCollectionStmt *S) {
825 uint64_t ParentCount = CurrentCount;
826 BreakContinueStack.push_back(BreakContinue());
831 uint64_t BackedgeCount = CurrentCount;
832 BreakContinue BC = BreakContinueStack.pop_back_val();
834 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
836 RecordNextStmtCount =
true;
839 void VisitSwitchStmt(
const SwitchStmt *S) {
845 BreakContinueStack.push_back(BreakContinue());
848 BreakContinue BC = BreakContinueStack.pop_back_val();
849 if (!BreakContinueStack.empty())
850 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
853 RecordNextStmtCount =
true;
856 void VisitSwitchCase(
const SwitchCase *S) {
857 RecordNextStmtCount =
false;
862 setCount(CurrentCount + CaseCount);
866 RecordNextStmtCount =
true;
870 void VisitIfStmt(
const IfStmt *S) {
880 uint64_t ParentCount = CurrentCount;
892 uint64_t ElseCount = ParentCount - ThenCount;
897 OutCount += CurrentCount;
899 OutCount += ElseCount;
901 RecordNextStmtCount =
true;
904 void VisitCXXTryStmt(
const CXXTryStmt *S) {
911 RecordNextStmtCount =
true;
914 void VisitCXXCatchStmt(
const CXXCatchStmt *S) {
915 RecordNextStmtCount =
false;
922 void VisitAbstractConditionalOperator(
const AbstractConditionalOperator *E) {
924 uint64_t ParentCount = CurrentCount;
934 uint64_t FalseCount = setCount(ParentCount - TrueCount);
937 OutCount += CurrentCount;
940 RecordNextStmtCount =
true;
943 void VisitBinLAnd(
const BinaryOperator *E) {
945 uint64_t ParentCount = CurrentCount;
951 setCount(ParentCount + RHSCount - CurrentCount);
952 RecordNextStmtCount =
true;
955 void VisitBinLOr(
const BinaryOperator *E) {
957 uint64_t ParentCount = CurrentCount;
963 setCount(ParentCount + RHSCount - CurrentCount);
964 RecordNextStmtCount =
true;
969void PGOHash::combine(HashType
Type) {
971 assert(
Type &&
"Hash is invalid: unexpected type 0");
972 assert(
unsigned(
Type) < TooBig &&
"Hash is invalid: too many types");
975 if (Count && Count % NumTypesPerWord == 0) {
976 using namespace llvm::support;
978 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
979 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped,
sizeof(Swapped)));
985 Working = Working << NumBitsPerType |
Type;
990 if (Count <= NumTypesPerWord)
1001 MD5.update({(uint8_t)Working});
1003 using namespace llvm::support;
1005 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
1006 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped,
sizeof(Swapped)));
1011 llvm::MD5::MD5Result
Result;
1022 if (CGM.getLangOpts().CUDA && !CGM.getLangOpts().CUDAIsDevice &&
1026 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1027 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1028 if (!InstrumentRegions && !PGOReader)
1035 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1036 if (
const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
1044 CGM.ClearUnusedCoverageMapping(D);
1045 if (Fn->hasFnAttribute(llvm::Attribute::NoProfile))
1047 if (Fn->hasFnAttribute(llvm::Attribute::SkipProfile))
1057 mapRegionCounters(D);
1058 if (CGM.getCodeGenOpts().CoverageMapping)
1059 emitCounterRegionMapping(D);
1061 loadRegionCounts(PGOReader,
SM.isInMainFile(D->
getLocation()));
1062 computeRegionCounts(D);
1063 applyFunctionAttributes(PGOReader, Fn);
1067void CodeGenPGO::mapRegionCounters(
const Decl *D) {
1071 uint64_t ProfileVersion = llvm::IndexedInstrProf::Version;
1073 HashVersion = getPGOHashVersion(PGOReader, CGM);
1074 ProfileVersion = PGOReader->getVersion();
1086 unsigned MCDCMaxConditions =
1090 RegionCounterMap.reset(
new llvm::DenseMap<const Stmt *, CounterPair>);
1092 MapRegionCounters Walker(HashVersion, ProfileVersion, *RegionCounterMap,
1093 *RegionMCDCState, MCDCMaxConditions, CGM.
getDiags());
1094 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1096 else if (
const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1098 else if (
const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1099 Walker.TraverseDecl(
const_cast<BlockDecl *
>(BD));
1100 else if (
const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1102 assert(Walker.NextCounter > 0 &&
"no entry counter mapped for decl");
1103 NumRegionCounters = Walker.NextCounter;
1104 FunctionHash = Walker.Hash.finalize();
1106 FunctionHash &= llvm::NamedInstrProfRecord::FUNC_HASH_MASK;
1109bool CodeGenPGO::skipRegionMappingForDecl(
const Decl *D) {
1119 !D->
hasAttr<CUDAGlobalAttr>()) ||
1121 (D->
hasAttr<CUDAGlobalAttr>() ||
1122 (!D->
hasAttr<CUDAHostAttr>() && D->
hasAttr<CUDADeviceAttr>())))))
1131void CodeGenPGO::emitCounterRegionMapping(
const Decl *D) {
1132 if (skipRegionMappingForDecl(D))
1135 std::string CoverageMapping;
1136 llvm::raw_string_ostream
OS(CoverageMapping);
1137 RegionMCDCState->BranchByStmt.clear();
1138 CoverageMappingGen MappingGen(
1139 *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
1140 CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCState.get());
1141 MappingGen.emitCounterMapping(D, OS);
1143 if (CoverageMapping.empty())
1146 CGM.getCoverageMapping()->addFunctionMappingRecord(
1147 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
1152 llvm::GlobalValue::LinkageTypes
Linkage) {
1153 if (skipRegionMappingForDecl(D))
1156 std::string CoverageMapping;
1157 llvm::raw_string_ostream OS(CoverageMapping);
1159 CGM.getContext().getSourceManager(),
1163 if (CoverageMapping.empty())
1167 CGM.getCoverageMapping()->addFunctionMappingRecord(
1168 FuncNameVar, FuncName, FunctionHash, CoverageMapping,
false);
1171void CodeGenPGO::computeRegionCounts(
const Decl *D) {
1172 StmtCountMap.reset(
new llvm::DenseMap<const Stmt *, uint64_t>);
1173 ComputeRegionCounts Walker(*StmtCountMap, *
this);
1174 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1175 Walker.VisitFunctionDecl(FD);
1176 else if (
const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1177 Walker.VisitObjCMethodDecl(MD);
1178 else if (
const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1179 Walker.VisitBlockDecl(BD);
1180 else if (
const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1181 Walker.VisitCapturedDecl(
const_cast<CapturedDecl *
>(CD));
1185CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
1186 llvm::Function *Fn) {
1191 Fn->setEntryCount(FunctionCount);
1195 if (!RegionCounterMap)
1196 return {
false,
false};
1198 auto I = RegionCounterMap->find(S);
1199 if (I == RegionCounterMap->end())
1200 return {
false,
false};
1202 return {I->second.Executed.hasValue(), I->second.Skipped.hasValue()};
1206 llvm::Value *StepV) {
1207 if (!RegionCounterMap || !Builder.GetInsertBlock())
1210 unsigned Counter = (*RegionCounterMap)[S].Executed;
1214 auto *NormalizedFuncNameVarPtr =
1215 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1216 FuncNameVar, llvm::PointerType::get(CGM.getLLVMContext(), 0));
1218 llvm::Value *Args[] = {
1219 NormalizedFuncNameVarPtr, Builder.getInt64(FunctionHash),
1220 Builder.getInt32(NumRegionCounters), Builder.getInt32(Counter), StepV};
1223 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_cover),
1226 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
1230 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step), Args);
1233bool CodeGenPGO::canEmitMCDCCoverage(
const CGBuilderTy &Builder) {
1239 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1242 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1247 llvm::Value *Args[3] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1248 Builder.getInt64(FunctionHash),
1249 Builder.getInt32(RegionMCDCState->BitmapBits)};
1251 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_parameters), Args);
1258 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1263 auto DecisionStateIter = RegionMCDCState->DecisionByStmt.find(S);
1264 if (DecisionStateIter == RegionMCDCState->DecisionByStmt.end())
1269 if (DecisionStateIter->second.Indices.size() == 0)
1273 unsigned MCDCTestVectorBitmapOffset = DecisionStateIter->second.BitmapIdx;
1274 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1281 llvm::Value *Args[4] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1282 Builder.getInt64(FunctionHash),
1283 Builder.getInt32(MCDCTestVectorBitmapOffset),
1286 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_tvbitmap_update), Args);
1291 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1296 if (!RegionMCDCState->DecisionByStmt.contains(S))
1300 Builder.CreateStore(Builder.getInt32(0), MCDCCondBitmapAddr);
1307 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1319 auto BranchStateIter = RegionMCDCState->BranchByStmt.find(S);
1320 if (BranchStateIter == RegionMCDCState->BranchByStmt.end())
1324 const auto &Branch = BranchStateIter->second;
1325 assert(Branch.ID >= 0 &&
"Condition has no ID!");
1326 assert(Branch.DecisionStmt);
1329 const auto DecisionIter =
1330 RegionMCDCState->DecisionByStmt.find(Branch.DecisionStmt);
1331 if (DecisionIter == RegionMCDCState->DecisionByStmt.end())
1334 const auto &TVIdxs = DecisionIter->second.Indices[Branch.ID];
1336 auto *CurTV = Builder.CreateLoad(MCDCCondBitmapAddr,
1337 "mcdc." + Twine(Branch.ID + 1) +
".cur");
1338 auto *NewTV = Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[
true]));
1339 NewTV = Builder.CreateSelect(
1340 Val, NewTV, Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[
false])));
1341 Builder.CreateStore(NewTV, MCDCCondBitmapAddr);
1345 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1346 M.addModuleFlag(llvm::Module::Warning,
"EnableValueProfiling",
1351 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1353 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1354 llvm::Type *IntTy64 = llvm::Type::getInt64Ty(M.getContext());
1355 uint64_t ProfileVersion =
1356 (INSTR_PROF_RAW_VERSION | VARIANT_MASK_BYTE_COVERAGE);
1358 auto IRLevelVersionVariable =
new llvm::GlobalVariable(
1359 M, IntTy64,
true, llvm::GlobalValue::WeakAnyLinkage,
1360 llvm::Constant::getIntegerValue(IntTy64,
1361 llvm::APInt(64, ProfileVersion)),
1364 IRLevelVersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1365 llvm::Triple TT(M.getTargetTriple());
1367 IRLevelVersionVariable->setVisibility(
1368 llvm::GlobalValue::ProtectedVisibility);
1369 if (TT.supportsCOMDAT()) {
1370 IRLevelVersionVariable->setLinkage(llvm::GlobalValue::ExternalLinkage);
1371 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1373 IRLevelVersionVariable->setDSOLocal(
true);
1380 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
1385 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
1391 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
1392 if (InstrumentValueSites && RegionCounterMap) {
1393 auto BuilderInsertPoint = Builder.saveIP();
1394 Builder.SetInsertPoint(ValueSite);
1395 llvm::Value *Args[5] = {
1397 Builder.getInt64(FunctionHash),
1398 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
1399 Builder.getInt32(ValueKind),
1400 Builder.getInt32(NumValueSites[ValueKind]++)
1403 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
1404 Builder.restoreIP(BuilderInsertPoint);
1408 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1416 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
1419 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
1420 (llvm::InstrProfValueKind)ValueKind,
1421 NumValueSites[ValueKind]);
1423 NumValueSites[ValueKind]++;
1427void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
1428 bool IsInMainFile) {
1430 RegionCounts.clear();
1431 auto RecordExpected = PGOReader->getInstrProfRecord(FuncName, FunctionHash);
1432 if (
auto E = RecordExpected.takeError()) {
1433 auto IPE = std::get<0>(llvm::InstrProfError::take(std::move(E)));
1434 if (IPE == llvm::instrprof_error::unknown_function)
1436 else if (IPE == llvm::instrprof_error::hash_mismatch)
1438 else if (IPE == llvm::instrprof_error::malformed)
1444 std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
1445 RegionCounts = ProfRecord->Counts;
1453 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
1466 assert(Scale &&
"scale by 0?");
1467 uint64_t Scaled = Weight / Scale + 1;
1468 assert(Scaled <= UINT32_MAX &&
"overflow 32-bits");
1472llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1473 uint64_t FalseCount)
const {
1475 if (!TrueCount && !FalseCount)
1481 llvm::MDBuilder MDHelper(
CGM.getLLVMContext());
1487CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights)
const {
1489 if (Weights.size() < 2)
1493 uint64_t MaxWeight = *llvm::max_element(Weights);
1500 SmallVector<uint32_t, 16> ScaledWeights;
1501 ScaledWeights.reserve(Weights.size());
1502 for (uint64_t W : Weights)
1505 llvm::MDBuilder MDHelper(
CGM.getLLVMContext());
1506 return MDHelper.createBranchWeights(ScaledWeights);
1510CodeGenFunction::createProfileWeightsForLoop(
const Stmt *
Cond,
1511 uint64_t LoopCount)
const {
1512 if (!PGO->haveRegionCounts())
1514 std::optional<uint64_t> CondCount = PGO->getStmtCount(
Cond);
1515 if (!CondCount || *CondCount == 0)
1517 return createProfileWeights(LoopCount,
1518 std::max(*CondCount, LoopCount) - LoopCount);
1522 llvm::Value *StepV) {
1523 if (
CGM.getCodeGenOpts().hasProfileClangInstr() &&
1524 !
CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1525 !
CurFn->hasFnAttribute(llvm::Attribute::SkipProfile)) {
1527 PGO->emitCounterSetOrIncrement(
Builder, S, StepV);
1529 PGO->setCurrentStmt(S);
1533 return PGO->getIsCounterPair(S);
1536 PGO->markStmtAsUsed(Skipped, S);
1539 PGO->markStmtMaybeUsed(S);
1544 PGO->emitMCDCParameters(
Builder);
1550 PGO->emitMCDCCondBitmapReset(
Builder, E, MCDCCondBitmapAddr);
1551 PGO->setCurrentStmt(E);
1556 PGO->emitMCDCTestVectorBitmapUpdate(
Builder, E, MCDCCondBitmapAddr, *
this);
1557 PGO->setCurrentStmt(E);
1564 PGO->emitMCDCCondBitmapUpdate(
Builder, E, MCDCCondBitmapAddr, Val, *
this);
1565 PGO->setCurrentStmt(E);
1570 return PGO->getStmtCount(S).value_or(0);
1575 PGO->setCurrentRegionCount(Count);
1581 return PGO->getCurrentRegionCount();
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.
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()
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
CXXCatchStmt - This represents a C++ catch block.
Stmt * getHandlerBlock() const
DeclStmt * getBeginStmt()
DeclStmt * getLoopVarStmt()
DeclStmt * getRangeStmt()
const Expr * getSubExpr() const
CXXTryStmt - A C++ try block, including all handlers.
CXXCatchStmt * getHandler(unsigned i)
unsigned getNumHandlers() const
CompoundStmt * getTryBlock()
Represents the body of a CapturedStmt, and serves as its DeclContext.
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string MainFileName
The user provided name for the "main file", if non-empty.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
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
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
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...
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.
bool isMCDCCoverageEnabled() const
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
ASTContext & getContext() 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)
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
void emitMCDCTestVectorBitmapUpdate(CGBuilderTy &Builder, const Expr *S, Address MCDCCondBitmapAddr, CodeGenFunction &CGF)
uint64_t getRegionCount(const Stmt *S)
Return the region count for the counter at the given index.
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, Address MCDCCondBitmapAddr, llvm::Value *Val, CodeGenFunction &CGF)
void emitMCDCCondBitmapReset(CGBuilderTy &Builder, const Expr *S, Address MCDCCondBitmapAddr)
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 emitMCDCParameters(CGBuilderTy &Builder)
bool haveRegionCounts() const
Whether or not we have PGO region data for the current function.
void emitCounterSetOrIncrement(CGBuilderTy &Builder, const Stmt *S, llvm::Value *StepV)
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...
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Decl - This represents one declaration (or definition), e.g.
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
SourceLocation getLocation() const
This represents one expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Represents a function declaration or definition.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
GlobalDecl - represents a global declaration.
CXXCtorType getCtorType() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
bool isNegatedConsteval() const
Represents Objective-C's collection statement.
ObjCMethodDecl - Represents an instance or class method declaration.
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
This class handles loading and caching of source files into memory.
Stmt - This represents one statement.
StmtClass getStmtClass() const
SourceLocation getBeginLoc() const LLVM_READONLY
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool LE(InterpState &S, CodePtr OpPC)
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
bool isa(CodeGen::Address addr)
@ 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.
@ Result
The result type of a method or function.
@ Dtor_Base
Base object dtor.
@ Type
The name was classified as a type.
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
U cast(CodeGen::Address addr)
@ None
The alignment was not explicit in code.
cl::opt< bool > SystemHeadersCoverage
Diagnostic wrappers for TextAPI types for error reporting.
cl::opt< bool > EnableSingleByteCoverage
Per-Function MC/DC state.
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt