ProfileGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. static cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  10. cl::Required,
  11. cl::desc("Output profile file"));
  12. static cl::alias OutputA("o", cl::desc("Alias for --output"),
  13. cl::aliasopt(OutputFilename));
  14. static cl::opt<SampleProfileFormat> OutputFormat(
  15. "format", cl::desc("Format of output profile"), cl::init(SPF_Text),
  16. cl::values(
  17. clEnumValN(SPF_Binary, "binary", "Binary encoding (default)"),
  18. clEnumValN(SPF_Compact_Binary, "compbinary", "Compact binary encoding"),
  19. clEnumValN(SPF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  20. clEnumValN(SPF_Text, "text", "Text encoding"),
  21. clEnumValN(SPF_GCC, "gcc",
  22. "GCC encoding (only meaningful for -sample)")));
  23. static cl::opt<int32_t, true> RecursionCompression(
  24. "compress-recursion",
  25. cl::desc("Compressing recursion by deduplicating adjacent frame "
  26. "sequences up to the specified size. -1 means no size limit."),
  27. cl::Hidden,
  28. cl::location(llvm::sampleprof::CSProfileGenerator::MaxCompressionSize));
  29. static cl::opt<uint64_t> CSProfColdThres(
  30. "csprof-cold-thres", cl::init(100), cl::ZeroOrMore,
  31. cl::desc("Specify the total samples threshold for a context profile to "
  32. "be considered cold, any cold profiles will be merged into "
  33. "context-less base profiles"));
  34. static cl::opt<bool> CSProfKeepCold(
  35. "csprof-keep-cold", cl::init(false), cl::ZeroOrMore,
  36. cl::desc("This works together with --csprof-cold-thres. If the total count "
  37. "of the profile after all merge is done is still smaller than the "
  38. "csprof-cold-thres, it will be trimmed unless csprof-keep-cold "
  39. "flag is specified."));
  40. using namespace llvm;
  41. using namespace sampleprof;
  42. namespace llvm {
  43. namespace sampleprof {
  44. // Initialize the MaxCompressionSize to -1 which means no size limit
  45. int32_t CSProfileGenerator::MaxCompressionSize = -1;
  46. static bool
  47. usePseudoProbes(const BinarySampleCounterMap &BinarySampleCounters) {
  48. return BinarySampleCounters.size() &&
  49. BinarySampleCounters.begin()->first->usePseudoProbes();
  50. }
  51. std::unique_ptr<ProfileGenerator>
  52. ProfileGenerator::create(const BinarySampleCounterMap &BinarySampleCounters,
  53. enum PerfScriptType SampleType) {
  54. std::unique_ptr<ProfileGenerator> ProfileGenerator;
  55. if (SampleType == PERF_LBR_STACK) {
  56. if (usePseudoProbes(BinarySampleCounters)) {
  57. ProfileGenerator.reset(
  58. new PseudoProbeCSProfileGenerator(BinarySampleCounters));
  59. } else {
  60. ProfileGenerator.reset(new CSProfileGenerator(BinarySampleCounters));
  61. }
  62. } else {
  63. // TODO:
  64. llvm_unreachable("Unsupported perfscript!");
  65. }
  66. return ProfileGenerator;
  67. }
  68. void ProfileGenerator::write(std::unique_ptr<SampleProfileWriter> Writer,
  69. StringMap<FunctionSamples> &ProfileMap) {
  70. Writer->write(ProfileMap);
  71. }
  72. void ProfileGenerator::write() {
  73. auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
  74. if (std::error_code EC = WriterOrErr.getError())
  75. exitWithError(EC, OutputFilename);
  76. write(std::move(WriterOrErr.get()), ProfileMap);
  77. }
  78. void ProfileGenerator::findDisjointRanges(RangeSample &DisjointRanges,
  79. const RangeSample &Ranges) {
  80. /*
  81. Regions may overlap with each other. Using the boundary info, find all
  82. disjoint ranges and their sample count. BoundaryPoint contains the count
  83. multiple samples begin/end at this points.
  84. |<--100-->| Sample1
  85. |<------200------>| Sample2
  86. A B C
  87. In the example above,
  88. Sample1 begins at A, ends at B, its value is 100.
  89. Sample2 beings at A, ends at C, its value is 200.
  90. For A, BeginCount is the sum of sample begins at A, which is 300 and no
  91. samples ends at A, so EndCount is 0.
  92. Then boundary points A, B, and C with begin/end counts are:
  93. A: (300, 0)
  94. B: (0, 100)
  95. C: (0, 200)
  96. */
  97. struct BoundaryPoint {
  98. // Sum of sample counts beginning at this point
  99. uint64_t BeginCount;
  100. // Sum of sample counts ending at this point
  101. uint64_t EndCount;
  102. BoundaryPoint() : BeginCount(0), EndCount(0){};
  103. void addBeginCount(uint64_t Count) { BeginCount += Count; }
  104. void addEndCount(uint64_t Count) { EndCount += Count; }
  105. };
  106. /*
  107. For the above example. With boundary points, follwing logic finds two
  108. disjoint region of
  109. [A,B]: 300
  110. [B+1,C]: 200
  111. If there is a boundary point that both begin and end, the point itself
  112. becomes a separate disjoint region. For example, if we have original
  113. ranges of
  114. |<--- 100 --->|
  115. |<--- 200 --->|
  116. A B C
  117. there are three boundary points with their begin/end counts of
  118. A: (100, 0)
  119. B: (200, 100)
  120. C: (0, 200)
  121. the disjoint ranges would be
  122. [A, B-1]: 100
  123. [B, B]: 300
  124. [B+1, C]: 200.
  125. */
  126. std::map<uint64_t, BoundaryPoint> Boundaries;
  127. for (auto Item : Ranges) {
  128. uint64_t Begin = Item.first.first;
  129. uint64_t End = Item.first.second;
  130. uint64_t Count = Item.second;
  131. if (Boundaries.find(Begin) == Boundaries.end())
  132. Boundaries[Begin] = BoundaryPoint();
  133. Boundaries[Begin].addBeginCount(Count);
  134. if (Boundaries.find(End) == Boundaries.end())
  135. Boundaries[End] = BoundaryPoint();
  136. Boundaries[End].addEndCount(Count);
  137. }
  138. uint64_t BeginAddress = 0;
  139. int Count = 0;
  140. for (auto Item : Boundaries) {
  141. uint64_t Address = Item.first;
  142. BoundaryPoint &Point = Item.second;
  143. if (Point.BeginCount) {
  144. if (BeginAddress)
  145. DisjointRanges[{BeginAddress, Address - 1}] = Count;
  146. Count += Point.BeginCount;
  147. BeginAddress = Address;
  148. }
  149. if (Point.EndCount) {
  150. assert(BeginAddress && "First boundary point cannot be 'end' point");
  151. DisjointRanges[{BeginAddress, Address}] = Count;
  152. Count -= Point.EndCount;
  153. BeginAddress = Address + 1;
  154. }
  155. }
  156. }
  157. FunctionSamples &
  158. CSProfileGenerator::getFunctionProfileForContext(StringRef ContextStr) {
  159. auto Ret = ProfileMap.try_emplace(ContextStr, FunctionSamples());
  160. if (Ret.second) {
  161. SampleContext FContext(Ret.first->first(), RawContext);
  162. FunctionSamples &FProfile = Ret.first->second;
  163. FProfile.setContext(FContext);
  164. }
  165. return Ret.first->second;
  166. }
  167. void CSProfileGenerator::updateBodySamplesforFunctionProfile(
  168. FunctionSamples &FunctionProfile, const FrameLocation &LeafLoc,
  169. uint64_t Count) {
  170. // Filter out invalid negative(int type) lineOffset
  171. if (LeafLoc.second.LineOffset & 0x80000000)
  172. return;
  173. // Use the maximum count of samples with same line location
  174. ErrorOr<uint64_t> R = FunctionProfile.findSamplesAt(
  175. LeafLoc.second.LineOffset, LeafLoc.second.Discriminator);
  176. uint64_t PreviousCount = R ? R.get() : 0;
  177. if (PreviousCount < Count) {
  178. FunctionProfile.addBodySamples(LeafLoc.second.LineOffset,
  179. LeafLoc.second.Discriminator,
  180. Count - PreviousCount);
  181. }
  182. }
  183. void CSProfileGenerator::populateFunctionBodySamples(
  184. FunctionSamples &FunctionProfile, const RangeSample &RangeCounter,
  185. ProfiledBinary *Binary) {
  186. // Compute disjoint ranges first, so we can use MAX
  187. // for calculating count for each location.
  188. RangeSample Ranges;
  189. findDisjointRanges(Ranges, RangeCounter);
  190. for (auto Range : Ranges) {
  191. uint64_t RangeBegin = Binary->offsetToVirtualAddr(Range.first.first);
  192. uint64_t RangeEnd = Binary->offsetToVirtualAddr(Range.first.second);
  193. uint64_t Count = Range.second;
  194. // Disjoint ranges have introduce zero-filled gap that
  195. // doesn't belong to current context, filter them out.
  196. if (Count == 0)
  197. continue;
  198. InstructionPointer IP(Binary, RangeBegin, true);
  199. // Disjoint ranges may have range in the middle of two instr,
  200. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  201. // can be Addr1+1 to Addr2-1. We should ignore such range.
  202. if (IP.Address > RangeEnd)
  203. continue;
  204. while (IP.Address <= RangeEnd) {
  205. uint64_t Offset = Binary->virtualAddrToOffset(IP.Address);
  206. auto LeafLoc = Binary->getInlineLeafFrameLoc(Offset);
  207. if (LeafLoc.hasValue()) {
  208. // Recording body sample for this specific context
  209. updateBodySamplesforFunctionProfile(FunctionProfile, *LeafLoc, Count);
  210. }
  211. // Accumulate total sample count even it's a line with invalid debug info
  212. FunctionProfile.addTotalSamples(Count);
  213. // Move to next IP within the range
  214. IP.advance();
  215. }
  216. }
  217. }
  218. void CSProfileGenerator::populateFunctionBoundarySamples(
  219. StringRef ContextId, FunctionSamples &FunctionProfile,
  220. const BranchSample &BranchCounters, ProfiledBinary *Binary) {
  221. for (auto Entry : BranchCounters) {
  222. uint64_t SourceOffset = Entry.first.first;
  223. uint64_t TargetOffset = Entry.first.second;
  224. uint64_t Count = Entry.second;
  225. // Get the callee name by branch target if it's a call branch
  226. StringRef CalleeName = FunctionSamples::getCanonicalFnName(
  227. Binary->getFuncFromStartOffset(TargetOffset));
  228. if (CalleeName.size() == 0)
  229. continue;
  230. // Record called target sample and its count
  231. auto LeafLoc = Binary->getInlineLeafFrameLoc(SourceOffset);
  232. if (!LeafLoc.hasValue())
  233. continue;
  234. FunctionProfile.addCalledTargetSamples(LeafLoc->second.LineOffset,
  235. LeafLoc->second.Discriminator,
  236. CalleeName, Count);
  237. // Record head sample for called target(callee)
  238. std::ostringstream OCalleeCtxStr;
  239. if (ContextId.find(" @ ") != StringRef::npos) {
  240. OCalleeCtxStr << ContextId.rsplit(" @ ").first.str();
  241. OCalleeCtxStr << " @ ";
  242. }
  243. OCalleeCtxStr << getCallSite(*LeafLoc) << " @ " << CalleeName.str();
  244. FunctionSamples &CalleeProfile =
  245. getFunctionProfileForContext(OCalleeCtxStr.str());
  246. assert(Count != 0 && "Unexpected zero weight branch");
  247. CalleeProfile.addHeadSamples(Count);
  248. }
  249. }
  250. static FrameLocation getCallerContext(StringRef CalleeContext,
  251. StringRef &CallerNameWithContext) {
  252. StringRef CallerContext = CalleeContext.rsplit(" @ ").first;
  253. CallerNameWithContext = CallerContext.rsplit(':').first;
  254. auto ContextSplit = CallerContext.rsplit(" @ ");
  255. StringRef CallerFrameStr = ContextSplit.second.size() == 0
  256. ? ContextSplit.first
  257. : ContextSplit.second;
  258. FrameLocation LeafFrameLoc = {"", {0, 0}};
  259. StringRef Funcname;
  260. SampleContext::decodeContextString(CallerFrameStr, Funcname,
  261. LeafFrameLoc.second);
  262. LeafFrameLoc.first = Funcname.str();
  263. return LeafFrameLoc;
  264. }
  265. void CSProfileGenerator::populateInferredFunctionSamples() {
  266. for (const auto &Item : ProfileMap) {
  267. const StringRef CalleeContext = Item.first();
  268. const FunctionSamples &CalleeProfile = Item.second;
  269. // If we already have head sample counts, we must have value profile
  270. // for call sites added already. Skip to avoid double counting.
  271. if (CalleeProfile.getHeadSamples())
  272. continue;
  273. // If we don't have context, nothing to do for caller's call site.
  274. // This could happen for entry point function.
  275. if (CalleeContext.find(" @ ") == StringRef::npos)
  276. continue;
  277. // Infer Caller's frame loc and context ID through string splitting
  278. StringRef CallerContextId;
  279. FrameLocation &&CallerLeafFrameLoc =
  280. getCallerContext(CalleeContext, CallerContextId);
  281. // It's possible that we haven't seen any sample directly in the caller,
  282. // in which case CallerProfile will not exist. But we can't modify
  283. // ProfileMap while iterating it.
  284. // TODO: created function profile for those callers too
  285. if (ProfileMap.find(CallerContextId) == ProfileMap.end())
  286. continue;
  287. FunctionSamples &CallerProfile = ProfileMap[CallerContextId];
  288. // Since we don't have call count for inlined functions, we
  289. // estimate it from inlinee's profile using entry body sample.
  290. uint64_t EstimatedCallCount = CalleeProfile.getEntrySamples();
  291. // If we don't have samples with location, use 1 to indicate live.
  292. if (!EstimatedCallCount && !CalleeProfile.getBodySamples().size())
  293. EstimatedCallCount = 1;
  294. CallerProfile.addCalledTargetSamples(
  295. CallerLeafFrameLoc.second.LineOffset,
  296. CallerLeafFrameLoc.second.Discriminator,
  297. CalleeProfile.getContext().getNameWithoutContext(), EstimatedCallCount);
  298. CallerProfile.addBodySamples(CallerLeafFrameLoc.second.LineOffset,
  299. CallerLeafFrameLoc.second.Discriminator,
  300. EstimatedCallCount);
  301. CallerProfile.addTotalSamples(EstimatedCallCount);
  302. }
  303. }
  304. void CSProfileGenerator::mergeAndTrimColdProfile(
  305. StringMap<FunctionSamples> &ProfileMap) {
  306. // Nothing to merge if sample threshold is zero
  307. if (!CSProfColdThres)
  308. return;
  309. // Filter the cold profiles from ProfileMap and move them into a tmp
  310. // container
  311. std::vector<std::pair<StringRef, const FunctionSamples *>> ToRemoveVec;
  312. for (const auto &I : ProfileMap) {
  313. const FunctionSamples &FunctionProfile = I.second;
  314. if (FunctionProfile.getTotalSamples() >= CSProfColdThres)
  315. continue;
  316. ToRemoveVec.emplace_back(I.getKey(), &I.second);
  317. }
  318. // Remove the code profile from ProfileMap and merge them into BaseProileMap
  319. StringMap<FunctionSamples> BaseProfileMap;
  320. for (const auto &I : ToRemoveVec) {
  321. auto Ret = BaseProfileMap.try_emplace(
  322. I.second->getContext().getNameWithoutContext(), FunctionSamples());
  323. FunctionSamples &BaseProfile = Ret.first->second;
  324. BaseProfile.merge(*I.second);
  325. ProfileMap.erase(I.first);
  326. }
  327. // Merge the base profiles into ProfileMap;
  328. for (const auto &I : BaseProfileMap) {
  329. // Filter the cold base profile
  330. if (!CSProfKeepCold && I.second.getTotalSamples() < CSProfColdThres &&
  331. ProfileMap.find(I.getKey()) == ProfileMap.end())
  332. continue;
  333. // Merge the profile if the original profile exists, otherwise just insert
  334. // as a new profile
  335. FunctionSamples &OrigProfile = getFunctionProfileForContext(I.getKey());
  336. OrigProfile.merge(I.second);
  337. }
  338. }
  339. void CSProfileGenerator::write(std::unique_ptr<SampleProfileWriter> Writer,
  340. StringMap<FunctionSamples> &ProfileMap) {
  341. mergeAndTrimColdProfile(ProfileMap);
  342. // Add bracket for context key to support different profile binary format
  343. StringMap<FunctionSamples> CxtWithBracketPMap;
  344. for (const auto &Item : ProfileMap) {
  345. std::string ContextWithBracket = "[" + Item.first().str() + "]";
  346. auto Ret = CxtWithBracketPMap.try_emplace(ContextWithBracket, Item.second);
  347. assert(Ret.second && "Must be a unique context");
  348. SampleContext FContext(Ret.first->first(), RawContext);
  349. FunctionSamples &FProfile = Ret.first->second;
  350. FProfile.setName(FContext.getNameWithContext(true));
  351. FProfile.setContext(FContext);
  352. }
  353. Writer->write(CxtWithBracketPMap);
  354. }
  355. // Helper function to extract context prefix string stack
  356. // Extract context stack for reusing, leaf context stack will
  357. // be added compressed while looking up function profile
  358. static void
  359. extractPrefixContextStack(SmallVectorImpl<std::string> &ContextStrStack,
  360. const SmallVectorImpl<const PseudoProbe *> &Probes,
  361. ProfiledBinary *Binary) {
  362. for (const auto *P : Probes) {
  363. Binary->getInlineContextForProbe(P, ContextStrStack, true);
  364. }
  365. }
  366. void PseudoProbeCSProfileGenerator::generateProfile() {
  367. // Enable pseudo probe functionalities in SampleProf
  368. FunctionSamples::ProfileIsProbeBased = true;
  369. for (const auto &BI : BinarySampleCounters) {
  370. ProfiledBinary *Binary = BI.first;
  371. for (const auto &CI : BI.second) {
  372. const ProbeBasedCtxKey *CtxKey =
  373. dyn_cast<ProbeBasedCtxKey>(CI.first.getPtr());
  374. SmallVector<std::string, 16> ContextStrStack;
  375. extractPrefixContextStack(ContextStrStack, CtxKey->Probes, Binary);
  376. // Fill in function body samples from probes, also infer caller's samples
  377. // from callee's probe
  378. populateBodySamplesWithProbes(CI.second.RangeCounter, ContextStrStack,
  379. Binary);
  380. // Fill in boundary samples for a call probe
  381. populateBoundarySamplesWithProbes(CI.second.BranchCounter,
  382. ContextStrStack, Binary);
  383. }
  384. }
  385. }
  386. void PseudoProbeCSProfileGenerator::extractProbesFromRange(
  387. const RangeSample &RangeCounter, ProbeCounterMap &ProbeCounter,
  388. ProfiledBinary *Binary) {
  389. RangeSample Ranges;
  390. findDisjointRanges(Ranges, RangeCounter);
  391. for (const auto &Range : Ranges) {
  392. uint64_t RangeBegin = Binary->offsetToVirtualAddr(Range.first.first);
  393. uint64_t RangeEnd = Binary->offsetToVirtualAddr(Range.first.second);
  394. uint64_t Count = Range.second;
  395. // Disjoint ranges have introduce zero-filled gap that
  396. // doesn't belong to current context, filter them out.
  397. if (Count == 0)
  398. continue;
  399. InstructionPointer IP(Binary, RangeBegin, true);
  400. // Disjoint ranges may have range in the middle of two instr,
  401. // e.g. If Instr1 at Addr1, and Instr2 at Addr2, disjoint range
  402. // can be Addr1+1 to Addr2-1. We should ignore such range.
  403. if (IP.Address > RangeEnd)
  404. continue;
  405. while (IP.Address <= RangeEnd) {
  406. const AddressProbesMap &Address2ProbesMap =
  407. Binary->getAddress2ProbesMap();
  408. auto It = Address2ProbesMap.find(IP.Address);
  409. if (It != Address2ProbesMap.end()) {
  410. for (const auto &Probe : It->second) {
  411. if (!Probe.isBlock())
  412. continue;
  413. ProbeCounter[&Probe] += Count;
  414. }
  415. }
  416. IP.advance();
  417. }
  418. }
  419. }
  420. void PseudoProbeCSProfileGenerator::populateBodySamplesWithProbes(
  421. const RangeSample &RangeCounter,
  422. SmallVectorImpl<std::string> &ContextStrStack, ProfiledBinary *Binary) {
  423. ProbeCounterMap ProbeCounter;
  424. // Extract the top frame probes by looking up each address among the range in
  425. // the Address2ProbeMap
  426. extractProbesFromRange(RangeCounter, ProbeCounter, Binary);
  427. for (auto PI : ProbeCounter) {
  428. const PseudoProbe *Probe = PI.first;
  429. uint64_t Count = PI.second;
  430. FunctionSamples &FunctionProfile =
  431. getFunctionProfileForLeafProbe(ContextStrStack, Probe, Binary);
  432. FunctionProfile.addBodySamples(Probe->Index, 0, Count);
  433. FunctionProfile.addTotalSamples(Count);
  434. if (Probe->isEntry()) {
  435. FunctionProfile.addHeadSamples(Count);
  436. // Look up for the caller's function profile
  437. const auto *InlinerDesc = Binary->getInlinerDescForProbe(Probe);
  438. if (InlinerDesc != nullptr) {
  439. // Since the context id will be compressed, we have to use callee's
  440. // context id to infer caller's context id to ensure they share the
  441. // same context prefix.
  442. StringRef CalleeContextId =
  443. FunctionProfile.getContext().getNameWithContext(true);
  444. StringRef CallerContextId;
  445. FrameLocation &&CallerLeafFrameLoc =
  446. getCallerContext(CalleeContextId, CallerContextId);
  447. uint64_t CallerIndex = CallerLeafFrameLoc.second.LineOffset;
  448. assert(CallerIndex &&
  449. "Inferred caller's location index shouldn't be zero!");
  450. FunctionSamples &CallerProfile =
  451. getFunctionProfileForContext(CallerContextId);
  452. CallerProfile.setFunctionHash(InlinerDesc->FuncHash);
  453. CallerProfile.addBodySamples(CallerIndex, 0, Count);
  454. CallerProfile.addTotalSamples(Count);
  455. CallerProfile.addCalledTargetSamples(
  456. CallerIndex, 0,
  457. FunctionProfile.getContext().getNameWithoutContext(), Count);
  458. }
  459. }
  460. }
  461. }
  462. void PseudoProbeCSProfileGenerator::populateBoundarySamplesWithProbes(
  463. const BranchSample &BranchCounter,
  464. SmallVectorImpl<std::string> &ContextStrStack, ProfiledBinary *Binary) {
  465. for (auto BI : BranchCounter) {
  466. uint64_t SourceOffset = BI.first.first;
  467. uint64_t TargetOffset = BI.first.second;
  468. uint64_t Count = BI.second;
  469. uint64_t SourceAddress = Binary->offsetToVirtualAddr(SourceOffset);
  470. const PseudoProbe *CallProbe = Binary->getCallProbeForAddr(SourceAddress);
  471. if (CallProbe == nullptr)
  472. continue;
  473. FunctionSamples &FunctionProfile =
  474. getFunctionProfileForLeafProbe(ContextStrStack, CallProbe, Binary);
  475. FunctionProfile.addBodySamples(CallProbe->Index, 0, Count);
  476. FunctionProfile.addTotalSamples(Count);
  477. StringRef CalleeName = FunctionSamples::getCanonicalFnName(
  478. Binary->getFuncFromStartOffset(TargetOffset));
  479. if (CalleeName.size() == 0)
  480. continue;
  481. FunctionProfile.addCalledTargetSamples(CallProbe->Index, 0, CalleeName,
  482. Count);
  483. }
  484. }
  485. FunctionSamples &PseudoProbeCSProfileGenerator::getFunctionProfileForLeafProbe(
  486. SmallVectorImpl<std::string> &ContextStrStack,
  487. const PseudoProbeFuncDesc *LeafFuncDesc) {
  488. assert(ContextStrStack.size() && "Profile context must have the leaf frame");
  489. // Compress the context string except for the leaf frame
  490. std::string LeafFrame = ContextStrStack.back();
  491. ContextStrStack.pop_back();
  492. CSProfileGenerator::compressRecursionContext(ContextStrStack);
  493. std::ostringstream OContextStr;
  494. for (uint32_t I = 0; I < ContextStrStack.size(); I++) {
  495. if (OContextStr.str().size())
  496. OContextStr << " @ ";
  497. OContextStr << ContextStrStack[I];
  498. }
  499. // For leaf inlined context with the top frame, we should strip off the top
  500. // frame's probe id, like:
  501. // Inlined stack: [foo:1, bar:2], the ContextId will be "foo:1 @ bar"
  502. if (OContextStr.str().size())
  503. OContextStr << " @ ";
  504. OContextStr << StringRef(LeafFrame).split(":").first.str();
  505. FunctionSamples &FunctionProile =
  506. getFunctionProfileForContext(OContextStr.str());
  507. FunctionProile.setFunctionHash(LeafFuncDesc->FuncHash);
  508. return FunctionProile;
  509. }
  510. FunctionSamples &PseudoProbeCSProfileGenerator::getFunctionProfileForLeafProbe(
  511. SmallVectorImpl<std::string> &ContextStrStack, const PseudoProbe *LeafProbe,
  512. ProfiledBinary *Binary) {
  513. // Explicitly copy the context for appending the leaf context
  514. SmallVector<std::string, 16> ContextStrStackCopy(ContextStrStack.begin(),
  515. ContextStrStack.end());
  516. Binary->getInlineContextForProbe(LeafProbe, ContextStrStackCopy);
  517. // Note that the context from probe doesn't include leaf frame,
  518. // hence we need to retrieve and append the leaf frame.
  519. const auto *FuncDesc = Binary->getFuncDescForGUID(LeafProbe->GUID);
  520. ContextStrStackCopy.emplace_back(FuncDesc->FuncName + ":" +
  521. Twine(LeafProbe->Index).str());
  522. return getFunctionProfileForLeafProbe(ContextStrStackCopy, FuncDesc);
  523. }
  524. } // end namespace sampleprof
  525. } // end namespace llvm