1*0b57cec5SDimitry Andric //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Instrumentation-based profile-guided optimization
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "CodeGenPGO.h"
14*0b57cec5SDimitry Andric #include "CodeGenFunction.h"
15*0b57cec5SDimitry Andric #include "CoverageMappingGen.h"
16*0b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
17*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
18*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
19*0b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
20480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
21*0b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
22*0b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
23*0b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
24*0b57cec5SDimitry Andric 
25*0b57cec5SDimitry Andric static llvm::cl::opt<bool>
26*0b57cec5SDimitry Andric     EnableValueProfiling("enable-value-profiling", llvm::cl::ZeroOrMore,
27*0b57cec5SDimitry Andric                          llvm::cl::desc("Enable value profiling"),
28*0b57cec5SDimitry Andric                          llvm::cl::Hidden, llvm::cl::init(false));
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric using namespace clang;
31*0b57cec5SDimitry Andric using namespace CodeGen;
32*0b57cec5SDimitry Andric 
33*0b57cec5SDimitry Andric void CodeGenPGO::setFuncName(StringRef Name,
34*0b57cec5SDimitry Andric                              llvm::GlobalValue::LinkageTypes Linkage) {
35*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
36*0b57cec5SDimitry Andric   FuncName = llvm::getPGOFuncName(
37*0b57cec5SDimitry Andric       Name, Linkage, CGM.getCodeGenOpts().MainFileName,
38*0b57cec5SDimitry Andric       PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
39*0b57cec5SDimitry Andric 
40*0b57cec5SDimitry Andric   // If we're generating a profile, create a variable for the name.
41*0b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().hasProfileClangInstr())
42*0b57cec5SDimitry Andric     FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
43*0b57cec5SDimitry Andric }
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric void CodeGenPGO::setFuncName(llvm::Function *Fn) {
46*0b57cec5SDimitry Andric   setFuncName(Fn->getName(), Fn->getLinkage());
47*0b57cec5SDimitry Andric   // Create PGOFuncName meta data.
48*0b57cec5SDimitry Andric   llvm::createPGOFuncNameMetadata(*Fn, FuncName);
49*0b57cec5SDimitry Andric }
50*0b57cec5SDimitry Andric 
51*0b57cec5SDimitry Andric /// The version of the PGO hash algorithm.
52*0b57cec5SDimitry Andric enum PGOHashVersion : unsigned {
53*0b57cec5SDimitry Andric   PGO_HASH_V1,
54*0b57cec5SDimitry Andric   PGO_HASH_V2,
55*0b57cec5SDimitry Andric 
56*0b57cec5SDimitry Andric   // Keep this set to the latest hash version.
57*0b57cec5SDimitry Andric   PGO_HASH_LATEST = PGO_HASH_V2
58*0b57cec5SDimitry Andric };
59*0b57cec5SDimitry Andric 
60*0b57cec5SDimitry Andric namespace {
61*0b57cec5SDimitry Andric /// Stable hasher for PGO region counters.
62*0b57cec5SDimitry Andric ///
63*0b57cec5SDimitry Andric /// PGOHash produces a stable hash of a given function's control flow.
64*0b57cec5SDimitry Andric ///
65*0b57cec5SDimitry Andric /// Changing the output of this hash will invalidate all previously generated
66*0b57cec5SDimitry Andric /// profiles -- i.e., don't do it.
67*0b57cec5SDimitry Andric ///
68*0b57cec5SDimitry Andric /// \note  When this hash does eventually change (years?), we still need to
69*0b57cec5SDimitry Andric /// support old hashes.  We'll need to pull in the version number from the
70*0b57cec5SDimitry Andric /// profile data format and use the matching hash function.
71*0b57cec5SDimitry Andric class PGOHash {
72*0b57cec5SDimitry Andric   uint64_t Working;
73*0b57cec5SDimitry Andric   unsigned Count;
74*0b57cec5SDimitry Andric   PGOHashVersion HashVersion;
75*0b57cec5SDimitry Andric   llvm::MD5 MD5;
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric   static const int NumBitsPerType = 6;
78*0b57cec5SDimitry Andric   static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
79*0b57cec5SDimitry Andric   static const unsigned TooBig = 1u << NumBitsPerType;
80*0b57cec5SDimitry Andric 
81*0b57cec5SDimitry Andric public:
82*0b57cec5SDimitry Andric   /// Hash values for AST nodes.
83*0b57cec5SDimitry Andric   ///
84*0b57cec5SDimitry Andric   /// Distinct values for AST nodes that have region counters attached.
85*0b57cec5SDimitry Andric   ///
86*0b57cec5SDimitry Andric   /// These values must be stable.  All new members must be added at the end,
87*0b57cec5SDimitry Andric   /// and no members should be removed.  Changing the enumeration value for an
88*0b57cec5SDimitry Andric   /// AST node will affect the hash of every function that contains that node.
89*0b57cec5SDimitry Andric   enum HashType : unsigned char {
90*0b57cec5SDimitry Andric     None = 0,
91*0b57cec5SDimitry Andric     LabelStmt = 1,
92*0b57cec5SDimitry Andric     WhileStmt,
93*0b57cec5SDimitry Andric     DoStmt,
94*0b57cec5SDimitry Andric     ForStmt,
95*0b57cec5SDimitry Andric     CXXForRangeStmt,
96*0b57cec5SDimitry Andric     ObjCForCollectionStmt,
97*0b57cec5SDimitry Andric     SwitchStmt,
98*0b57cec5SDimitry Andric     CaseStmt,
99*0b57cec5SDimitry Andric     DefaultStmt,
100*0b57cec5SDimitry Andric     IfStmt,
101*0b57cec5SDimitry Andric     CXXTryStmt,
102*0b57cec5SDimitry Andric     CXXCatchStmt,
103*0b57cec5SDimitry Andric     ConditionalOperator,
104*0b57cec5SDimitry Andric     BinaryOperatorLAnd,
105*0b57cec5SDimitry Andric     BinaryOperatorLOr,
106*0b57cec5SDimitry Andric     BinaryConditionalOperator,
107*0b57cec5SDimitry Andric     // The preceding values are available with PGO_HASH_V1.
108*0b57cec5SDimitry Andric 
109*0b57cec5SDimitry Andric     EndOfScope,
110*0b57cec5SDimitry Andric     IfThenBranch,
111*0b57cec5SDimitry Andric     IfElseBranch,
112*0b57cec5SDimitry Andric     GotoStmt,
113*0b57cec5SDimitry Andric     IndirectGotoStmt,
114*0b57cec5SDimitry Andric     BreakStmt,
115*0b57cec5SDimitry Andric     ContinueStmt,
116*0b57cec5SDimitry Andric     ReturnStmt,
117*0b57cec5SDimitry Andric     ThrowExpr,
118*0b57cec5SDimitry Andric     UnaryOperatorLNot,
119*0b57cec5SDimitry Andric     BinaryOperatorLT,
120*0b57cec5SDimitry Andric     BinaryOperatorGT,
121*0b57cec5SDimitry Andric     BinaryOperatorLE,
122*0b57cec5SDimitry Andric     BinaryOperatorGE,
123*0b57cec5SDimitry Andric     BinaryOperatorEQ,
124*0b57cec5SDimitry Andric     BinaryOperatorNE,
125*0b57cec5SDimitry Andric     // The preceding values are available with PGO_HASH_V2.
126*0b57cec5SDimitry Andric 
127*0b57cec5SDimitry Andric     // Keep this last.  It's for the static assert that follows.
128*0b57cec5SDimitry Andric     LastHashType
129*0b57cec5SDimitry Andric   };
130*0b57cec5SDimitry Andric   static_assert(LastHashType <= TooBig, "Too many types in HashType");
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric   PGOHash(PGOHashVersion HashVersion)
133*0b57cec5SDimitry Andric       : Working(0), Count(0), HashVersion(HashVersion), MD5() {}
134*0b57cec5SDimitry Andric   void combine(HashType Type);
135*0b57cec5SDimitry Andric   uint64_t finalize();
136*0b57cec5SDimitry Andric   PGOHashVersion getHashVersion() const { return HashVersion; }
137*0b57cec5SDimitry Andric };
138*0b57cec5SDimitry Andric const int PGOHash::NumBitsPerType;
139*0b57cec5SDimitry Andric const unsigned PGOHash::NumTypesPerWord;
140*0b57cec5SDimitry Andric const unsigned PGOHash::TooBig;
141*0b57cec5SDimitry Andric 
142*0b57cec5SDimitry Andric /// Get the PGO hash version used in the given indexed profile.
143*0b57cec5SDimitry Andric static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
144*0b57cec5SDimitry Andric                                         CodeGenModule &CGM) {
145*0b57cec5SDimitry Andric   if (PGOReader->getVersion() <= 4)
146*0b57cec5SDimitry Andric     return PGO_HASH_V1;
147*0b57cec5SDimitry Andric   return PGO_HASH_V2;
148*0b57cec5SDimitry Andric }
149*0b57cec5SDimitry Andric 
150*0b57cec5SDimitry Andric /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
151*0b57cec5SDimitry Andric struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
152*0b57cec5SDimitry Andric   using Base = RecursiveASTVisitor<MapRegionCounters>;
153*0b57cec5SDimitry Andric 
154*0b57cec5SDimitry Andric   /// The next counter value to assign.
155*0b57cec5SDimitry Andric   unsigned NextCounter;
156*0b57cec5SDimitry Andric   /// The function hash.
157*0b57cec5SDimitry Andric   PGOHash Hash;
158*0b57cec5SDimitry Andric   /// The map of statements to counters.
159*0b57cec5SDimitry Andric   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
160*0b57cec5SDimitry Andric 
161*0b57cec5SDimitry Andric   MapRegionCounters(PGOHashVersion HashVersion,
162*0b57cec5SDimitry Andric                     llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
163*0b57cec5SDimitry Andric       : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap) {}
164*0b57cec5SDimitry Andric 
165*0b57cec5SDimitry Andric   // Blocks and lambdas are handled as separate functions, so we need not
166*0b57cec5SDimitry Andric   // traverse them in the parent context.
167*0b57cec5SDimitry Andric   bool TraverseBlockExpr(BlockExpr *BE) { return true; }
168*0b57cec5SDimitry Andric   bool TraverseLambdaExpr(LambdaExpr *LE) {
169*0b57cec5SDimitry Andric     // Traverse the captures, but not the body.
170480093f4SDimitry Andric     for (auto C : zip(LE->captures(), LE->capture_inits()))
171*0b57cec5SDimitry Andric       TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
172*0b57cec5SDimitry Andric     return true;
173*0b57cec5SDimitry Andric   }
174*0b57cec5SDimitry Andric   bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric   bool VisitDecl(const Decl *D) {
177*0b57cec5SDimitry Andric     switch (D->getKind()) {
178*0b57cec5SDimitry Andric     default:
179*0b57cec5SDimitry Andric       break;
180*0b57cec5SDimitry Andric     case Decl::Function:
181*0b57cec5SDimitry Andric     case Decl::CXXMethod:
182*0b57cec5SDimitry Andric     case Decl::CXXConstructor:
183*0b57cec5SDimitry Andric     case Decl::CXXDestructor:
184*0b57cec5SDimitry Andric     case Decl::CXXConversion:
185*0b57cec5SDimitry Andric     case Decl::ObjCMethod:
186*0b57cec5SDimitry Andric     case Decl::Block:
187*0b57cec5SDimitry Andric     case Decl::Captured:
188*0b57cec5SDimitry Andric       CounterMap[D->getBody()] = NextCounter++;
189*0b57cec5SDimitry Andric       break;
190*0b57cec5SDimitry Andric     }
191*0b57cec5SDimitry Andric     return true;
192*0b57cec5SDimitry Andric   }
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric   /// If \p S gets a fresh counter, update the counter mappings. Return the
195*0b57cec5SDimitry Andric   /// V1 hash of \p S.
196*0b57cec5SDimitry Andric   PGOHash::HashType updateCounterMappings(Stmt *S) {
197*0b57cec5SDimitry Andric     auto Type = getHashType(PGO_HASH_V1, S);
198*0b57cec5SDimitry Andric     if (Type != PGOHash::None)
199*0b57cec5SDimitry Andric       CounterMap[S] = NextCounter++;
200*0b57cec5SDimitry Andric     return Type;
201*0b57cec5SDimitry Andric   }
202*0b57cec5SDimitry Andric 
203*0b57cec5SDimitry Andric   /// Include \p S in the function hash.
204*0b57cec5SDimitry Andric   bool VisitStmt(Stmt *S) {
205*0b57cec5SDimitry Andric     auto Type = updateCounterMappings(S);
206*0b57cec5SDimitry Andric     if (Hash.getHashVersion() != PGO_HASH_V1)
207*0b57cec5SDimitry Andric       Type = getHashType(Hash.getHashVersion(), S);
208*0b57cec5SDimitry Andric     if (Type != PGOHash::None)
209*0b57cec5SDimitry Andric       Hash.combine(Type);
210*0b57cec5SDimitry Andric     return true;
211*0b57cec5SDimitry Andric   }
212*0b57cec5SDimitry Andric 
213*0b57cec5SDimitry Andric   bool TraverseIfStmt(IfStmt *If) {
214*0b57cec5SDimitry Andric     // If we used the V1 hash, use the default traversal.
215*0b57cec5SDimitry Andric     if (Hash.getHashVersion() == PGO_HASH_V1)
216*0b57cec5SDimitry Andric       return Base::TraverseIfStmt(If);
217*0b57cec5SDimitry Andric 
218*0b57cec5SDimitry Andric     // Otherwise, keep track of which branch we're in while traversing.
219*0b57cec5SDimitry Andric     VisitStmt(If);
220*0b57cec5SDimitry Andric     for (Stmt *CS : If->children()) {
221*0b57cec5SDimitry Andric       if (!CS)
222*0b57cec5SDimitry Andric         continue;
223*0b57cec5SDimitry Andric       if (CS == If->getThen())
224*0b57cec5SDimitry Andric         Hash.combine(PGOHash::IfThenBranch);
225*0b57cec5SDimitry Andric       else if (CS == If->getElse())
226*0b57cec5SDimitry Andric         Hash.combine(PGOHash::IfElseBranch);
227*0b57cec5SDimitry Andric       TraverseStmt(CS);
228*0b57cec5SDimitry Andric     }
229*0b57cec5SDimitry Andric     Hash.combine(PGOHash::EndOfScope);
230*0b57cec5SDimitry Andric     return true;
231*0b57cec5SDimitry Andric   }
232*0b57cec5SDimitry Andric 
233*0b57cec5SDimitry Andric // If the statement type \p N is nestable, and its nesting impacts profile
234*0b57cec5SDimitry Andric // stability, define a custom traversal which tracks the end of the statement
235*0b57cec5SDimitry Andric // in the hash (provided we're not using the V1 hash).
236*0b57cec5SDimitry Andric #define DEFINE_NESTABLE_TRAVERSAL(N)                                           \
237*0b57cec5SDimitry Andric   bool Traverse##N(N *S) {                                                     \
238*0b57cec5SDimitry Andric     Base::Traverse##N(S);                                                      \
239*0b57cec5SDimitry Andric     if (Hash.getHashVersion() != PGO_HASH_V1)                                  \
240*0b57cec5SDimitry Andric       Hash.combine(PGOHash::EndOfScope);                                       \
241*0b57cec5SDimitry Andric     return true;                                                               \
242*0b57cec5SDimitry Andric   }
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
245*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(DoStmt)
246*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(ForStmt)
247*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
248*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
249*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
250*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric   /// Get version \p HashVersion of the PGO hash for \p S.
253*0b57cec5SDimitry Andric   PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
254*0b57cec5SDimitry Andric     switch (S->getStmtClass()) {
255*0b57cec5SDimitry Andric     default:
256*0b57cec5SDimitry Andric       break;
257*0b57cec5SDimitry Andric     case Stmt::LabelStmtClass:
258*0b57cec5SDimitry Andric       return PGOHash::LabelStmt;
259*0b57cec5SDimitry Andric     case Stmt::WhileStmtClass:
260*0b57cec5SDimitry Andric       return PGOHash::WhileStmt;
261*0b57cec5SDimitry Andric     case Stmt::DoStmtClass:
262*0b57cec5SDimitry Andric       return PGOHash::DoStmt;
263*0b57cec5SDimitry Andric     case Stmt::ForStmtClass:
264*0b57cec5SDimitry Andric       return PGOHash::ForStmt;
265*0b57cec5SDimitry Andric     case Stmt::CXXForRangeStmtClass:
266*0b57cec5SDimitry Andric       return PGOHash::CXXForRangeStmt;
267*0b57cec5SDimitry Andric     case Stmt::ObjCForCollectionStmtClass:
268*0b57cec5SDimitry Andric       return PGOHash::ObjCForCollectionStmt;
269*0b57cec5SDimitry Andric     case Stmt::SwitchStmtClass:
270*0b57cec5SDimitry Andric       return PGOHash::SwitchStmt;
271*0b57cec5SDimitry Andric     case Stmt::CaseStmtClass:
272*0b57cec5SDimitry Andric       return PGOHash::CaseStmt;
273*0b57cec5SDimitry Andric     case Stmt::DefaultStmtClass:
274*0b57cec5SDimitry Andric       return PGOHash::DefaultStmt;
275*0b57cec5SDimitry Andric     case Stmt::IfStmtClass:
276*0b57cec5SDimitry Andric       return PGOHash::IfStmt;
277*0b57cec5SDimitry Andric     case Stmt::CXXTryStmtClass:
278*0b57cec5SDimitry Andric       return PGOHash::CXXTryStmt;
279*0b57cec5SDimitry Andric     case Stmt::CXXCatchStmtClass:
280*0b57cec5SDimitry Andric       return PGOHash::CXXCatchStmt;
281*0b57cec5SDimitry Andric     case Stmt::ConditionalOperatorClass:
282*0b57cec5SDimitry Andric       return PGOHash::ConditionalOperator;
283*0b57cec5SDimitry Andric     case Stmt::BinaryConditionalOperatorClass:
284*0b57cec5SDimitry Andric       return PGOHash::BinaryConditionalOperator;
285*0b57cec5SDimitry Andric     case Stmt::BinaryOperatorClass: {
286*0b57cec5SDimitry Andric       const BinaryOperator *BO = cast<BinaryOperator>(S);
287*0b57cec5SDimitry Andric       if (BO->getOpcode() == BO_LAnd)
288*0b57cec5SDimitry Andric         return PGOHash::BinaryOperatorLAnd;
289*0b57cec5SDimitry Andric       if (BO->getOpcode() == BO_LOr)
290*0b57cec5SDimitry Andric         return PGOHash::BinaryOperatorLOr;
291*0b57cec5SDimitry Andric       if (HashVersion == PGO_HASH_V2) {
292*0b57cec5SDimitry Andric         switch (BO->getOpcode()) {
293*0b57cec5SDimitry Andric         default:
294*0b57cec5SDimitry Andric           break;
295*0b57cec5SDimitry Andric         case BO_LT:
296*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorLT;
297*0b57cec5SDimitry Andric         case BO_GT:
298*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorGT;
299*0b57cec5SDimitry Andric         case BO_LE:
300*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorLE;
301*0b57cec5SDimitry Andric         case BO_GE:
302*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorGE;
303*0b57cec5SDimitry Andric         case BO_EQ:
304*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorEQ;
305*0b57cec5SDimitry Andric         case BO_NE:
306*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorNE;
307*0b57cec5SDimitry Andric         }
308*0b57cec5SDimitry Andric       }
309*0b57cec5SDimitry Andric       break;
310*0b57cec5SDimitry Andric     }
311*0b57cec5SDimitry Andric     }
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric     if (HashVersion == PGO_HASH_V2) {
314*0b57cec5SDimitry Andric       switch (S->getStmtClass()) {
315*0b57cec5SDimitry Andric       default:
316*0b57cec5SDimitry Andric         break;
317*0b57cec5SDimitry Andric       case Stmt::GotoStmtClass:
318*0b57cec5SDimitry Andric         return PGOHash::GotoStmt;
319*0b57cec5SDimitry Andric       case Stmt::IndirectGotoStmtClass:
320*0b57cec5SDimitry Andric         return PGOHash::IndirectGotoStmt;
321*0b57cec5SDimitry Andric       case Stmt::BreakStmtClass:
322*0b57cec5SDimitry Andric         return PGOHash::BreakStmt;
323*0b57cec5SDimitry Andric       case Stmt::ContinueStmtClass:
324*0b57cec5SDimitry Andric         return PGOHash::ContinueStmt;
325*0b57cec5SDimitry Andric       case Stmt::ReturnStmtClass:
326*0b57cec5SDimitry Andric         return PGOHash::ReturnStmt;
327*0b57cec5SDimitry Andric       case Stmt::CXXThrowExprClass:
328*0b57cec5SDimitry Andric         return PGOHash::ThrowExpr;
329*0b57cec5SDimitry Andric       case Stmt::UnaryOperatorClass: {
330*0b57cec5SDimitry Andric         const UnaryOperator *UO = cast<UnaryOperator>(S);
331*0b57cec5SDimitry Andric         if (UO->getOpcode() == UO_LNot)
332*0b57cec5SDimitry Andric           return PGOHash::UnaryOperatorLNot;
333*0b57cec5SDimitry Andric         break;
334*0b57cec5SDimitry Andric       }
335*0b57cec5SDimitry Andric       }
336*0b57cec5SDimitry Andric     }
337*0b57cec5SDimitry Andric 
338*0b57cec5SDimitry Andric     return PGOHash::None;
339*0b57cec5SDimitry Andric   }
340*0b57cec5SDimitry Andric };
341*0b57cec5SDimitry Andric 
342*0b57cec5SDimitry Andric /// A StmtVisitor that propagates the raw counts through the AST and
343*0b57cec5SDimitry Andric /// records the count at statements where the value may change.
344*0b57cec5SDimitry Andric struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
345*0b57cec5SDimitry Andric   /// PGO state.
346*0b57cec5SDimitry Andric   CodeGenPGO &PGO;
347*0b57cec5SDimitry Andric 
348*0b57cec5SDimitry Andric   /// A flag that is set when the current count should be recorded on the
349*0b57cec5SDimitry Andric   /// next statement, such as at the exit of a loop.
350*0b57cec5SDimitry Andric   bool RecordNextStmtCount;
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric   /// The count at the current location in the traversal.
353*0b57cec5SDimitry Andric   uint64_t CurrentCount;
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric   /// The map of statements to count values.
356*0b57cec5SDimitry Andric   llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
357*0b57cec5SDimitry Andric 
358*0b57cec5SDimitry Andric   /// BreakContinueStack - Keep counts of breaks and continues inside loops.
359*0b57cec5SDimitry Andric   struct BreakContinue {
360*0b57cec5SDimitry Andric     uint64_t BreakCount;
361*0b57cec5SDimitry Andric     uint64_t ContinueCount;
362*0b57cec5SDimitry Andric     BreakContinue() : BreakCount(0), ContinueCount(0) {}
363*0b57cec5SDimitry Andric   };
364*0b57cec5SDimitry Andric   SmallVector<BreakContinue, 8> BreakContinueStack;
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
367*0b57cec5SDimitry Andric                       CodeGenPGO &PGO)
368*0b57cec5SDimitry Andric       : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric   void RecordStmtCount(const Stmt *S) {
371*0b57cec5SDimitry Andric     if (RecordNextStmtCount) {
372*0b57cec5SDimitry Andric       CountMap[S] = CurrentCount;
373*0b57cec5SDimitry Andric       RecordNextStmtCount = false;
374*0b57cec5SDimitry Andric     }
375*0b57cec5SDimitry Andric   }
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric   /// Set and return the current count.
378*0b57cec5SDimitry Andric   uint64_t setCount(uint64_t Count) {
379*0b57cec5SDimitry Andric     CurrentCount = Count;
380*0b57cec5SDimitry Andric     return Count;
381*0b57cec5SDimitry Andric   }
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric   void VisitStmt(const Stmt *S) {
384*0b57cec5SDimitry Andric     RecordStmtCount(S);
385*0b57cec5SDimitry Andric     for (const Stmt *Child : S->children())
386*0b57cec5SDimitry Andric       if (Child)
387*0b57cec5SDimitry Andric         this->Visit(Child);
388*0b57cec5SDimitry Andric   }
389*0b57cec5SDimitry Andric 
390*0b57cec5SDimitry Andric   void VisitFunctionDecl(const FunctionDecl *D) {
391*0b57cec5SDimitry Andric     // Counter tracks entry to the function body.
392*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
393*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
394*0b57cec5SDimitry Andric     Visit(D->getBody());
395*0b57cec5SDimitry Andric   }
396*0b57cec5SDimitry Andric 
397*0b57cec5SDimitry Andric   // Skip lambda expressions. We visit these as FunctionDecls when we're
398*0b57cec5SDimitry Andric   // generating them and aren't interested in the body when generating a
399*0b57cec5SDimitry Andric   // parent context.
400*0b57cec5SDimitry Andric   void VisitLambdaExpr(const LambdaExpr *LE) {}
401*0b57cec5SDimitry Andric 
402*0b57cec5SDimitry Andric   void VisitCapturedDecl(const CapturedDecl *D) {
403*0b57cec5SDimitry Andric     // Counter tracks entry to the capture body.
404*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
405*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
406*0b57cec5SDimitry Andric     Visit(D->getBody());
407*0b57cec5SDimitry Andric   }
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric   void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
410*0b57cec5SDimitry Andric     // Counter tracks entry to the method body.
411*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
412*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
413*0b57cec5SDimitry Andric     Visit(D->getBody());
414*0b57cec5SDimitry Andric   }
415*0b57cec5SDimitry Andric 
416*0b57cec5SDimitry Andric   void VisitBlockDecl(const BlockDecl *D) {
417*0b57cec5SDimitry Andric     // Counter tracks entry to the block body.
418*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
419*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
420*0b57cec5SDimitry Andric     Visit(D->getBody());
421*0b57cec5SDimitry Andric   }
422*0b57cec5SDimitry Andric 
423*0b57cec5SDimitry Andric   void VisitReturnStmt(const ReturnStmt *S) {
424*0b57cec5SDimitry Andric     RecordStmtCount(S);
425*0b57cec5SDimitry Andric     if (S->getRetValue())
426*0b57cec5SDimitry Andric       Visit(S->getRetValue());
427*0b57cec5SDimitry Andric     CurrentCount = 0;
428*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
429*0b57cec5SDimitry Andric   }
430*0b57cec5SDimitry Andric 
431*0b57cec5SDimitry Andric   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
432*0b57cec5SDimitry Andric     RecordStmtCount(E);
433*0b57cec5SDimitry Andric     if (E->getSubExpr())
434*0b57cec5SDimitry Andric       Visit(E->getSubExpr());
435*0b57cec5SDimitry Andric     CurrentCount = 0;
436*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
437*0b57cec5SDimitry Andric   }
438*0b57cec5SDimitry Andric 
439*0b57cec5SDimitry Andric   void VisitGotoStmt(const GotoStmt *S) {
440*0b57cec5SDimitry Andric     RecordStmtCount(S);
441*0b57cec5SDimitry Andric     CurrentCount = 0;
442*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
443*0b57cec5SDimitry Andric   }
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   void VisitLabelStmt(const LabelStmt *S) {
446*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
447*0b57cec5SDimitry Andric     // Counter tracks the block following the label.
448*0b57cec5SDimitry Andric     uint64_t BlockCount = setCount(PGO.getRegionCount(S));
449*0b57cec5SDimitry Andric     CountMap[S] = BlockCount;
450*0b57cec5SDimitry Andric     Visit(S->getSubStmt());
451*0b57cec5SDimitry Andric   }
452*0b57cec5SDimitry Andric 
453*0b57cec5SDimitry Andric   void VisitBreakStmt(const BreakStmt *S) {
454*0b57cec5SDimitry Andric     RecordStmtCount(S);
455*0b57cec5SDimitry Andric     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
456*0b57cec5SDimitry Andric     BreakContinueStack.back().BreakCount += CurrentCount;
457*0b57cec5SDimitry Andric     CurrentCount = 0;
458*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
459*0b57cec5SDimitry Andric   }
460*0b57cec5SDimitry Andric 
461*0b57cec5SDimitry Andric   void VisitContinueStmt(const ContinueStmt *S) {
462*0b57cec5SDimitry Andric     RecordStmtCount(S);
463*0b57cec5SDimitry Andric     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
464*0b57cec5SDimitry Andric     BreakContinueStack.back().ContinueCount += CurrentCount;
465*0b57cec5SDimitry Andric     CurrentCount = 0;
466*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
467*0b57cec5SDimitry Andric   }
468*0b57cec5SDimitry Andric 
469*0b57cec5SDimitry Andric   void VisitWhileStmt(const WhileStmt *S) {
470*0b57cec5SDimitry Andric     RecordStmtCount(S);
471*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
472*0b57cec5SDimitry Andric 
473*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
474*0b57cec5SDimitry Andric     // Visit the body region first so the break/continue adjustments can be
475*0b57cec5SDimitry Andric     // included when visiting the condition.
476*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
477*0b57cec5SDimitry Andric     CountMap[S->getBody()] = CurrentCount;
478*0b57cec5SDimitry Andric     Visit(S->getBody());
479*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
480*0b57cec5SDimitry Andric 
481*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition. The count
482*0b57cec5SDimitry Andric     // at the start of the condition is the sum of the incoming edges,
483*0b57cec5SDimitry Andric     // the backedge from the end of the loop body, and the edges from
484*0b57cec5SDimitry Andric     // continue statements.
485*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
486*0b57cec5SDimitry Andric     uint64_t CondCount =
487*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
488*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
489*0b57cec5SDimitry Andric     Visit(S->getCond());
490*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
491*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
492*0b57cec5SDimitry Andric   }
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric   void VisitDoStmt(const DoStmt *S) {
495*0b57cec5SDimitry Andric     RecordStmtCount(S);
496*0b57cec5SDimitry Andric     uint64_t LoopCount = PGO.getRegionCount(S);
497*0b57cec5SDimitry Andric 
498*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
499*0b57cec5SDimitry Andric     // The count doesn't include the fallthrough from the parent scope. Add it.
500*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(LoopCount + CurrentCount);
501*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
502*0b57cec5SDimitry Andric     Visit(S->getBody());
503*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
506*0b57cec5SDimitry Andric     // The count at the start of the condition is equal to the count at the
507*0b57cec5SDimitry Andric     // end of the body, plus any continues.
508*0b57cec5SDimitry Andric     uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
509*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
510*0b57cec5SDimitry Andric     Visit(S->getCond());
511*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - LoopCount);
512*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
513*0b57cec5SDimitry Andric   }
514*0b57cec5SDimitry Andric 
515*0b57cec5SDimitry Andric   void VisitForStmt(const ForStmt *S) {
516*0b57cec5SDimitry Andric     RecordStmtCount(S);
517*0b57cec5SDimitry Andric     if (S->getInit())
518*0b57cec5SDimitry Andric       Visit(S->getInit());
519*0b57cec5SDimitry Andric 
520*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
523*0b57cec5SDimitry Andric     // Visit the body region first. (This is basically the same as a while
524*0b57cec5SDimitry Andric     // loop; see further comments in VisitWhileStmt.)
525*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
526*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
527*0b57cec5SDimitry Andric     Visit(S->getBody());
528*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
529*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric     // The increment is essentially part of the body but it needs to include
532*0b57cec5SDimitry Andric     // the count for all the continue statements.
533*0b57cec5SDimitry Andric     if (S->getInc()) {
534*0b57cec5SDimitry Andric       uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
535*0b57cec5SDimitry Andric       CountMap[S->getInc()] = IncCount;
536*0b57cec5SDimitry Andric       Visit(S->getInc());
537*0b57cec5SDimitry Andric     }
538*0b57cec5SDimitry Andric 
539*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition.
540*0b57cec5SDimitry Andric     uint64_t CondCount =
541*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
542*0b57cec5SDimitry Andric     if (S->getCond()) {
543*0b57cec5SDimitry Andric       CountMap[S->getCond()] = CondCount;
544*0b57cec5SDimitry Andric       Visit(S->getCond());
545*0b57cec5SDimitry Andric     }
546*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
547*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
548*0b57cec5SDimitry Andric   }
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
551*0b57cec5SDimitry Andric     RecordStmtCount(S);
552*0b57cec5SDimitry Andric     if (S->getInit())
553*0b57cec5SDimitry Andric       Visit(S->getInit());
554*0b57cec5SDimitry Andric     Visit(S->getLoopVarStmt());
555*0b57cec5SDimitry Andric     Visit(S->getRangeStmt());
556*0b57cec5SDimitry Andric     Visit(S->getBeginStmt());
557*0b57cec5SDimitry Andric     Visit(S->getEndStmt());
558*0b57cec5SDimitry Andric 
559*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
560*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
561*0b57cec5SDimitry Andric     // Visit the body region first. (This is basically the same as a while
562*0b57cec5SDimitry Andric     // loop; see further comments in VisitWhileStmt.)
563*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
564*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
565*0b57cec5SDimitry Andric     Visit(S->getBody());
566*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
567*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
568*0b57cec5SDimitry Andric 
569*0b57cec5SDimitry Andric     // The increment is essentially part of the body but it needs to include
570*0b57cec5SDimitry Andric     // the count for all the continue statements.
571*0b57cec5SDimitry Andric     uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
572*0b57cec5SDimitry Andric     CountMap[S->getInc()] = IncCount;
573*0b57cec5SDimitry Andric     Visit(S->getInc());
574*0b57cec5SDimitry Andric 
575*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition.
576*0b57cec5SDimitry Andric     uint64_t CondCount =
577*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
578*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
579*0b57cec5SDimitry Andric     Visit(S->getCond());
580*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
581*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
582*0b57cec5SDimitry Andric   }
583*0b57cec5SDimitry Andric 
584*0b57cec5SDimitry Andric   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
585*0b57cec5SDimitry Andric     RecordStmtCount(S);
586*0b57cec5SDimitry Andric     Visit(S->getElement());
587*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
588*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
589*0b57cec5SDimitry Andric     // Counter tracks the body of the loop.
590*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
591*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
592*0b57cec5SDimitry Andric     Visit(S->getBody());
593*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
594*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
595*0b57cec5SDimitry Andric 
596*0b57cec5SDimitry Andric     setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
597*0b57cec5SDimitry Andric              BodyCount);
598*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
599*0b57cec5SDimitry Andric   }
600*0b57cec5SDimitry Andric 
601*0b57cec5SDimitry Andric   void VisitSwitchStmt(const SwitchStmt *S) {
602*0b57cec5SDimitry Andric     RecordStmtCount(S);
603*0b57cec5SDimitry Andric     if (S->getInit())
604*0b57cec5SDimitry Andric       Visit(S->getInit());
605*0b57cec5SDimitry Andric     Visit(S->getCond());
606*0b57cec5SDimitry Andric     CurrentCount = 0;
607*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
608*0b57cec5SDimitry Andric     Visit(S->getBody());
609*0b57cec5SDimitry Andric     // If the switch is inside a loop, add the continue counts.
610*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
611*0b57cec5SDimitry Andric     if (!BreakContinueStack.empty())
612*0b57cec5SDimitry Andric       BreakContinueStack.back().ContinueCount += BC.ContinueCount;
613*0b57cec5SDimitry Andric     // Counter tracks the exit block of the switch.
614*0b57cec5SDimitry Andric     setCount(PGO.getRegionCount(S));
615*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
616*0b57cec5SDimitry Andric   }
617*0b57cec5SDimitry Andric 
618*0b57cec5SDimitry Andric   void VisitSwitchCase(const SwitchCase *S) {
619*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
620*0b57cec5SDimitry Andric     // Counter for this particular case. This counts only jumps from the
621*0b57cec5SDimitry Andric     // switch header and does not include fallthrough from the case before
622*0b57cec5SDimitry Andric     // this one.
623*0b57cec5SDimitry Andric     uint64_t CaseCount = PGO.getRegionCount(S);
624*0b57cec5SDimitry Andric     setCount(CurrentCount + CaseCount);
625*0b57cec5SDimitry Andric     // We need the count without fallthrough in the mapping, so it's more useful
626*0b57cec5SDimitry Andric     // for branch probabilities.
627*0b57cec5SDimitry Andric     CountMap[S] = CaseCount;
628*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
629*0b57cec5SDimitry Andric     Visit(S->getSubStmt());
630*0b57cec5SDimitry Andric   }
631*0b57cec5SDimitry Andric 
632*0b57cec5SDimitry Andric   void VisitIfStmt(const IfStmt *S) {
633*0b57cec5SDimitry Andric     RecordStmtCount(S);
634*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
635*0b57cec5SDimitry Andric     if (S->getInit())
636*0b57cec5SDimitry Andric       Visit(S->getInit());
637*0b57cec5SDimitry Andric     Visit(S->getCond());
638*0b57cec5SDimitry Andric 
639*0b57cec5SDimitry Andric     // Counter tracks the "then" part of an if statement. The count for
640*0b57cec5SDimitry Andric     // the "else" part, if it exists, will be calculated from this counter.
641*0b57cec5SDimitry Andric     uint64_t ThenCount = setCount(PGO.getRegionCount(S));
642*0b57cec5SDimitry Andric     CountMap[S->getThen()] = ThenCount;
643*0b57cec5SDimitry Andric     Visit(S->getThen());
644*0b57cec5SDimitry Andric     uint64_t OutCount = CurrentCount;
645*0b57cec5SDimitry Andric 
646*0b57cec5SDimitry Andric     uint64_t ElseCount = ParentCount - ThenCount;
647*0b57cec5SDimitry Andric     if (S->getElse()) {
648*0b57cec5SDimitry Andric       setCount(ElseCount);
649*0b57cec5SDimitry Andric       CountMap[S->getElse()] = ElseCount;
650*0b57cec5SDimitry Andric       Visit(S->getElse());
651*0b57cec5SDimitry Andric       OutCount += CurrentCount;
652*0b57cec5SDimitry Andric     } else
653*0b57cec5SDimitry Andric       OutCount += ElseCount;
654*0b57cec5SDimitry Andric     setCount(OutCount);
655*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
656*0b57cec5SDimitry Andric   }
657*0b57cec5SDimitry Andric 
658*0b57cec5SDimitry Andric   void VisitCXXTryStmt(const CXXTryStmt *S) {
659*0b57cec5SDimitry Andric     RecordStmtCount(S);
660*0b57cec5SDimitry Andric     Visit(S->getTryBlock());
661*0b57cec5SDimitry Andric     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
662*0b57cec5SDimitry Andric       Visit(S->getHandler(I));
663*0b57cec5SDimitry Andric     // Counter tracks the continuation block of the try statement.
664*0b57cec5SDimitry Andric     setCount(PGO.getRegionCount(S));
665*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
666*0b57cec5SDimitry Andric   }
667*0b57cec5SDimitry Andric 
668*0b57cec5SDimitry Andric   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
669*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
670*0b57cec5SDimitry Andric     // Counter tracks the catch statement's handler block.
671*0b57cec5SDimitry Andric     uint64_t CatchCount = setCount(PGO.getRegionCount(S));
672*0b57cec5SDimitry Andric     CountMap[S] = CatchCount;
673*0b57cec5SDimitry Andric     Visit(S->getHandlerBlock());
674*0b57cec5SDimitry Andric   }
675*0b57cec5SDimitry Andric 
676*0b57cec5SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
677*0b57cec5SDimitry Andric     RecordStmtCount(E);
678*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
679*0b57cec5SDimitry Andric     Visit(E->getCond());
680*0b57cec5SDimitry Andric 
681*0b57cec5SDimitry Andric     // Counter tracks the "true" part of a conditional operator. The
682*0b57cec5SDimitry Andric     // count in the "false" part will be calculated from this counter.
683*0b57cec5SDimitry Andric     uint64_t TrueCount = setCount(PGO.getRegionCount(E));
684*0b57cec5SDimitry Andric     CountMap[E->getTrueExpr()] = TrueCount;
685*0b57cec5SDimitry Andric     Visit(E->getTrueExpr());
686*0b57cec5SDimitry Andric     uint64_t OutCount = CurrentCount;
687*0b57cec5SDimitry Andric 
688*0b57cec5SDimitry Andric     uint64_t FalseCount = setCount(ParentCount - TrueCount);
689*0b57cec5SDimitry Andric     CountMap[E->getFalseExpr()] = FalseCount;
690*0b57cec5SDimitry Andric     Visit(E->getFalseExpr());
691*0b57cec5SDimitry Andric     OutCount += CurrentCount;
692*0b57cec5SDimitry Andric 
693*0b57cec5SDimitry Andric     setCount(OutCount);
694*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
695*0b57cec5SDimitry Andric   }
696*0b57cec5SDimitry Andric 
697*0b57cec5SDimitry Andric   void VisitBinLAnd(const BinaryOperator *E) {
698*0b57cec5SDimitry Andric     RecordStmtCount(E);
699*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
700*0b57cec5SDimitry Andric     Visit(E->getLHS());
701*0b57cec5SDimitry Andric     // Counter tracks the right hand side of a logical and operator.
702*0b57cec5SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
703*0b57cec5SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
704*0b57cec5SDimitry Andric     Visit(E->getRHS());
705*0b57cec5SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
706*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
707*0b57cec5SDimitry Andric   }
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric   void VisitBinLOr(const BinaryOperator *E) {
710*0b57cec5SDimitry Andric     RecordStmtCount(E);
711*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
712*0b57cec5SDimitry Andric     Visit(E->getLHS());
713*0b57cec5SDimitry Andric     // Counter tracks the right hand side of a logical or operator.
714*0b57cec5SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
715*0b57cec5SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
716*0b57cec5SDimitry Andric     Visit(E->getRHS());
717*0b57cec5SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
718*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
719*0b57cec5SDimitry Andric   }
720*0b57cec5SDimitry Andric };
721*0b57cec5SDimitry Andric } // end anonymous namespace
722*0b57cec5SDimitry Andric 
723*0b57cec5SDimitry Andric void PGOHash::combine(HashType Type) {
724*0b57cec5SDimitry Andric   // Check that we never combine 0 and only have six bits.
725*0b57cec5SDimitry Andric   assert(Type && "Hash is invalid: unexpected type 0");
726*0b57cec5SDimitry Andric   assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   // Pass through MD5 if enough work has built up.
729*0b57cec5SDimitry Andric   if (Count && Count % NumTypesPerWord == 0) {
730*0b57cec5SDimitry Andric     using namespace llvm::support;
731*0b57cec5SDimitry Andric     uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
732*0b57cec5SDimitry Andric     MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
733*0b57cec5SDimitry Andric     Working = 0;
734*0b57cec5SDimitry Andric   }
735*0b57cec5SDimitry Andric 
736*0b57cec5SDimitry Andric   // Accumulate the current type.
737*0b57cec5SDimitry Andric   ++Count;
738*0b57cec5SDimitry Andric   Working = Working << NumBitsPerType | Type;
739*0b57cec5SDimitry Andric }
740*0b57cec5SDimitry Andric 
741*0b57cec5SDimitry Andric uint64_t PGOHash::finalize() {
742*0b57cec5SDimitry Andric   // Use Working as the hash directly if we never used MD5.
743*0b57cec5SDimitry Andric   if (Count <= NumTypesPerWord)
744*0b57cec5SDimitry Andric     // No need to byte swap here, since none of the math was endian-dependent.
745*0b57cec5SDimitry Andric     // This number will be byte-swapped as required on endianness transitions,
746*0b57cec5SDimitry Andric     // so we will see the same value on the other side.
747*0b57cec5SDimitry Andric     return Working;
748*0b57cec5SDimitry Andric 
749*0b57cec5SDimitry Andric   // Check for remaining work in Working.
750*0b57cec5SDimitry Andric   if (Working)
751*0b57cec5SDimitry Andric     MD5.update(Working);
752*0b57cec5SDimitry Andric 
753*0b57cec5SDimitry Andric   // Finalize the MD5 and return the hash.
754*0b57cec5SDimitry Andric   llvm::MD5::MD5Result Result;
755*0b57cec5SDimitry Andric   MD5.final(Result);
756*0b57cec5SDimitry Andric   using namespace llvm::support;
757*0b57cec5SDimitry Andric   return Result.low();
758*0b57cec5SDimitry Andric }
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
761*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
762*0b57cec5SDimitry Andric   if (!D->hasBody())
763*0b57cec5SDimitry Andric     return;
764*0b57cec5SDimitry Andric 
765*0b57cec5SDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
766*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
767*0b57cec5SDimitry Andric   if (!InstrumentRegions && !PGOReader)
768*0b57cec5SDimitry Andric     return;
769*0b57cec5SDimitry Andric   if (D->isImplicit())
770*0b57cec5SDimitry Andric     return;
771*0b57cec5SDimitry Andric   // Constructors and destructors may be represented by several functions in IR.
772*0b57cec5SDimitry Andric   // If so, instrument only base variant, others are implemented by delegation
773*0b57cec5SDimitry Andric   // to the base one, it would be counted twice otherwise.
774*0b57cec5SDimitry Andric   if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
775*0b57cec5SDimitry Andric     if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
776*0b57cec5SDimitry Andric       if (GD.getCtorType() != Ctor_Base &&
777*0b57cec5SDimitry Andric           CodeGenFunction::IsConstructorDelegationValid(CCD))
778*0b57cec5SDimitry Andric         return;
779*0b57cec5SDimitry Andric   }
780*0b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
781*0b57cec5SDimitry Andric     return;
782*0b57cec5SDimitry Andric 
783*0b57cec5SDimitry Andric   CGM.ClearUnusedCoverageMapping(D);
784*0b57cec5SDimitry Andric   setFuncName(Fn);
785*0b57cec5SDimitry Andric 
786*0b57cec5SDimitry Andric   mapRegionCounters(D);
787*0b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().CoverageMapping)
788*0b57cec5SDimitry Andric     emitCounterRegionMapping(D);
789*0b57cec5SDimitry Andric   if (PGOReader) {
790*0b57cec5SDimitry Andric     SourceManager &SM = CGM.getContext().getSourceManager();
791*0b57cec5SDimitry Andric     loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
792*0b57cec5SDimitry Andric     computeRegionCounts(D);
793*0b57cec5SDimitry Andric     applyFunctionAttributes(PGOReader, Fn);
794*0b57cec5SDimitry Andric   }
795*0b57cec5SDimitry Andric }
796*0b57cec5SDimitry Andric 
797*0b57cec5SDimitry Andric void CodeGenPGO::mapRegionCounters(const Decl *D) {
798*0b57cec5SDimitry Andric   // Use the latest hash version when inserting instrumentation, but use the
799*0b57cec5SDimitry Andric   // version in the indexed profile if we're reading PGO data.
800*0b57cec5SDimitry Andric   PGOHashVersion HashVersion = PGO_HASH_LATEST;
801*0b57cec5SDimitry Andric   if (auto *PGOReader = CGM.getPGOReader())
802*0b57cec5SDimitry Andric     HashVersion = getPGOHashVersion(PGOReader, CGM);
803*0b57cec5SDimitry Andric 
804*0b57cec5SDimitry Andric   RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
805*0b57cec5SDimitry Andric   MapRegionCounters Walker(HashVersion, *RegionCounterMap);
806*0b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
807*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
808*0b57cec5SDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
809*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
810*0b57cec5SDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
811*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
812*0b57cec5SDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
813*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
814*0b57cec5SDimitry Andric   assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
815*0b57cec5SDimitry Andric   NumRegionCounters = Walker.NextCounter;
816*0b57cec5SDimitry Andric   FunctionHash = Walker.Hash.finalize();
817*0b57cec5SDimitry Andric }
818*0b57cec5SDimitry Andric 
819*0b57cec5SDimitry Andric bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
820*0b57cec5SDimitry Andric   if (!D->getBody())
821*0b57cec5SDimitry Andric     return true;
822*0b57cec5SDimitry Andric 
823*0b57cec5SDimitry Andric   // Don't map the functions in system headers.
824*0b57cec5SDimitry Andric   const auto &SM = CGM.getContext().getSourceManager();
825*0b57cec5SDimitry Andric   auto Loc = D->getBody()->getBeginLoc();
826*0b57cec5SDimitry Andric   return SM.isInSystemHeader(Loc);
827*0b57cec5SDimitry Andric }
828*0b57cec5SDimitry Andric 
829*0b57cec5SDimitry Andric void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
830*0b57cec5SDimitry Andric   if (skipRegionMappingForDecl(D))
831*0b57cec5SDimitry Andric     return;
832*0b57cec5SDimitry Andric 
833*0b57cec5SDimitry Andric   std::string CoverageMapping;
834*0b57cec5SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
835*0b57cec5SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
836*0b57cec5SDimitry Andric                                 CGM.getContext().getSourceManager(),
837*0b57cec5SDimitry Andric                                 CGM.getLangOpts(), RegionCounterMap.get());
838*0b57cec5SDimitry Andric   MappingGen.emitCounterMapping(D, OS);
839*0b57cec5SDimitry Andric   OS.flush();
840*0b57cec5SDimitry Andric 
841*0b57cec5SDimitry Andric   if (CoverageMapping.empty())
842*0b57cec5SDimitry Andric     return;
843*0b57cec5SDimitry Andric 
844*0b57cec5SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
845*0b57cec5SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
846*0b57cec5SDimitry Andric }
847*0b57cec5SDimitry Andric 
848*0b57cec5SDimitry Andric void
849*0b57cec5SDimitry Andric CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
850*0b57cec5SDimitry Andric                                     llvm::GlobalValue::LinkageTypes Linkage) {
851*0b57cec5SDimitry Andric   if (skipRegionMappingForDecl(D))
852*0b57cec5SDimitry Andric     return;
853*0b57cec5SDimitry Andric 
854*0b57cec5SDimitry Andric   std::string CoverageMapping;
855*0b57cec5SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
856*0b57cec5SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
857*0b57cec5SDimitry Andric                                 CGM.getContext().getSourceManager(),
858*0b57cec5SDimitry Andric                                 CGM.getLangOpts());
859*0b57cec5SDimitry Andric   MappingGen.emitEmptyMapping(D, OS);
860*0b57cec5SDimitry Andric   OS.flush();
861*0b57cec5SDimitry Andric 
862*0b57cec5SDimitry Andric   if (CoverageMapping.empty())
863*0b57cec5SDimitry Andric     return;
864*0b57cec5SDimitry Andric 
865*0b57cec5SDimitry Andric   setFuncName(Name, Linkage);
866*0b57cec5SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
867*0b57cec5SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
868*0b57cec5SDimitry Andric }
869*0b57cec5SDimitry Andric 
870*0b57cec5SDimitry Andric void CodeGenPGO::computeRegionCounts(const Decl *D) {
871*0b57cec5SDimitry Andric   StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
872*0b57cec5SDimitry Andric   ComputeRegionCounts Walker(*StmtCountMap, *this);
873*0b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
874*0b57cec5SDimitry Andric     Walker.VisitFunctionDecl(FD);
875*0b57cec5SDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
876*0b57cec5SDimitry Andric     Walker.VisitObjCMethodDecl(MD);
877*0b57cec5SDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
878*0b57cec5SDimitry Andric     Walker.VisitBlockDecl(BD);
879*0b57cec5SDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
880*0b57cec5SDimitry Andric     Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
881*0b57cec5SDimitry Andric }
882*0b57cec5SDimitry Andric 
883*0b57cec5SDimitry Andric void
884*0b57cec5SDimitry Andric CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
885*0b57cec5SDimitry Andric                                     llvm::Function *Fn) {
886*0b57cec5SDimitry Andric   if (!haveRegionCounts())
887*0b57cec5SDimitry Andric     return;
888*0b57cec5SDimitry Andric 
889*0b57cec5SDimitry Andric   uint64_t FunctionCount = getRegionCount(nullptr);
890*0b57cec5SDimitry Andric   Fn->setEntryCount(FunctionCount);
891*0b57cec5SDimitry Andric }
892*0b57cec5SDimitry Andric 
893*0b57cec5SDimitry Andric void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
894*0b57cec5SDimitry Andric                                       llvm::Value *StepV) {
895*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
896*0b57cec5SDimitry Andric     return;
897*0b57cec5SDimitry Andric   if (!Builder.GetInsertBlock())
898*0b57cec5SDimitry Andric     return;
899*0b57cec5SDimitry Andric 
900*0b57cec5SDimitry Andric   unsigned Counter = (*RegionCounterMap)[S];
901*0b57cec5SDimitry Andric   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
902*0b57cec5SDimitry Andric 
903*0b57cec5SDimitry Andric   llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
904*0b57cec5SDimitry Andric                          Builder.getInt64(FunctionHash),
905*0b57cec5SDimitry Andric                          Builder.getInt32(NumRegionCounters),
906*0b57cec5SDimitry Andric                          Builder.getInt32(Counter), StepV};
907*0b57cec5SDimitry Andric   if (!StepV)
908*0b57cec5SDimitry Andric     Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
909*0b57cec5SDimitry Andric                        makeArrayRef(Args, 4));
910*0b57cec5SDimitry Andric   else
911*0b57cec5SDimitry Andric     Builder.CreateCall(
912*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
913*0b57cec5SDimitry Andric         makeArrayRef(Args));
914*0b57cec5SDimitry Andric }
915*0b57cec5SDimitry Andric 
916*0b57cec5SDimitry Andric // This method either inserts a call to the profile run-time during
917*0b57cec5SDimitry Andric // instrumentation or puts profile data into metadata for PGO use.
918*0b57cec5SDimitry Andric void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
919*0b57cec5SDimitry Andric     llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
920*0b57cec5SDimitry Andric 
921*0b57cec5SDimitry Andric   if (!EnableValueProfiling)
922*0b57cec5SDimitry Andric     return;
923*0b57cec5SDimitry Andric 
924*0b57cec5SDimitry Andric   if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
925*0b57cec5SDimitry Andric     return;
926*0b57cec5SDimitry Andric 
927*0b57cec5SDimitry Andric   if (isa<llvm::Constant>(ValuePtr))
928*0b57cec5SDimitry Andric     return;
929*0b57cec5SDimitry Andric 
930*0b57cec5SDimitry Andric   bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
931*0b57cec5SDimitry Andric   if (InstrumentValueSites && RegionCounterMap) {
932*0b57cec5SDimitry Andric     auto BuilderInsertPoint = Builder.saveIP();
933*0b57cec5SDimitry Andric     Builder.SetInsertPoint(ValueSite);
934*0b57cec5SDimitry Andric     llvm::Value *Args[5] = {
935*0b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
936*0b57cec5SDimitry Andric         Builder.getInt64(FunctionHash),
937*0b57cec5SDimitry Andric         Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
938*0b57cec5SDimitry Andric         Builder.getInt32(ValueKind),
939*0b57cec5SDimitry Andric         Builder.getInt32(NumValueSites[ValueKind]++)
940*0b57cec5SDimitry Andric     };
941*0b57cec5SDimitry Andric     Builder.CreateCall(
942*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
943*0b57cec5SDimitry Andric     Builder.restoreIP(BuilderInsertPoint);
944*0b57cec5SDimitry Andric     return;
945*0b57cec5SDimitry Andric   }
946*0b57cec5SDimitry Andric 
947*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
948*0b57cec5SDimitry Andric   if (PGOReader && haveRegionCounts()) {
949*0b57cec5SDimitry Andric     // We record the top most called three functions at each call site.
950*0b57cec5SDimitry Andric     // Profile metadata contains "VP" string identifying this metadata
951*0b57cec5SDimitry Andric     // as value profiling data, then a uint32_t value for the value profiling
952*0b57cec5SDimitry Andric     // kind, a uint64_t value for the total number of times the call is
953*0b57cec5SDimitry Andric     // executed, followed by the function hash and execution count (uint64_t)
954*0b57cec5SDimitry Andric     // pairs for each function.
955*0b57cec5SDimitry Andric     if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
956*0b57cec5SDimitry Andric       return;
957*0b57cec5SDimitry Andric 
958*0b57cec5SDimitry Andric     llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
959*0b57cec5SDimitry Andric                             (llvm::InstrProfValueKind)ValueKind,
960*0b57cec5SDimitry Andric                             NumValueSites[ValueKind]);
961*0b57cec5SDimitry Andric 
962*0b57cec5SDimitry Andric     NumValueSites[ValueKind]++;
963*0b57cec5SDimitry Andric   }
964*0b57cec5SDimitry Andric }
965*0b57cec5SDimitry Andric 
966*0b57cec5SDimitry Andric void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
967*0b57cec5SDimitry Andric                                   bool IsInMainFile) {
968*0b57cec5SDimitry Andric   CGM.getPGOStats().addVisited(IsInMainFile);
969*0b57cec5SDimitry Andric   RegionCounts.clear();
970*0b57cec5SDimitry Andric   llvm::Expected<llvm::InstrProfRecord> RecordExpected =
971*0b57cec5SDimitry Andric       PGOReader->getInstrProfRecord(FuncName, FunctionHash);
972*0b57cec5SDimitry Andric   if (auto E = RecordExpected.takeError()) {
973*0b57cec5SDimitry Andric     auto IPE = llvm::InstrProfError::take(std::move(E));
974*0b57cec5SDimitry Andric     if (IPE == llvm::instrprof_error::unknown_function)
975*0b57cec5SDimitry Andric       CGM.getPGOStats().addMissing(IsInMainFile);
976*0b57cec5SDimitry Andric     else if (IPE == llvm::instrprof_error::hash_mismatch)
977*0b57cec5SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
978*0b57cec5SDimitry Andric     else if (IPE == llvm::instrprof_error::malformed)
979*0b57cec5SDimitry Andric       // TODO: Consider a more specific warning for this case.
980*0b57cec5SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
981*0b57cec5SDimitry Andric     return;
982*0b57cec5SDimitry Andric   }
983*0b57cec5SDimitry Andric   ProfRecord =
984a7dea167SDimitry Andric       std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
985*0b57cec5SDimitry Andric   RegionCounts = ProfRecord->Counts;
986*0b57cec5SDimitry Andric }
987*0b57cec5SDimitry Andric 
988*0b57cec5SDimitry Andric /// Calculate what to divide by to scale weights.
989*0b57cec5SDimitry Andric ///
990*0b57cec5SDimitry Andric /// Given the maximum weight, calculate a divisor that will scale all the
991*0b57cec5SDimitry Andric /// weights to strictly less than UINT32_MAX.
992*0b57cec5SDimitry Andric static uint64_t calculateWeightScale(uint64_t MaxWeight) {
993*0b57cec5SDimitry Andric   return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
994*0b57cec5SDimitry Andric }
995*0b57cec5SDimitry Andric 
996*0b57cec5SDimitry Andric /// Scale an individual branch weight (and add 1).
997*0b57cec5SDimitry Andric ///
998*0b57cec5SDimitry Andric /// Scale a 64-bit weight down to 32-bits using \c Scale.
999*0b57cec5SDimitry Andric ///
1000*0b57cec5SDimitry Andric /// According to Laplace's Rule of Succession, it is better to compute the
1001*0b57cec5SDimitry Andric /// weight based on the count plus 1, so universally add 1 to the value.
1002*0b57cec5SDimitry Andric ///
1003*0b57cec5SDimitry Andric /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1004*0b57cec5SDimitry Andric /// greater than \c Weight.
1005*0b57cec5SDimitry Andric static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1006*0b57cec5SDimitry Andric   assert(Scale && "scale by 0?");
1007*0b57cec5SDimitry Andric   uint64_t Scaled = Weight / Scale + 1;
1008*0b57cec5SDimitry Andric   assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1009*0b57cec5SDimitry Andric   return Scaled;
1010*0b57cec5SDimitry Andric }
1011*0b57cec5SDimitry Andric 
1012*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1013*0b57cec5SDimitry Andric                                                     uint64_t FalseCount) {
1014*0b57cec5SDimitry Andric   // Check for empty weights.
1015*0b57cec5SDimitry Andric   if (!TrueCount && !FalseCount)
1016*0b57cec5SDimitry Andric     return nullptr;
1017*0b57cec5SDimitry Andric 
1018*0b57cec5SDimitry Andric   // Calculate how to scale down to 32-bits.
1019*0b57cec5SDimitry Andric   uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1020*0b57cec5SDimitry Andric 
1021*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1022*0b57cec5SDimitry Andric   return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1023*0b57cec5SDimitry Andric                                       scaleBranchWeight(FalseCount, Scale));
1024*0b57cec5SDimitry Andric }
1025*0b57cec5SDimitry Andric 
1026*0b57cec5SDimitry Andric llvm::MDNode *
1027*0b57cec5SDimitry Andric CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
1028*0b57cec5SDimitry Andric   // We need at least two elements to create meaningful weights.
1029*0b57cec5SDimitry Andric   if (Weights.size() < 2)
1030*0b57cec5SDimitry Andric     return nullptr;
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric   // Check for empty weights.
1033*0b57cec5SDimitry Andric   uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1034*0b57cec5SDimitry Andric   if (MaxWeight == 0)
1035*0b57cec5SDimitry Andric     return nullptr;
1036*0b57cec5SDimitry Andric 
1037*0b57cec5SDimitry Andric   // Calculate how to scale down to 32-bits.
1038*0b57cec5SDimitry Andric   uint64_t Scale = calculateWeightScale(MaxWeight);
1039*0b57cec5SDimitry Andric 
1040*0b57cec5SDimitry Andric   SmallVector<uint32_t, 16> ScaledWeights;
1041*0b57cec5SDimitry Andric   ScaledWeights.reserve(Weights.size());
1042*0b57cec5SDimitry Andric   for (uint64_t W : Weights)
1043*0b57cec5SDimitry Andric     ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1044*0b57cec5SDimitry Andric 
1045*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1046*0b57cec5SDimitry Andric   return MDHelper.createBranchWeights(ScaledWeights);
1047*0b57cec5SDimitry Andric }
1048*0b57cec5SDimitry Andric 
1049*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1050*0b57cec5SDimitry Andric                                                            uint64_t LoopCount) {
1051*0b57cec5SDimitry Andric   if (!PGO.haveRegionCounts())
1052*0b57cec5SDimitry Andric     return nullptr;
1053*0b57cec5SDimitry Andric   Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
1054*0b57cec5SDimitry Andric   assert(CondCount.hasValue() && "missing expected loop condition count");
1055*0b57cec5SDimitry Andric   if (*CondCount == 0)
1056*0b57cec5SDimitry Andric     return nullptr;
1057*0b57cec5SDimitry Andric   return createProfileWeights(LoopCount,
1058*0b57cec5SDimitry Andric                               std::max(*CondCount, LoopCount) - LoopCount);
1059*0b57cec5SDimitry Andric }
1060