#include "CodeGenPGO.h"
#include "CodeGenFunction.h"
#include "CoverageMappingGen.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MD5.h"
static llvm::cl::opt<bool>
EnableValueProfiling("enable-value-profiling",
llvm::cl::desc("Enable value profiling"),
llvm::cl::Hidden, llvm::cl::init(false));
using namespace clang;
using namespace CodeGen;
void CodeGenPGO::setFuncName(StringRef Name,
llvm::GlobalValue::LinkageTypes Linkage) {
llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
FuncName = llvm::getPGOFuncName(
Name, Linkage, CGM.getCodeGenOpts().MainFileName,
PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
if (CGM.getCodeGenOpts().hasProfileClangInstr())
FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
}
void CodeGenPGO::setFuncName(llvm::Function *Fn) {
setFuncName(Fn->getName(), Fn->getLinkage());
llvm::createPGOFuncNameMetadata(*Fn, FuncName);
}
enum PGOHashVersion : unsigned {
PGO_HASH_V1,
PGO_HASH_V2,
PGO_HASH_V3,
PGO_HASH_LATEST = PGO_HASH_V3
};
namespace {
class PGOHash {
uint64_t Working;
unsigned Count;
PGOHashVersion HashVersion;
llvm::MD5 MD5;
static const int NumBitsPerType = 6;
static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
static const unsigned TooBig = 1u << NumBitsPerType;
public:
enum HashType : unsigned char {
None = 0,
LabelStmt = 1,
WhileStmt,
DoStmt,
ForStmt,
CXXForRangeStmt,
ObjCForCollectionStmt,
SwitchStmt,
CaseStmt,
DefaultStmt,
IfStmt,
CXXTryStmt,
CXXCatchStmt,
ConditionalOperator,
BinaryOperatorLAnd,
BinaryOperatorLOr,
BinaryConditionalOperator,
EndOfScope,
IfThenBranch,
IfElseBranch,
GotoStmt,
IndirectGotoStmt,
BreakStmt,
ContinueStmt,
ReturnStmt,
ThrowExpr,
UnaryOperatorLNot,
BinaryOperatorLT,
BinaryOperatorGT,
BinaryOperatorLE,
BinaryOperatorGE,
BinaryOperatorEQ,
BinaryOperatorNE,
LastHashType
};
static_assert(LastHashType <= TooBig, "Too many types in HashType");
PGOHash(PGOHashVersion HashVersion)
: Working(0), Count(0), HashVersion(HashVersion) {}
void combine(HashType Type);
uint64_t finalize();
PGOHashVersion getHashVersion() const { return HashVersion; }
};
const int PGOHash::NumBitsPerType;
const unsigned PGOHash::NumTypesPerWord;
const unsigned PGOHash::TooBig;
static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
CodeGenModule &CGM) {
if (PGOReader->getVersion() <= 4)
return PGO_HASH_V1;
if (PGOReader->getVersion() <= 5)
return PGO_HASH_V2;
return PGO_HASH_V3;
}
struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
using Base = RecursiveASTVisitor<MapRegionCounters>;
unsigned NextCounter;
PGOHash Hash;
llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
uint64_t ProfileVersion;
MapRegionCounters(PGOHashVersion HashVersion, uint64_t ProfileVersion,
llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
: NextCounter(0), Hash(HashVersion), CounterMap(CounterMap),
ProfileVersion(ProfileVersion) {}
bool TraverseBlockExpr(BlockExpr *BE) { return true; }
bool TraverseLambdaExpr(LambdaExpr *LE) {
for (auto C : zip(LE->captures(), LE->capture_inits()))
TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
return true;
}
bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
bool VisitDecl(const Decl *D) {
switch (D->getKind()) {
default:
break;
case Decl::Function:
case Decl::CXXMethod:
case Decl::CXXConstructor:
case Decl::CXXDestructor:
case Decl::CXXConversion:
case Decl::ObjCMethod:
case Decl::Block:
case Decl::Captured:
CounterMap[D->getBody()] = NextCounter++;
break;
}
return true;
}
PGOHash::HashType updateCounterMappings(Stmt *S) {
auto Type = getHashType(PGO_HASH_V1, S);
if (Type != PGOHash::None)
CounterMap[S] = NextCounter++;
return Type;
}
bool VisitBinaryOperator(BinaryOperator *S) {
if (ProfileVersion >= llvm::IndexedInstrProf::Version7)
if (S->isLogicalOp() &&
CodeGenFunction::isInstrumentedCondition(S->getRHS()))
CounterMap[S->getRHS()] = NextCounter++;
return Base::VisitBinaryOperator(S);
}
bool VisitStmt(Stmt *S) {
auto Type = updateCounterMappings(S);
if (Hash.getHashVersion() != PGO_HASH_V1)
Type = getHashType(Hash.getHashVersion(), S);
if (Type != PGOHash::None)
Hash.combine(Type);
return true;
}
bool TraverseIfStmt(IfStmt *If) {
if (Hash.getHashVersion() == PGO_HASH_V1)
return Base::TraverseIfStmt(If);
VisitStmt(If);
for (Stmt *CS : If->children()) {
if (!CS)
continue;
if (CS == If->getThen())
Hash.combine(PGOHash::IfThenBranch);
else if (CS == If->getElse())
Hash.combine(PGOHash::IfElseBranch);
TraverseStmt(CS);
}
Hash.combine(PGOHash::EndOfScope);
return true;
}
#define DEFINE_NESTABLE_TRAVERSAL(N) \
bool Traverse##N(N *S) { \
Base::Traverse##N(S); \
if (Hash.getHashVersion() != PGO_HASH_V1) \
Hash.combine(PGOHash::EndOfScope); \
return true; \
}
DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
DEFINE_NESTABLE_TRAVERSAL(DoStmt)
DEFINE_NESTABLE_TRAVERSAL(ForStmt)
DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
switch (S->getStmtClass()) {
default:
break;
case Stmt::LabelStmtClass:
return PGOHash::LabelStmt;
case Stmt::WhileStmtClass:
return PGOHash::WhileStmt;
case Stmt::DoStmtClass:
return PGOHash::DoStmt;
case Stmt::ForStmtClass:
return PGOHash::ForStmt;
case Stmt::CXXForRangeStmtClass:
return PGOHash::CXXForRangeStmt;
case Stmt::ObjCForCollectionStmtClass:
return PGOHash::ObjCForCollectionStmt;
case Stmt::SwitchStmtClass:
return PGOHash::SwitchStmt;
case Stmt::CaseStmtClass:
return PGOHash::CaseStmt;
case Stmt::DefaultStmtClass:
return PGOHash::DefaultStmt;
case Stmt::IfStmtClass:
return PGOHash::IfStmt;
case Stmt::CXXTryStmtClass:
return PGOHash::CXXTryStmt;
case Stmt::CXXCatchStmtClass:
return PGOHash::CXXCatchStmt;
case Stmt::ConditionalOperatorClass:
return PGOHash::ConditionalOperator;
case Stmt::BinaryConditionalOperatorClass:
return PGOHash::BinaryConditionalOperator;
case Stmt::BinaryOperatorClass: {
const BinaryOperator *BO = cast<BinaryOperator>(S);
if (BO->getOpcode() == BO_LAnd)
return PGOHash::BinaryOperatorLAnd;
if (BO->getOpcode() == BO_LOr)
return PGOHash::BinaryOperatorLOr;
if (HashVersion >= PGO_HASH_V2) {
switch (BO->getOpcode()) {
default:
break;
case BO_LT:
return PGOHash::BinaryOperatorLT;
case BO_GT:
return PGOHash::BinaryOperatorGT;
case BO_LE:
return PGOHash::BinaryOperatorLE;
case BO_GE:
return PGOHash::BinaryOperatorGE;
case BO_EQ:
return PGOHash::BinaryOperatorEQ;
case BO_NE:
return PGOHash::BinaryOperatorNE;
}
}
break;
}
}
if (HashVersion >= PGO_HASH_V2) {
switch (S->getStmtClass()) {
default:
break;
case Stmt::GotoStmtClass:
return PGOHash::GotoStmt;
case Stmt::IndirectGotoStmtClass:
return PGOHash::IndirectGotoStmt;
case Stmt::BreakStmtClass:
return PGOHash::BreakStmt;
case Stmt::ContinueStmtClass:
return PGOHash::ContinueStmt;
case Stmt::ReturnStmtClass:
return PGOHash::ReturnStmt;
case Stmt::CXXThrowExprClass:
return PGOHash::ThrowExpr;
case Stmt::UnaryOperatorClass: {
const UnaryOperator *UO = cast<UnaryOperator>(S);
if (UO->getOpcode() == UO_LNot)
return PGOHash::UnaryOperatorLNot;
break;
}
}
}
return PGOHash::None;
}
};
struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
CodeGenPGO &PGO;
bool RecordNextStmtCount;
uint64_t CurrentCount;
llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
struct BreakContinue {
uint64_t BreakCount;
uint64_t ContinueCount;
BreakContinue() : BreakCount(0), ContinueCount(0) {}
};
SmallVector<BreakContinue, 8> BreakContinueStack;
ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
CodeGenPGO &PGO)
: PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
void RecordStmtCount(const Stmt *S) {
if (RecordNextStmtCount) {
CountMap[S] = CurrentCount;
RecordNextStmtCount = false;
}
}
uint64_t setCount(uint64_t Count) {
CurrentCount = Count;
return Count;
}
void VisitStmt(const Stmt *S) {
RecordStmtCount(S);
for (const Stmt *Child : S->children())
if (Child)
this->Visit(Child);
}
void VisitFunctionDecl(const FunctionDecl *D) {
uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
CountMap[D->getBody()] = BodyCount;
Visit(D->getBody());
}
void VisitLambdaExpr(const LambdaExpr *LE) {}
void VisitCapturedDecl(const CapturedDecl *D) {
uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
CountMap[D->getBody()] = BodyCount;
Visit(D->getBody());
}
void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
CountMap[D->getBody()] = BodyCount;
Visit(D->getBody());
}
void VisitBlockDecl(const BlockDecl *D) {
uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
CountMap[D->getBody()] = BodyCount;
Visit(D->getBody());
}
void VisitReturnStmt(const ReturnStmt *S) {
RecordStmtCount(S);
if (S->getRetValue())
Visit(S->getRetValue());
CurrentCount = 0;
RecordNextStmtCount = true;
}
void VisitCXXThrowExpr(const CXXThrowExpr *E) {
RecordStmtCount(E);
if (E->getSubExpr())
Visit(E->getSubExpr());
CurrentCount = 0;
RecordNextStmtCount = true;
}
void VisitGotoStmt(const GotoStmt *S) {
RecordStmtCount(S);
CurrentCount = 0;
RecordNextStmtCount = true;
}
void VisitLabelStmt(const LabelStmt *S) {
RecordNextStmtCount = false;
uint64_t BlockCount = setCount(PGO.getRegionCount(S));
CountMap[S] = BlockCount;
Visit(S->getSubStmt());
}
void VisitBreakStmt(const BreakStmt *S) {
RecordStmtCount(S);
assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
BreakContinueStack.back().BreakCount += CurrentCount;
CurrentCount = 0;
RecordNextStmtCount = true;
}
void VisitContinueStmt(const ContinueStmt *S) {
RecordStmtCount(S);
assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
BreakContinueStack.back().ContinueCount += CurrentCount;
CurrentCount = 0;
RecordNextStmtCount = true;
}
void VisitWhileStmt(const WhileStmt *S) {
RecordStmtCount(S);
uint64_t ParentCount = CurrentCount;
BreakContinueStack.push_back(BreakContinue());
uint64_t BodyCount = setCount(PGO.getRegionCount(S));
CountMap[S->getBody()] = CurrentCount;
Visit(S->getBody());
uint64_t BackedgeCount = CurrentCount;
BreakContinue BC = BreakContinueStack.pop_back_val();
uint64_t CondCount =
setCount(ParentCount + BackedgeCount + BC.ContinueCount);
CountMap[S->getCond()] = CondCount;
Visit(S->getCond());
setCount(BC.BreakCount + CondCount - BodyCount);
RecordNextStmtCount = true;
}
void VisitDoStmt(const DoStmt *S) {
RecordStmtCount(S);
uint64_t LoopCount = PGO.getRegionCount(S);
BreakContinueStack.push_back(BreakContinue());
uint64_t BodyCount = setCount(LoopCount + CurrentCount);
CountMap[S->getBody()] = BodyCount;
Visit(S->getBody());
uint64_t BackedgeCount = CurrentCount;
BreakContinue BC = BreakContinueStack.pop_back_val();
uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
CountMap[S->getCond()] = CondCount;
Visit(S->getCond());
setCount(BC.BreakCount + CondCount - LoopCount);
RecordNextStmtCount = true;
}
void VisitForStmt(const ForStmt *S) {
RecordStmtCount(S);
if (S->getInit())
Visit(S->getInit());
uint64_t ParentCount = CurrentCount;
BreakContinueStack.push_back(BreakContinue());
uint64_t BodyCount = setCount(PGO.getRegionCount(S));
CountMap[S->getBody()] = BodyCount;
Visit(S->getBody());
uint64_t BackedgeCount = CurrentCount;
BreakContinue BC = BreakContinueStack.pop_back_val();
if (S->getInc()) {
uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
CountMap[S->getInc()] = IncCount;
Visit(S->getInc());
}
uint64_t CondCount =
setCount(ParentCount + BackedgeCount + BC.ContinueCount);
if (S->getCond()) {
CountMap[S->getCond()] = CondCount;
Visit(S->getCond());
}
setCount(BC.BreakCount + CondCount - BodyCount);
RecordNextStmtCount = true;
}
void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
RecordStmtCount(S);
if (S->getInit())
Visit(S->getInit());
Visit(S->getLoopVarStmt());
Visit(S->getRangeStmt());
Visit(S->getBeginStmt());
Visit(S->getEndStmt());
uint64_t ParentCount = CurrentCount;
BreakContinueStack.push_back(BreakContinue());
uint64_t BodyCount = setCount(PGO.getRegionCount(S));
CountMap[S->getBody()] = BodyCount;
Visit(S->getBody());
uint64_t BackedgeCount = CurrentCount;
BreakContinue BC = BreakContinueStack.pop_back_val();
uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
CountMap[S->getInc()] = IncCount;
Visit(S->getInc());
uint64_t CondCount =
setCount(ParentCount + BackedgeCount + BC.ContinueCount);
CountMap[S->getCond()] = CondCount;
Visit(S->getCond());
setCount(BC.BreakCount + CondCount - BodyCount);
RecordNextStmtCount = true;
}
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
RecordStmtCount(S);
Visit(S->getElement());
uint64_t ParentCount = CurrentCount;
BreakContinueStack.push_back(BreakContinue());
uint64_t BodyCount = setCount(PGO.getRegionCount(S));
CountMap[S->getBody()] = BodyCount;
Visit(S->getBody());
uint64_t BackedgeCount = CurrentCount;
BreakContinue BC = BreakContinueStack.pop_back_val();
setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
BodyCount);
RecordNextStmtCount = true;
}
void VisitSwitchStmt(const SwitchStmt *S) {
RecordStmtCount(S);
if (S->getInit())
Visit(S->getInit());
Visit(S->getCond());
CurrentCount = 0;
BreakContinueStack.push_back(BreakContinue());
Visit(S->getBody());
BreakContinue BC = BreakContinueStack.pop_back_val();
if (!BreakContinueStack.empty())
BreakContinueStack.back().ContinueCount += BC.ContinueCount;
setCount(PGO.getRegionCount(S));
RecordNextStmtCount = true;
}
void VisitSwitchCase(const SwitchCase *S) {
RecordNextStmtCount = false;
uint64_t CaseCount = PGO.getRegionCount(S);
setCount(CurrentCount + CaseCount);
CountMap[S] = CaseCount;
RecordNextStmtCount = true;
Visit(S->getSubStmt());
}
void VisitIfStmt(const IfStmt *S) {
RecordStmtCount(S);
if (S->isConsteval()) {
const Stmt *Stm = S->isNegatedConsteval() ? S->getThen() : S->getElse();
if (Stm)
Visit(Stm);
return;
}
uint64_t ParentCount = CurrentCount;
if (S->getInit())
Visit(S->getInit());
Visit(S->getCond());
uint64_t ThenCount = setCount(PGO.getRegionCount(S));
CountMap[S->getThen()] = ThenCount;
Visit(S->getThen());
uint64_t OutCount = CurrentCount;
uint64_t ElseCount = ParentCount - ThenCount;
if (S->getElse()) {
setCount(ElseCount);
CountMap[S->getElse()] = ElseCount;
Visit(S->getElse());
OutCount += CurrentCount;
} else
OutCount += ElseCount;
setCount(OutCount);
RecordNextStmtCount = true;
}
void VisitCXXTryStmt(const CXXTryStmt *S) {
RecordStmtCount(S);
Visit(S->getTryBlock());
for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
Visit(S->getHandler(I));
setCount(PGO.getRegionCount(S));
RecordNextStmtCount = true;
}
void VisitCXXCatchStmt(const CXXCatchStmt *S) {
RecordNextStmtCount = false;
uint64_t CatchCount = setCount(PGO.getRegionCount(S));
CountMap[S] = CatchCount;
Visit(S->getHandlerBlock());
}
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
RecordStmtCount(E);
uint64_t ParentCount = CurrentCount;
Visit(E->getCond());
uint64_t TrueCount = setCount(PGO.getRegionCount(E));
CountMap[E->getTrueExpr()] = TrueCount;
Visit(E->getTrueExpr());
uint64_t OutCount = CurrentCount;
uint64_t FalseCount = setCount(ParentCount - TrueCount);
CountMap[E->getFalseExpr()] = FalseCount;
Visit(E->getFalseExpr());
OutCount += CurrentCount;
setCount(OutCount);
RecordNextStmtCount = true;
}
void VisitBinLAnd(const BinaryOperator *E) {
RecordStmtCount(E);
uint64_t ParentCount = CurrentCount;
Visit(E->getLHS());
uint64_t RHSCount = setCount(PGO.getRegionCount(E));
CountMap[E->getRHS()] = RHSCount;
Visit(E->getRHS());
setCount(ParentCount + RHSCount - CurrentCount);
RecordNextStmtCount = true;
}
void VisitBinLOr(const BinaryOperator *E) {
RecordStmtCount(E);
uint64_t ParentCount = CurrentCount;
Visit(E->getLHS());
uint64_t RHSCount = setCount(PGO.getRegionCount(E));
CountMap[E->getRHS()] = RHSCount;
Visit(E->getRHS());
setCount(ParentCount + RHSCount - CurrentCount);
RecordNextStmtCount = true;
}
};
}
void PGOHash::combine(HashType Type) {
assert(Type && "Hash is invalid: unexpected type 0");
assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
if (Count && Count % NumTypesPerWord == 0) {
using namespace llvm::support;
uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
Working = 0;
}
++Count;
Working = Working << NumBitsPerType | Type;
}
uint64_t PGOHash::finalize() {
if (Count <= NumTypesPerWord)
return Working;
if (Working) {
if (HashVersion < PGO_HASH_V3) {
MD5.update({(uint8_t)Working});
} else {
using namespace llvm::support;
uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
}
}
llvm::MD5::MD5Result Result;
MD5.final(Result);
return Result.low();
}
void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
const Decl *D = GD.getDecl();
if (!D->hasBody())
return;
if (CGM.getLangOpts().CUDA && !CGM.getLangOpts().CUDAIsDevice &&
D->hasAttr<CUDAGlobalAttr>())
return;
bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
if (!InstrumentRegions && !PGOReader)
return;
if (D->isImplicit())
return;
if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
if (GD.getCtorType() != Ctor_Base &&
CodeGenFunction::IsConstructorDelegationValid(CCD))
return;
}
if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
return;
CGM.ClearUnusedCoverageMapping(D);
if (Fn->hasFnAttribute(llvm::Attribute::NoProfile))
return;
setFuncName(Fn);
mapRegionCounters(D);
if (CGM.getCodeGenOpts().CoverageMapping)
emitCounterRegionMapping(D);
if (PGOReader) {
SourceManager &SM = CGM.getContext().getSourceManager();
loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
computeRegionCounts(D);
applyFunctionAttributes(PGOReader, Fn);
}
}
void CodeGenPGO::mapRegionCounters(const Decl *D) {
PGOHashVersion HashVersion = PGO_HASH_LATEST;
uint64_t ProfileVersion = llvm::IndexedInstrProf::Version;
if (auto *PGOReader = CGM.getPGOReader()) {
HashVersion = getPGOHashVersion(PGOReader, CGM);
ProfileVersion = PGOReader->getVersion();
}
RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
MapRegionCounters Walker(HashVersion, ProfileVersion, *RegionCounterMap);
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
NumRegionCounters = Walker.NextCounter;
FunctionHash = Walker.Hash.finalize();
}
bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
if (!D->getBody())
return true;
if (CGM.getLangOpts().CUDA &&
((CGM.getLangOpts().CUDAIsDevice && !D->hasAttr<CUDADeviceAttr>() &&
!D->hasAttr<CUDAGlobalAttr>()) ||
(!CGM.getLangOpts().CUDAIsDevice &&
(D->hasAttr<CUDAGlobalAttr>() ||
(!D->hasAttr<CUDAHostAttr>() && D->hasAttr<CUDADeviceAttr>())))))
return true;
const auto &SM = CGM.getContext().getSourceManager();
auto Loc = D->getBody()->getBeginLoc();
return SM.isInSystemHeader(Loc);
}
void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
if (skipRegionMappingForDecl(D))
return;
std::string CoverageMapping;
llvm::raw_string_ostream OS(CoverageMapping);
CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
CGM.getContext().getSourceManager(),
CGM.getLangOpts(), RegionCounterMap.get());
MappingGen.emitCounterMapping(D, OS);
OS.flush();
if (CoverageMapping.empty())
return;
CGM.getCoverageMapping()->addFunctionMappingRecord(
FuncNameVar, FuncName, FunctionHash, CoverageMapping);
}
void
CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
llvm::GlobalValue::LinkageTypes Linkage) {
if (skipRegionMappingForDecl(D))
return;
std::string CoverageMapping;
llvm::raw_string_ostream OS(CoverageMapping);
CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
CGM.getContext().getSourceManager(),
CGM.getLangOpts());
MappingGen.emitEmptyMapping(D, OS);
OS.flush();
if (CoverageMapping.empty())
return;
setFuncName(Name, Linkage);
CGM.getCoverageMapping()->addFunctionMappingRecord(
FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
}
void CodeGenPGO::computeRegionCounts(const Decl *D) {
StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
ComputeRegionCounts Walker(*StmtCountMap, *this);
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Walker.VisitFunctionDecl(FD);
else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Walker.VisitObjCMethodDecl(MD);
else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Walker.VisitBlockDecl(BD);
else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
}
void
CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
llvm::Function *Fn) {
if (!haveRegionCounts())
return;
uint64_t FunctionCount = getRegionCount(nullptr);
Fn->setEntryCount(FunctionCount);
}
void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
llvm::Value *StepV) {
if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
return;
if (!Builder.GetInsertBlock())
return;
unsigned Counter = (*RegionCounterMap)[S];
auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Builder.getInt64(FunctionHash),
Builder.getInt32(NumRegionCounters),
Builder.getInt32(Counter), StepV};
if (!StepV)
Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
makeArrayRef(Args, 4));
else
Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
makeArrayRef(Args));
}
void CodeGenPGO::setValueProfilingFlag(llvm::Module &M) {
if (CGM.getCodeGenOpts().hasProfileClangInstr())
M.addModuleFlag(llvm::Module::Warning, "EnableValueProfiling",
uint32_t(EnableValueProfiling));
}
void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
if (!EnableValueProfiling)
return;
if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
return;
if (isa<llvm::Constant>(ValuePtr))
return;
bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
if (InstrumentValueSites && RegionCounterMap) {
auto BuilderInsertPoint = Builder.saveIP();
Builder.SetInsertPoint(ValueSite);
llvm::Value *Args[5] = {
llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Builder.getInt64(FunctionHash),
Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
Builder.getInt32(ValueKind),
Builder.getInt32(NumValueSites[ValueKind]++)
};
Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Builder.restoreIP(BuilderInsertPoint);
return;
}
llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
if (PGOReader && haveRegionCounts()) {
if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
return;
llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
(llvm::InstrProfValueKind)ValueKind,
NumValueSites[ValueKind]);
NumValueSites[ValueKind]++;
}
}
void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
bool IsInMainFile) {
CGM.getPGOStats().addVisited(IsInMainFile);
RegionCounts.clear();
llvm::Expected<llvm::InstrProfRecord> RecordExpected =
PGOReader->getInstrProfRecord(FuncName, FunctionHash);
if (auto E = RecordExpected.takeError()) {
auto IPE = llvm::InstrProfError::take(std::move(E));
if (IPE == llvm::instrprof_error::unknown_function)
CGM.getPGOStats().addMissing(IsInMainFile);
else if (IPE == llvm::instrprof_error::hash_mismatch)
CGM.getPGOStats().addMismatched(IsInMainFile);
else if (IPE == llvm::instrprof_error::malformed)
CGM.getPGOStats().addMismatched(IsInMainFile);
return;
}
ProfRecord =
std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
RegionCounts = ProfRecord->Counts;
}
static uint64_t calculateWeightScale(uint64_t MaxWeight) {
return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
}
static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
assert(Scale && "scale by 0?");
uint64_t Scaled = Weight / Scale + 1;
assert(Scaled <= UINT32_MAX && "overflow 32-bits");
return Scaled;
}
llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
uint64_t FalseCount) const {
if (!TrueCount && !FalseCount)
return nullptr;
uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
llvm::MDBuilder MDHelper(CGM.getLLVMContext());
return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
scaleBranchWeight(FalseCount, Scale));
}
llvm::MDNode *
CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) const {
if (Weights.size() < 2)
return nullptr;
uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
if (MaxWeight == 0)
return nullptr;
uint64_t Scale = calculateWeightScale(MaxWeight);
SmallVector<uint32_t, 16> ScaledWeights;
ScaledWeights.reserve(Weights.size());
for (uint64_t W : Weights)
ScaledWeights.push_back(scaleBranchWeight(W, Scale));
llvm::MDBuilder MDHelper(CGM.getLLVMContext());
return MDHelper.createBranchWeights(ScaledWeights);
}
llvm::MDNode *
CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
uint64_t LoopCount) const {
if (!PGO.haveRegionCounts())
return nullptr;
Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
if (!CondCount || *CondCount == 0)
return nullptr;
return createProfileWeights(LoopCount,
std::max(*CondCount, LoopCount) - LoopCount);
}