CodeGenPGO.cpp 38 KB

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