ProfileGenerator.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. //===-- ProfileGenerator.cpp - Profile Generator ---------------*- 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. #include "ProfileGenerator.h"
  9. #include "ErrorHandling.h"
  10. #include "ProfiledBinary.h"
  11. #include "llvm/ProfileData/ProfileCommon.h"
  12. #include <float.h>
  13. #include <unordered_set>
  14. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  15. cl::Required,
  16. cl::desc("Output profile file"));
  17. static cl::alias OutputA("o", cl::desc("Alias for --output"),
  18. cl::aliasopt(OutputFilename));
  19. static cl::opt<SampleProfileFormat> OutputFormat(
  20. "format", cl::desc("Format of output profile"), cl::init(SPF_Ext_Binary),
  21. cl::values(
  22. clEnumValN(SPF_Binary, "binary", "Binary encoding (default)"),
  23. clEnumValN(SPF_Compact_Binary, "compbinary", "Compact binary encoding"),
  24. clEnumValN(SPF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  25. clEnumValN(SPF_Text, "text", "Text encoding"),
  26. clEnumValN(SPF_GCC, "gcc",
  27. "GCC encoding (only meaningful for -sample)")));
  28. cl::opt<bool> UseMD5(
  29. "use-md5", cl::init(false), cl::Hidden,
  30. cl::desc("Use md5 to represent function names in the output profile (only "
  31. "meaningful for -extbinary)"));
  32. static cl::opt<bool> PopulateProfileSymbolList(
  33. "populate-profile-symbol-list", cl::init(false), cl::Hidden,
  34. cl::desc("Populate profile symbol list (only meaningful for -extbinary)"));
  35. static cl::opt<bool> FillZeroForAllFuncs(
  36. "fill-zero-for-all-funcs", cl::init(false), cl::Hidden,
  37. cl::desc("Attribute all functions' range with zero count "
  38. "even it's not hit by any samples."));
  39. static cl::opt<int32_t, true> RecursionCompression(
  40. "compress-recursion",
  41. cl::desc("Compressing recursion by deduplicating adjacent frame "
  42. "sequences up to the specified size. -1 means no size limit."),
  43. cl::Hidden,
  44. cl::location(llvm::sampleprof::CSProfileGenerator::MaxCompressionSize));
  45. static cl::opt<bool>
  46. TrimColdProfile("trim-cold-profile", cl::init(false), cl::ZeroOrMore,
  47. cl::desc("If the total count of the profile is smaller "
  48. "than threshold, it will be trimmed."));
  49. static cl::opt<bool> CSProfMergeColdContext(
  50. "csprof-merge-cold-context", cl::init(true), cl::ZeroOrMore,
  51. cl::desc("If the total count of context profile is smaller than "
  52. "the threshold, it will be merged into context-less base "
  53. "profile."));
  54. static cl::opt<uint32_t> CSProfMaxColdContextDepth(
  55. "csprof-max-cold-context-depth", cl::init(1), cl::ZeroOrMore,
  56. cl::desc("Keep the last K contexts while merging cold profile. 1 means the "
  57. "context-less base profile"));
  58. static cl::opt<int, true> CSProfMaxContextDepth(
  59. "csprof-max-context-depth", cl::ZeroOrMore,
  60. cl::desc("Keep the last K contexts while merging profile. -1 means no "
  61. "depth limit."),
  62. cl::location(llvm::sampleprof::CSProfileGenerator::MaxContextDepth));
  63. static cl::opt<double> HotFunctionDensityThreshold(
  64. "hot-function-density-threshold", llvm::cl::init(1000),
  65. llvm::cl::desc(
  66. "specify density threshold for hot functions (default: 1000)"),
  67. llvm::cl::Optional);
  68. static cl::opt<bool> ShowDensity("show-density", llvm::cl::init(false),
  69. llvm::cl::desc("show profile density details"),
  70. llvm::cl::Optional);
  71. static cl::opt<bool> UpdateTotalSamples(
  72. "update-total-samples", llvm::cl::init(false),
  73. llvm::cl::desc(
  74. "Update total samples by accumulating all its body samples."),
  75. llvm::cl::Optional);
  76. extern cl::opt<int> ProfileSummaryCutoffHot;
  77. static cl::opt<bool> GenCSNestedProfile(
  78. "gen-cs-nested-profile", cl::Hidden, cl::init(false),
  79. cl::desc("Generate nested function profiles for CSSPGO"));
  80. using namespace llvm;
  81. using namespace sampleprof;
  82. namespace llvm {
  83. namespace sampleprof {
  84. // Initialize the MaxCompressionSize to -1 which means no size limit
  85. int32_t CSProfileGenerator::MaxCompressionSize = -1;
  86. int CSProfileGenerator::MaxContextDepth = -1;
  87. bool ProfileGeneratorBase::UseFSDiscriminator = false;
  88. std::unique_ptr<ProfileGeneratorBase>
  89. ProfileGeneratorBase::create(ProfiledBinary *Binary,
  90. const ContextSampleCounterMap &SampleCounters,
  91. bool ProfileIsCSFlat) {
  92. std::unique_ptr<ProfileGeneratorBase> Generator;
  93. if (ProfileIsCSFlat) {
  94. if (Binary->useFSDiscriminator())
  95. exitWithError("FS discriminator is not supported in CS profile.");
  96. Generator.reset(new CSProfileGenerator(Binary, SampleCounters));
  97. } else {
  98. Generator.reset(new ProfileGenerator(Binary, SampleCounters));
  99. }
  100. ProfileGeneratorBase::UseFSDiscriminator = Binary->useFSDiscriminator();
  101. FunctionSamples::ProfileIsFS = Binary->useFSDiscriminator();
  102. return Generator;
  103. }
  104. void ProfileGeneratorBase::write(std::unique_ptr<SampleProfileWriter> Writer,
  105. SampleProfileMap &ProfileMap) {
  106. // Populate profile symbol list if extended binary format is used.
  107. ProfileSymbolList SymbolList;
  108. if (PopulateProfileSymbolList && OutputFormat == SPF_Ext_Binary) {
  109. Binary->populateSymbolListFromDWARF(SymbolList);
  110. Writer->setProfileSymbolList(&SymbolList);
  111. }
  112. if (std::error_code EC = Writer->write(ProfileMap))
  113. exitWithError(std::move(EC));
  114. }
  115. void ProfileGeneratorBase::write() {
  116. auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
  117. if (std::error_code EC = WriterOrErr.getError())
  118. exitWithError(EC, OutputFilename);
  119. if (UseMD5) {
  120. if (OutputFormat != SPF_Ext_Binary)
  121. WithColor::warning() << "-use-md5 is ignored. Specify "
  122. "--format=extbinary to enable it\n";
  123. else
  124. WriterOrErr.get()->setUseMD5();
  125. }
  126. write(std::move(WriterOrErr.get()), ProfileMap);
  127. }
  128. void ProfileGeneratorBase::showDensitySuggestion(double Density) {
  129. if (Density == 0.0)
  130. WithColor::warning() << "The --profile-summary-cutoff-hot option may be "
  131. "set too low. Please check your command.\n";
  132. else if (Density < HotFunctionDensityThreshold)
  133. WithColor::warning()
  134. << "AutoFDO is estimated to optimize better with "
  135. << format("%.1f", HotFunctionDensityThreshold / Density)
  136. << "x more samples. Please consider increasing sampling rate or "
  137. "profiling for longer duration to get more samples.\n";
  138. if (ShowDensity)
  139. outs() << "Minimum profile density for hot functions with top "
  140. << format("%.2f",
  141. static_cast<double>(ProfileSummaryCutoffHot.getValue()) /
  142. 10000)
  143. << "% total samples: " << format("%.1f", Density) << "\n";
  144. }
  145. double ProfileGeneratorBase::calculateDensity(const SampleProfileMap &Profiles,
  146. uint64_t HotCntThreshold) {
  147. double Density = DBL_MAX;
  148. std::vector<const FunctionSamples *> HotFuncs;
  149. for (auto &I : Profiles) {
  150. auto &FuncSamples = I.second;
  151. if (FuncSamples.getTotalSamples() < HotCntThreshold)
  152. continue;
  153. HotFuncs.emplace_back(&FuncSamples);
  154. }
  155. for (auto *FuncSamples : HotFuncs) {
  156. auto *Func = Binary->getBinaryFunction(FuncSamples->getName());
  157. if (!Func)
  158. continue;
  159. uint64_t FuncSize = Func->getFuncSize();
  160. if (FuncSize == 0)
  161. continue;
  162. Density =
  163. std::min(Density, static_cast<double>(FuncSamples->getTotalSamples()) /
  164. FuncSize);
  165. }
  166. return Density == DBL_MAX ? 0.0 : Density;
  167. }
  168. void ProfileGeneratorBase::findDisjointRanges(RangeSample &DisjointRanges,
  169. const RangeSample &Ranges) {
  170. /*
  171. Regions may overlap with each other. Using the boundary info, find all
  172. disjoint ranges and their sample count. BoundaryPoint contains the count
  173. multiple samples begin/end at this points.
  174. |<--100-->| Sample1
  175. |<------200------>| Sample2
  176. A B C
  177. In the example above,
  178. Sample1 begins at A, ends at B, its value is 100.
  179. Sample2 beings at A, ends at C, its value is 200.
  180. For A, BeginCount is the sum of sample begins at A, which is 300 and no
  181. samples ends at A, so EndCount is 0.
  182. Then boundary points A, B, and C with begin/end counts are:
  183. A: (300, 0)
  184. B: (0, 100)
  185. C: (0, 200)
  186. */
  187. struct BoundaryPoint {
  188. // Sum of sample counts beginning at this point
  189. uint64_t BeginCount = UINT64_MAX;
  190. // Sum of sample counts ending at this point
  191. uint64_t EndCount = UINT64_MAX;
  192. // Is the begin point of a zero range.
  193. bool IsZeroRangeBegin = false;
  194. // Is the end point of a zero range.
  195. bool IsZeroRangeEnd = false;
  196. void addBeginCount(uint64_t Count) {
  197. if (BeginCount == UINT64_MAX)
  198. BeginCount = 0;
  199. BeginCount += Count;
  200. }
  201. void addEndCount(uint64_t Count) {
  202. if (EndCount == UINT64_MAX)
  203. EndCount = 0;
  204. EndCount += Count;
  205. }
  206. };
  207. /*
  208. For the above example. With boundary points, follwing logic finds two
  209. disjoint region of
  210. [A,B]: 300
  211. [B+1,C]: 200
  212. If there is a boundary point that both begin and end, the point itself
  213. becomes a separate disjoint region. For example, if we have original
  214. ranges of
  215. |<--- 100 --->|
  216. |<--- 200 --->|
  217. A B C
  218. there are three boundary points with their begin/end counts of
  219. A: (100, 0)
  220. B: (200, 100)
  221. C: (0, 200)
  222. the disjoint ranges would be
  223. [A, B-1]: 100
  224. [B, B]: 300
  225. [B+1, C]: 200.
  226. Example for zero value range:
  227. |<--- 100 --->|
  228. |<--- 200 --->|
  229. |<--------------- 0 ----------------->|
  230. A B C D E F
  231. [A, B-1] : 0
  232. [B, C] : 100
  233. [C+1, D-1]: 0
  234. [D, E] : 200
  235. [E+1, F] : 0
  236. */
  237. std::map<uint64_t, BoundaryPoint> Boundaries;
  238. for (const auto &Item : Ranges) {
  239. assert(Item.first.first <= Item.first.second &&
  240. "Invalid instruction range");
  241. auto &BeginPoint = Boundaries[Item.first.first];
  242. auto &EndPoint = Boundaries[Item.first.second];
  243. uint64_t Count = Item.second;
  244. BeginPoint.addBeginCount(Count);
  245. EndPoint.addEndCount(Count);
  246. if (Count == 0) {
  247. BeginPoint.IsZeroRangeBegin = true;
  248. EndPoint.IsZeroRangeEnd = true;
  249. }
  250. }
  251. // Use UINT64_MAX to indicate there is no existing range between BeginAddress
  252. // and the next valid address
  253. uint64_t BeginAddress = UINT64_MAX;
  254. int ZeroRangeDepth = 0;
  255. uint64_t Count = 0;
  256. for (const auto &Item : Boundaries) {
  257. uint64_t Address = Item.first;
  258. const BoundaryPoint &Point = Item.second;
  259. if (Point.BeginCount != UINT64_MAX) {
  260. if (BeginAddress != UINT64_MAX)
  261. DisjointRanges[{BeginAddress, Address - 1}] = Count;
  262. Count += Point.BeginCount;
  263. BeginAddress = Address;
  264. ZeroRangeDepth += Point.IsZeroRangeBegin;
  265. }
  266. if (Point.EndCount != UINT64_MAX) {
  267. assert((BeginAddress != UINT64_MAX) &&
  268. "First boundary point cannot be 'end' point");
  269. DisjointRanges[{BeginAddress, Address}] = Count;
  270. assert(Count >= Point.EndCount && "Mismatched live ranges");
  271. Count -= Point.EndCount;
  272. BeginAddress = Address + 1;
  273. ZeroRangeDepth -= Point.IsZeroRangeEnd;
  274. // If the remaining count is zero and it's no longer in a zero range, this
  275. // means we consume all the ranges before, thus mark BeginAddress as
  276. // UINT64_MAX. e.g. supposing we have two non-overlapping ranges:
  277. // [<---- 10 ---->]
  278. // [<---- 20 ---->]
  279. // A B C D
  280. // The BeginAddress(B+1) will reset to invalid(UINT64_MAX), so we won't
  281. // have the [B+1, C-1] zero range.
  282. if (Count == 0 && ZeroRangeDepth == 0)
  283. BeginAddress = UINT64_MAX;
  284. }
  285. }
  286. }
  287. void ProfileGeneratorBase::updateBodySamplesforFunctionProfile(
  288. FunctionSamples &FunctionProfile, const SampleContextFrame &LeafLoc,
  289. uint64_t Count) {
  290. // Use the maximum count of samples with same line location
  291. uint32_t Discriminator = getBaseDiscriminator(LeafLoc.Location.Discriminator);
  292. // Use duplication factor to compensated for loop unroll/vectorization.
  293. // Note that this is only needed when we're taking MAX of the counts at
  294. // the location instead of SUM.
  295. Count *= getDuplicationFactor(LeafLoc.Location.Discriminator);
  296. ErrorOr<uint64_t> R =
  297. FunctionProfile.findSamplesAt(LeafLoc.Location.LineOffset, Discriminator);
  298. uint64_t PreviousCount = R ? R.get() : 0;
  299. if (PreviousCount <= Count) {
  300. FunctionProfile.addBodySamples(LeafLoc.Location.LineOffset, Discriminator,
  301. Count - PreviousCount);
  302. }
  303. }
  304. void ProfileGeneratorBase::updateTotalSamples() {
  305. if (!UpdateTotalSamples)
  306. return;
  307. for (auto &Item : ProfileMap) {
  308. FunctionSamples &FunctionProfile = Item.second;
  309. FunctionProfile.updateTotalSamples();
  310. }
  311. }
  312. FunctionSamples &
  313. ProfileGenerator::getTopLevelFunctionProfile(StringRef FuncName) {
  314. SampleContext Context(FuncName);
  315. auto Ret = ProfileMap.emplace(Context, FunctionSamples());
  316. if (Ret.second) {
  317. FunctionSamples &FProfile = Ret.first->second;
  318. FProfile.setContext(Context);
  319. }
  320. return Ret.first->second;
  321. }
  322. void ProfileGenerator::generateProfile() {
  323. if (Binary->usePseudoProbes()) {
  324. // TODO: Support probe based profile generation
  325. exitWithError("Probe based profile generation not supported for AutoFDO, "
  326. "consider dropping `--ignore-stack-samples` or adding `--use-dwarf-correlation`.");
  327. } else {
  328. generateLineNumBasedProfile();
  329. }
  330. postProcessProfiles();
  331. }
  332. void ProfileGenerator::postProcessProfiles() {
  333. computeSummaryAndThreshold();
  334. trimColdProfiles(ProfileMap, ColdCountThreshold);
  335. calculateAndShowDensity(ProfileMap);
  336. }
  337. void ProfileGenerator::trimColdProfiles(const SampleProfileMap &Profiles,
  338. uint64_t ColdCntThreshold) {
  339. if (!TrimColdProfile)
  340. return;
  341. // Move cold profiles into a tmp container.
  342. std::vector<SampleContext> ColdProfiles;
  343. for (const auto &I : ProfileMap) {
  344. if (I.second.getTotalSamples() < ColdCntThreshold)
  345. ColdProfiles.emplace_back(I.first);
  346. }
  347. // Remove the cold profile from ProfileMap.
  348. for (const auto &I : ColdProfiles)
  349. ProfileMap.erase(I);
  350. }
  351. void ProfileGenerator::generateLineNumBasedProfile() {
  352. assert(SampleCounters.size() == 1 &&
  353. "Must have one entry for profile generation.");
  354. const SampleCounter &SC = SampleCounters.begin()->second;
  355. // Fill in function body samples
  356. populateBodySamplesForAllFunctions(SC.RangeCounter);
  357. // Fill in boundary sample counts as well as call site samples for calls
  358. populateBoundarySamplesForAllFunctions(SC.BranchCounter);
  359. updateTotalSamples();
  360. }
  361. FunctionSamples &ProfileGenerator::getLeafProfileAndAddTotalSamples(
  362. const SampleContextFrameVector &FrameVec, uint64_t Count) {
  363. // Get top level profile
  364. FunctionSamples *FunctionProfile =
  365. &getTopLevelFunctionProfile(FrameVec[0].FuncName);
  366. FunctionProfile->addTotalSamples(Count);
  367. for (size_t I = 1; I < FrameVec.size(); I++) {
  368. LineLocation Callsite(
  369. FrameVec[I - 1].Location.LineOffset,
  370. getBaseDiscriminator(FrameVec[I - 1].Location.Discriminator));
  371. FunctionSamplesMap &SamplesMap =
  372. FunctionProfile->functionSamplesAt(Callsite);
  373. auto Ret =
  374. SamplesMap.emplace(FrameVec[I].FuncName.str(), FunctionSamples());
  375. if (Ret.second) {
  376. SampleContext Context(FrameVec[I].FuncName);
  377. Ret.first->second.setContext(Context);
  378. }
  379. FunctionProfile = &Ret.first->second;
  380. FunctionProfile->addTotalSamples(Count);
  381. }
  382. return *FunctionProfile;
  383. }
  384. RangeSample
  385. ProfileGenerator::preprocessRangeCounter(const RangeSample &RangeCounter) {
  386. RangeSample Ranges(RangeCounter.begin(), RangeCounter.end());
  387. if (FillZeroForAllFuncs) {
  388. for (auto &FuncI : Binary->getAllBinaryFunctions()) {
  389. for (auto &R : FuncI.second.Ranges) {
  390. Ranges[{R.first, R.second - 1}] += 0;
  391. }
  392. }
  393. } else {
  394. // For each range, we search for all ranges of the function it belongs to
  395. // and initialize it with zero count, so it remains zero if doesn't hit any
  396. // samples. This is to be consistent with compiler that interpret zero count
  397. // as unexecuted(cold).
  398. for (const auto &I : RangeCounter) {
  399. uint64_t StartOffset = I.first.first;
  400. for (const auto &Range : Binary->getRangesForOffset(StartOffset))
  401. Ranges[{Range.first, Range.second - 1}] += 0;
  402. }
  403. }
  404. RangeSample DisjointRanges;
  405. findDisjointRanges(DisjointRanges, Ranges);
  406. return DisjointRanges;
  407. }
  408. void ProfileGenerator::populateBodySamplesForAllFunctions(
  409. const RangeSample &RangeCounter) {
  410. for (const auto &Range : preprocessRangeCounter(RangeCounter)) {
  411. uint64_t RangeBegin = Binary->offsetToVirtualAddr(Range.first.first);
  412. uint64_t RangeEnd = Binary->offsetToVirtualAddr(Range.first.second);
  413. uint64_t Count = Range.second;
  414. InstructionPointer IP(Binary, RangeBegin, true);
  415. // Disjoint ranges may have range in the middle of two instr,
  416. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  417. // can be Addr1+1 to Addr2-1. We should ignore such range.
  418. if (IP.Address > RangeEnd)
  419. continue;
  420. do {
  421. uint64_t Offset = Binary->virtualAddrToOffset(IP.Address);
  422. const SampleContextFrameVector &FrameVec =
  423. Binary->getFrameLocationStack(Offset);
  424. if (!FrameVec.empty()) {
  425. // FIXME: As accumulating total count per instruction caused some
  426. // regression, we changed to accumulate total count per byte as a
  427. // workaround. Tuning hotness threshold on the compiler side might be
  428. // necessary in the future.
  429. FunctionSamples &FunctionProfile = getLeafProfileAndAddTotalSamples(
  430. FrameVec, Count * Binary->getInstSize(Offset));
  431. updateBodySamplesforFunctionProfile(FunctionProfile, FrameVec.back(),
  432. Count);
  433. }
  434. } while (IP.advance() && IP.Address <= RangeEnd);
  435. }
  436. }
  437. StringRef ProfileGeneratorBase::getCalleeNameForOffset(uint64_t TargetOffset) {
  438. // Get the function range by branch target if it's a call branch.
  439. auto *FRange = Binary->findFuncRangeForStartOffset(TargetOffset);
  440. // We won't accumulate sample count for a range whose start is not the real
  441. // function entry such as outlined function or inner labels.
  442. if (!FRange || !FRange->IsFuncEntry)
  443. return StringRef();
  444. return FunctionSamples::getCanonicalFnName(FRange->getFuncName());
  445. }
  446. void ProfileGenerator::populateBoundarySamplesForAllFunctions(
  447. const BranchSample &BranchCounters) {
  448. for (const auto &Entry : BranchCounters) {
  449. uint64_t SourceOffset = Entry.first.first;
  450. uint64_t TargetOffset = Entry.first.second;
  451. uint64_t Count = Entry.second;
  452. assert(Count != 0 && "Unexpected zero weight branch");
  453. StringRef CalleeName = getCalleeNameForOffset(TargetOffset);
  454. if (CalleeName.size() == 0)
  455. continue;
  456. // Record called target sample and its count.
  457. const SampleContextFrameVector &FrameVec =
  458. Binary->getFrameLocationStack(SourceOffset);
  459. if (!FrameVec.empty()) {
  460. FunctionSamples &FunctionProfile =
  461. getLeafProfileAndAddTotalSamples(FrameVec, 0);
  462. FunctionProfile.addCalledTargetSamples(
  463. FrameVec.back().Location.LineOffset,
  464. getBaseDiscriminator(FrameVec.back().Location.Discriminator),
  465. CalleeName, Count);
  466. }
  467. // Add head samples for callee.
  468. FunctionSamples &CalleeProfile = getTopLevelFunctionProfile(CalleeName);
  469. CalleeProfile.addHeadSamples(Count);
  470. }
  471. }
  472. void ProfileGeneratorBase::calculateAndShowDensity(
  473. const SampleProfileMap &Profiles) {
  474. double Density = calculateDensity(Profiles, HotCountThreshold);
  475. showDensitySuggestion(Density);
  476. }
  477. FunctionSamples &CSProfileGenerator::getFunctionProfileForContext(
  478. const SampleContextFrameVector &Context, bool WasLeafInlined) {
  479. auto I = ProfileMap.find(SampleContext(Context));
  480. if (I == ProfileMap.end()) {
  481. // Save the new context for future references.
  482. SampleContextFrames NewContext = *Contexts.insert(Context).first;
  483. SampleContext FContext(NewContext, RawContext);
  484. auto Ret = ProfileMap.emplace(FContext, FunctionSamples());
  485. if (WasLeafInlined)
  486. FContext.setAttribute(ContextWasInlined);
  487. FunctionSamples &FProfile = Ret.first->second;
  488. FProfile.setContext(FContext);
  489. return Ret.first->second;
  490. }
  491. return I->second;
  492. }
  493. void CSProfileGenerator::generateProfile() {
  494. FunctionSamples::ProfileIsCSFlat = true;
  495. if (Binary->getTrackFuncContextSize())
  496. computeSizeForProfiledFunctions();
  497. if (Binary->usePseudoProbes()) {
  498. // Enable pseudo probe functionalities in SampleProf
  499. FunctionSamples::ProfileIsProbeBased = true;
  500. generateProbeBasedProfile();
  501. } else {
  502. generateLineNumBasedProfile();
  503. }
  504. postProcessProfiles();
  505. }
  506. void CSProfileGenerator::computeSizeForProfiledFunctions() {
  507. // Hash map to deduplicate the function range and the item is a pair of
  508. // function start and end offset.
  509. std::unordered_map<uint64_t, uint64_t> AggregatedRanges;
  510. // Go through all the ranges in the CS counters, use the start of the range to
  511. // look up the function it belongs and record the function range.
  512. for (const auto &CI : SampleCounters) {
  513. for (const auto &Item : CI.second.RangeCounter) {
  514. // FIXME: Filter the bogus crossing function range.
  515. uint64_t StartOffset = Item.first.first;
  516. // Note that a function can be spilt into multiple ranges, so get all
  517. // ranges of the function.
  518. for (const auto &Range : Binary->getRangesForOffset(StartOffset))
  519. AggregatedRanges[Range.first] = Range.second;
  520. }
  521. }
  522. for (const auto &I : AggregatedRanges) {
  523. uint64_t StartOffset = I.first;
  524. uint64_t EndOffset = I.second;
  525. Binary->computeInlinedContextSizeForRange(StartOffset, EndOffset);
  526. }
  527. }
  528. void CSProfileGenerator::generateLineNumBasedProfile() {
  529. for (const auto &CI : SampleCounters) {
  530. const auto *CtxKey = cast<StringBasedCtxKey>(CI.first.getPtr());
  531. // Get or create function profile for the range
  532. FunctionSamples &FunctionProfile =
  533. getFunctionProfileForContext(CtxKey->Context, CtxKey->WasLeafInlined);
  534. // Fill in function body samples
  535. populateBodySamplesForFunction(FunctionProfile, CI.second.RangeCounter);
  536. // Fill in boundary sample counts as well as call site samples for calls
  537. populateBoundarySamplesForFunction(CtxKey->Context, FunctionProfile,
  538. CI.second.BranchCounter);
  539. }
  540. // Fill in call site value sample for inlined calls and also use context to
  541. // infer missing samples. Since we don't have call count for inlined
  542. // functions, we estimate it from inlinee's profile using the entry of the
  543. // body sample.
  544. populateInferredFunctionSamples();
  545. updateTotalSamples();
  546. }
  547. void CSProfileGenerator::populateBodySamplesForFunction(
  548. FunctionSamples &FunctionProfile, const RangeSample &RangeCounter) {
  549. // Compute disjoint ranges first, so we can use MAX
  550. // for calculating count for each location.
  551. RangeSample Ranges;
  552. findDisjointRanges(Ranges, RangeCounter);
  553. for (const auto &Range : Ranges) {
  554. uint64_t RangeBegin = Binary->offsetToVirtualAddr(Range.first.first);
  555. uint64_t RangeEnd = Binary->offsetToVirtualAddr(Range.first.second);
  556. uint64_t Count = Range.second;
  557. // Disjoint ranges have introduce zero-filled gap that
  558. // doesn't belong to current context, filter them out.
  559. if (Count == 0)
  560. continue;
  561. InstructionPointer IP(Binary, RangeBegin, true);
  562. // Disjoint ranges may have range in the middle of two instr,
  563. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  564. // can be Addr1+1 to Addr2-1. We should ignore such range.
  565. if (IP.Address > RangeEnd)
  566. continue;
  567. do {
  568. uint64_t Offset = Binary->virtualAddrToOffset(IP.Address);
  569. auto LeafLoc = Binary->getInlineLeafFrameLoc(Offset);
  570. if (LeafLoc.hasValue()) {
  571. // Recording body sample for this specific context
  572. updateBodySamplesforFunctionProfile(FunctionProfile, *LeafLoc, Count);
  573. FunctionProfile.addTotalSamples(Count);
  574. }
  575. } while (IP.advance() && IP.Address <= RangeEnd);
  576. }
  577. }
  578. void CSProfileGenerator::populateBoundarySamplesForFunction(
  579. SampleContextFrames ContextId, FunctionSamples &FunctionProfile,
  580. const BranchSample &BranchCounters) {
  581. for (const auto &Entry : BranchCounters) {
  582. uint64_t SourceOffset = Entry.first.first;
  583. uint64_t TargetOffset = Entry.first.second;
  584. uint64_t Count = Entry.second;
  585. assert(Count != 0 && "Unexpected zero weight branch");
  586. StringRef CalleeName = getCalleeNameForOffset(TargetOffset);
  587. if (CalleeName.size() == 0)
  588. continue;
  589. // Record called target sample and its count
  590. auto LeafLoc = Binary->getInlineLeafFrameLoc(SourceOffset);
  591. if (!LeafLoc.hasValue())
  592. continue;
  593. FunctionProfile.addCalledTargetSamples(
  594. LeafLoc->Location.LineOffset,
  595. getBaseDiscriminator(LeafLoc->Location.Discriminator), CalleeName,
  596. Count);
  597. // Record head sample for called target(callee)
  598. SampleContextFrameVector CalleeCtx(ContextId.begin(), ContextId.end());
  599. assert(CalleeCtx.back().FuncName == LeafLoc->FuncName &&
  600. "Leaf function name doesn't match");
  601. CalleeCtx.back() = *LeafLoc;
  602. CalleeCtx.emplace_back(CalleeName, LineLocation(0, 0));
  603. FunctionSamples &CalleeProfile = getFunctionProfileForContext(CalleeCtx);
  604. CalleeProfile.addHeadSamples(Count);
  605. }
  606. }
  607. static SampleContextFrame
  608. getCallerContext(SampleContextFrames CalleeContext,
  609. SampleContextFrameVector &CallerContext) {
  610. assert(CalleeContext.size() > 1 && "Unexpected empty context");
  611. CalleeContext = CalleeContext.drop_back();
  612. CallerContext.assign(CalleeContext.begin(), CalleeContext.end());
  613. SampleContextFrame CallerFrame = CallerContext.back();
  614. CallerContext.back().Location = LineLocation(0, 0);
  615. return CallerFrame;
  616. }
  617. void CSProfileGenerator::populateInferredFunctionSamples() {
  618. for (const auto &Item : ProfileMap) {
  619. const auto &CalleeContext = Item.first;
  620. const FunctionSamples &CalleeProfile = Item.second;
  621. // If we already have head sample counts, we must have value profile
  622. // for call sites added already. Skip to avoid double counting.
  623. if (CalleeProfile.getHeadSamples())
  624. continue;
  625. // If we don't have context, nothing to do for caller's call site.
  626. // This could happen for entry point function.
  627. if (CalleeContext.isBaseContext())
  628. continue;
  629. // Infer Caller's frame loc and context ID through string splitting
  630. SampleContextFrameVector CallerContextId;
  631. SampleContextFrame &&CallerLeafFrameLoc =
  632. getCallerContext(CalleeContext.getContextFrames(), CallerContextId);
  633. SampleContextFrames CallerContext(CallerContextId);
  634. // It's possible that we haven't seen any sample directly in the caller,
  635. // in which case CallerProfile will not exist. But we can't modify
  636. // ProfileMap while iterating it.
  637. // TODO: created function profile for those callers too
  638. if (ProfileMap.find(CallerContext) == ProfileMap.end())
  639. continue;
  640. FunctionSamples &CallerProfile = ProfileMap[CallerContext];
  641. // Since we don't have call count for inlined functions, we
  642. // estimate it from inlinee's profile using entry body sample.
  643. uint64_t EstimatedCallCount = CalleeProfile.getEntrySamples();
  644. // If we don't have samples with location, use 1 to indicate live.
  645. if (!EstimatedCallCount && !CalleeProfile.getBodySamples().size())
  646. EstimatedCallCount = 1;
  647. CallerProfile.addCalledTargetSamples(
  648. CallerLeafFrameLoc.Location.LineOffset,
  649. CallerLeafFrameLoc.Location.Discriminator,
  650. CalleeProfile.getContext().getName(), EstimatedCallCount);
  651. CallerProfile.addBodySamples(CallerLeafFrameLoc.Location.LineOffset,
  652. CallerLeafFrameLoc.Location.Discriminator,
  653. EstimatedCallCount);
  654. CallerProfile.addTotalSamples(EstimatedCallCount);
  655. }
  656. }
  657. void CSProfileGenerator::postProcessProfiles() {
  658. // Compute hot/cold threshold based on profile. This will be used for cold
  659. // context profile merging/trimming.
  660. computeSummaryAndThreshold();
  661. // Run global pre-inliner to adjust/merge context profile based on estimated
  662. // inline decisions.
  663. if (EnableCSPreInliner) {
  664. CSPreInliner(ProfileMap, *Binary, HotCountThreshold, ColdCountThreshold)
  665. .run();
  666. // Turn off the profile merger by default unless it is explicitly enabled.
  667. if (!CSProfMergeColdContext.getNumOccurrences())
  668. CSProfMergeColdContext = false;
  669. }
  670. // Trim and merge cold context profile using cold threshold above.
  671. if (TrimColdProfile || CSProfMergeColdContext) {
  672. SampleContextTrimmer(ProfileMap)
  673. .trimAndMergeColdContextProfiles(
  674. HotCountThreshold, TrimColdProfile, CSProfMergeColdContext,
  675. CSProfMaxColdContextDepth, EnableCSPreInliner);
  676. }
  677. // Merge function samples of CS profile to calculate profile density.
  678. sampleprof::SampleProfileMap ContextLessProfiles;
  679. for (const auto &I : ProfileMap) {
  680. ContextLessProfiles[I.second.getName()].merge(I.second);
  681. }
  682. calculateAndShowDensity(ContextLessProfiles);
  683. if (GenCSNestedProfile) {
  684. CSProfileConverter CSConverter(ProfileMap);
  685. CSConverter.convertProfiles();
  686. FunctionSamples::ProfileIsCSFlat = false;
  687. FunctionSamples::ProfileIsCSNested = EnableCSPreInliner;
  688. }
  689. }
  690. void ProfileGeneratorBase::computeSummaryAndThreshold() {
  691. SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
  692. auto Summary = Builder.computeSummaryForProfiles(ProfileMap);
  693. HotCountThreshold = ProfileSummaryBuilder::getHotCountThreshold(
  694. (Summary->getDetailedSummary()));
  695. ColdCountThreshold = ProfileSummaryBuilder::getColdCountThreshold(
  696. (Summary->getDetailedSummary()));
  697. }
  698. // Helper function to extract context prefix string stack
  699. // Extract context stack for reusing, leaf context stack will
  700. // be added compressed while looking up function profile
  701. static void extractPrefixContextStack(
  702. SampleContextFrameVector &ContextStack,
  703. const SmallVectorImpl<const MCDecodedPseudoProbe *> &Probes,
  704. ProfiledBinary *Binary) {
  705. for (const auto *P : Probes) {
  706. Binary->getInlineContextForProbe(P, ContextStack, true);
  707. }
  708. }
  709. void CSProfileGenerator::generateProbeBasedProfile() {
  710. for (const auto &CI : SampleCounters) {
  711. const ProbeBasedCtxKey *CtxKey =
  712. dyn_cast<ProbeBasedCtxKey>(CI.first.getPtr());
  713. SampleContextFrameVector ContextStack;
  714. extractPrefixContextStack(ContextStack, CtxKey->Probes, Binary);
  715. // Fill in function body samples from probes, also infer caller's samples
  716. // from callee's probe
  717. populateBodySamplesWithProbes(CI.second.RangeCounter, ContextStack);
  718. // Fill in boundary samples for a call probe
  719. populateBoundarySamplesWithProbes(CI.second.BranchCounter, ContextStack);
  720. }
  721. }
  722. void CSProfileGenerator::extractProbesFromRange(const RangeSample &RangeCounter,
  723. ProbeCounterMap &ProbeCounter) {
  724. RangeSample Ranges;
  725. findDisjointRanges(Ranges, RangeCounter);
  726. for (const auto &Range : Ranges) {
  727. uint64_t RangeBegin = Binary->offsetToVirtualAddr(Range.first.first);
  728. uint64_t RangeEnd = Binary->offsetToVirtualAddr(Range.first.second);
  729. uint64_t Count = Range.second;
  730. // Disjoint ranges have introduce zero-filled gap that
  731. // doesn't belong to current context, filter them out.
  732. if (Count == 0)
  733. continue;
  734. InstructionPointer IP(Binary, RangeBegin, true);
  735. // Disjoint ranges may have range in the middle of two instr,
  736. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  737. // can be Addr1+1 to Addr2-1. We should ignore such range.
  738. if (IP.Address > RangeEnd)
  739. continue;
  740. do {
  741. const AddressProbesMap &Address2ProbesMap =
  742. Binary->getAddress2ProbesMap();
  743. auto It = Address2ProbesMap.find(IP.Address);
  744. if (It != Address2ProbesMap.end()) {
  745. for (const auto &Probe : It->second) {
  746. if (!Probe.isBlock())
  747. continue;
  748. ProbeCounter[&Probe] += Count;
  749. }
  750. }
  751. } while (IP.advance() && IP.Address <= RangeEnd);
  752. }
  753. }
  754. void CSProfileGenerator::populateBodySamplesWithProbes(
  755. const RangeSample &RangeCounter, SampleContextFrames ContextStack) {
  756. ProbeCounterMap ProbeCounter;
  757. // Extract the top frame probes by looking up each address among the range in
  758. // the Address2ProbeMap
  759. extractProbesFromRange(RangeCounter, ProbeCounter);
  760. std::unordered_map<MCDecodedPseudoProbeInlineTree *,
  761. std::unordered_set<FunctionSamples *>>
  762. FrameSamples;
  763. for (const auto &PI : ProbeCounter) {
  764. const MCDecodedPseudoProbe *Probe = PI.first;
  765. uint64_t Count = PI.second;
  766. FunctionSamples &FunctionProfile =
  767. getFunctionProfileForLeafProbe(ContextStack, Probe);
  768. // Record the current frame and FunctionProfile whenever samples are
  769. // collected for non-danglie probes. This is for reporting all of the
  770. // zero count probes of the frame later.
  771. FrameSamples[Probe->getInlineTreeNode()].insert(&FunctionProfile);
  772. FunctionProfile.addBodySamplesForProbe(Probe->getIndex(), Count);
  773. FunctionProfile.addTotalSamples(Count);
  774. if (Probe->isEntry()) {
  775. FunctionProfile.addHeadSamples(Count);
  776. // Look up for the caller's function profile
  777. const auto *InlinerDesc = Binary->getInlinerDescForProbe(Probe);
  778. SampleContextFrames CalleeContextId =
  779. FunctionProfile.getContext().getContextFrames();
  780. if (InlinerDesc != nullptr && CalleeContextId.size() > 1) {
  781. // Since the context id will be compressed, we have to use callee's
  782. // context id to infer caller's context id to ensure they share the
  783. // same context prefix.
  784. SampleContextFrameVector CallerContextId;
  785. SampleContextFrame &&CallerLeafFrameLoc =
  786. getCallerContext(CalleeContextId, CallerContextId);
  787. uint64_t CallerIndex = CallerLeafFrameLoc.Location.LineOffset;
  788. assert(CallerIndex &&
  789. "Inferred caller's location index shouldn't be zero!");
  790. FunctionSamples &CallerProfile =
  791. getFunctionProfileForContext(CallerContextId);
  792. CallerProfile.setFunctionHash(InlinerDesc->FuncHash);
  793. CallerProfile.addBodySamples(CallerIndex, 0, Count);
  794. CallerProfile.addTotalSamples(Count);
  795. CallerProfile.addCalledTargetSamples(
  796. CallerIndex, 0, FunctionProfile.getContext().getName(), Count);
  797. }
  798. }
  799. }
  800. // Assign zero count for remaining probes without sample hits to
  801. // differentiate from probes optimized away, of which the counts are unknown
  802. // and will be inferred by the compiler.
  803. for (auto &I : FrameSamples) {
  804. for (auto *FunctionProfile : I.second) {
  805. for (auto *Probe : I.first->getProbes()) {
  806. FunctionProfile->addBodySamplesForProbe(Probe->getIndex(), 0);
  807. }
  808. }
  809. }
  810. }
  811. void CSProfileGenerator::populateBoundarySamplesWithProbes(
  812. const BranchSample &BranchCounter, SampleContextFrames ContextStack) {
  813. for (const auto &BI : BranchCounter) {
  814. uint64_t SourceOffset = BI.first.first;
  815. uint64_t TargetOffset = BI.first.second;
  816. uint64_t Count = BI.second;
  817. uint64_t SourceAddress = Binary->offsetToVirtualAddr(SourceOffset);
  818. const MCDecodedPseudoProbe *CallProbe =
  819. Binary->getCallProbeForAddr(SourceAddress);
  820. if (CallProbe == nullptr)
  821. continue;
  822. FunctionSamples &FunctionProfile =
  823. getFunctionProfileForLeafProbe(ContextStack, CallProbe);
  824. FunctionProfile.addBodySamples(CallProbe->getIndex(), 0, Count);
  825. FunctionProfile.addTotalSamples(Count);
  826. StringRef CalleeName = getCalleeNameForOffset(TargetOffset);
  827. if (CalleeName.size() == 0)
  828. continue;
  829. FunctionProfile.addCalledTargetSamples(CallProbe->getIndex(), 0, CalleeName,
  830. Count);
  831. }
  832. }
  833. FunctionSamples &CSProfileGenerator::getFunctionProfileForLeafProbe(
  834. SampleContextFrames ContextStack, const MCDecodedPseudoProbe *LeafProbe) {
  835. // Explicitly copy the context for appending the leaf context
  836. SampleContextFrameVector NewContextStack(ContextStack.begin(),
  837. ContextStack.end());
  838. Binary->getInlineContextForProbe(LeafProbe, NewContextStack, true);
  839. // For leaf inlined context with the top frame, we should strip off the top
  840. // frame's probe id, like:
  841. // Inlined stack: [foo:1, bar:2], the ContextId will be "foo:1 @ bar"
  842. auto LeafFrame = NewContextStack.back();
  843. LeafFrame.Location = LineLocation(0, 0);
  844. NewContextStack.pop_back();
  845. // Compress the context string except for the leaf frame
  846. CSProfileGenerator::compressRecursionContext(NewContextStack);
  847. CSProfileGenerator::trimContext(NewContextStack);
  848. NewContextStack.push_back(LeafFrame);
  849. const auto *FuncDesc = Binary->getFuncDescForGUID(LeafProbe->getGuid());
  850. bool WasLeafInlined = LeafProbe->getInlineTreeNode()->hasInlineSite();
  851. FunctionSamples &FunctionProile =
  852. getFunctionProfileForContext(NewContextStack, WasLeafInlined);
  853. FunctionProile.setFunctionHash(FuncDesc->FuncHash);
  854. return FunctionProile;
  855. }
  856. } // end namespace sampleprof
  857. } // end namespace llvm