ProfileGenerator.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //===-- ProfileGenerator.h - 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. #ifndef LLVM_TOOLS_LLVM_PROGEN_PROFILEGENERATOR_H
  9. #define LLVM_TOOLS_LLVM_PROGEN_PROFILEGENERATOR_H
  10. #include "CSPreInliner.h"
  11. #include "ErrorHandling.h"
  12. #include "PerfReader.h"
  13. #include "ProfiledBinary.h"
  14. #include "llvm/ProfileData/SampleProfWriter.h"
  15. #include <memory>
  16. #include <unordered_set>
  17. using namespace llvm;
  18. using namespace sampleprof;
  19. namespace llvm {
  20. namespace sampleprof {
  21. // This base class for profile generation of sample-based PGO. We reuse all
  22. // structures relating to function profiles and profile writers as seen in
  23. // /ProfileData/SampleProf.h.
  24. class ProfileGeneratorBase {
  25. public:
  26. ProfileGeneratorBase(ProfiledBinary *Binary,
  27. const ContextSampleCounterMap &Counters)
  28. : Binary(Binary), SampleCounters(Counters){};
  29. virtual ~ProfileGeneratorBase() = default;
  30. static std::unique_ptr<ProfileGeneratorBase>
  31. create(ProfiledBinary *Binary, const ContextSampleCounterMap &SampleCounters,
  32. bool ProfileIsCSFlat);
  33. virtual void generateProfile() = 0;
  34. void write();
  35. static uint32_t
  36. getDuplicationFactor(unsigned Discriminator,
  37. bool UseFSD = ProfileGeneratorBase::UseFSDiscriminator) {
  38. return UseFSD ? 1
  39. : llvm::DILocation::getDuplicationFactorFromDiscriminator(
  40. Discriminator);
  41. }
  42. static uint32_t
  43. getBaseDiscriminator(unsigned Discriminator,
  44. bool UseFSD = ProfileGeneratorBase::UseFSDiscriminator) {
  45. return UseFSD ? Discriminator
  46. : DILocation::getBaseDiscriminatorFromDiscriminator(
  47. Discriminator, /* IsFSDiscriminator */ false);
  48. }
  49. static bool UseFSDiscriminator;
  50. protected:
  51. // Use SampleProfileWriter to serialize profile map
  52. void write(std::unique_ptr<SampleProfileWriter> Writer,
  53. SampleProfileMap &ProfileMap);
  54. /*
  55. For each region boundary point, mark if it is begin or end (or both) of
  56. the region. Boundary points are inclusive. Log the sample count as well
  57. so we can use it when we compute the sample count of each disjoint region
  58. later. Note that there might be multiple ranges with different sample
  59. count that share same begin/end point. We need to accumulate the sample
  60. count for the boundary point for such case, because for the example
  61. below,
  62. |<--100-->|
  63. |<------200------>|
  64. A B C
  65. sample count for disjoint region [A,B] would be 300.
  66. */
  67. void findDisjointRanges(RangeSample &DisjointRanges,
  68. const RangeSample &Ranges);
  69. // Helper function for updating body sample for a leaf location in
  70. // FunctionProfile
  71. void updateBodySamplesforFunctionProfile(FunctionSamples &FunctionProfile,
  72. const SampleContextFrame &LeafLoc,
  73. uint64_t Count);
  74. void updateTotalSamples();
  75. StringRef getCalleeNameForOffset(uint64_t TargetOffset);
  76. void computeSummaryAndThreshold();
  77. void calculateAndShowDensity(const SampleProfileMap &Profiles);
  78. double calculateDensity(const SampleProfileMap &Profiles,
  79. uint64_t HotCntThreshold);
  80. void showDensitySuggestion(double Density);
  81. // Thresholds from profile summary to answer isHotCount/isColdCount queries.
  82. uint64_t HotCountThreshold;
  83. uint64_t ColdCountThreshold;
  84. // Used by SampleProfileWriter
  85. SampleProfileMap ProfileMap;
  86. ProfiledBinary *Binary = nullptr;
  87. const ContextSampleCounterMap &SampleCounters;
  88. };
  89. class ProfileGenerator : public ProfileGeneratorBase {
  90. public:
  91. ProfileGenerator(ProfiledBinary *Binary,
  92. const ContextSampleCounterMap &Counters)
  93. : ProfileGeneratorBase(Binary, Counters){};
  94. void generateProfile() override;
  95. private:
  96. void generateLineNumBasedProfile();
  97. RangeSample preprocessRangeCounter(const RangeSample &RangeCounter);
  98. FunctionSamples &getTopLevelFunctionProfile(StringRef FuncName);
  99. // Helper function to get the leaf frame's FunctionProfile by traversing the
  100. // inline stack and meanwhile it adds the total samples for each frame's
  101. // function profile.
  102. FunctionSamples &
  103. getLeafProfileAndAddTotalSamples(const SampleContextFrameVector &FrameVec,
  104. uint64_t Count);
  105. void populateBodySamplesForAllFunctions(const RangeSample &RangeCounter);
  106. void
  107. populateBoundarySamplesForAllFunctions(const BranchSample &BranchCounters);
  108. void postProcessProfiles();
  109. void trimColdProfiles(const SampleProfileMap &Profiles,
  110. uint64_t ColdCntThreshold);
  111. };
  112. using ProbeCounterMap =
  113. std::unordered_map<const MCDecodedPseudoProbe *, uint64_t>;
  114. class CSProfileGenerator : public ProfileGeneratorBase {
  115. public:
  116. CSProfileGenerator(ProfiledBinary *Binary,
  117. const ContextSampleCounterMap &Counters)
  118. : ProfileGeneratorBase(Binary, Counters){};
  119. void generateProfile() override;
  120. // Trim the context stack at a given depth.
  121. template <typename T>
  122. static void trimContext(SmallVectorImpl<T> &S, int Depth = MaxContextDepth) {
  123. if (Depth < 0 || static_cast<size_t>(Depth) >= S.size())
  124. return;
  125. std::copy(S.begin() + S.size() - static_cast<size_t>(Depth), S.end(),
  126. S.begin());
  127. S.resize(Depth);
  128. }
  129. // Remove adjacent repeated context sequences up to a given sequence length,
  130. // -1 means no size limit. Note that repeated sequences are identified based
  131. // on the exact call site, this is finer granularity than function recursion.
  132. template <typename T>
  133. static void compressRecursionContext(SmallVectorImpl<T> &Context,
  134. int32_t CSize = MaxCompressionSize) {
  135. uint32_t I = 1;
  136. uint32_t HS = static_cast<uint32_t>(Context.size() / 2);
  137. uint32_t MaxDedupSize =
  138. CSize == -1 ? HS : std::min(static_cast<uint32_t>(CSize), HS);
  139. auto BeginIter = Context.begin();
  140. // Use an in-place algorithm to save memory copy
  141. // End indicates the end location of current iteration's data
  142. uint32_t End = 0;
  143. // Deduplicate from length 1 to the max possible size of a repeated
  144. // sequence.
  145. while (I <= MaxDedupSize) {
  146. // This is a linear algorithm that deduplicates adjacent repeated
  147. // sequences of size I. The deduplication detection runs on a sliding
  148. // window whose size is 2*I and it keeps sliding the window to deduplicate
  149. // the data inside. Once duplication is detected, deduplicate it by
  150. // skipping the right half part of the window, otherwise just copy back
  151. // the new one by appending them at the back of End pointer(for the next
  152. // iteration).
  153. //
  154. // For example:
  155. // Input: [a1, a2, b1, b2]
  156. // (Added index to distinguish the same char, the origin is [a, a, b,
  157. // b], the size of the dedup window is 2(I = 1) at the beginning)
  158. //
  159. // 1) The initial status is a dummy window[null, a1], then just copy the
  160. // right half of the window(End = 0), then slide the window.
  161. // Result: [a1], a2, b1, b2 (End points to the element right before ],
  162. // after ] is the data of the previous iteration)
  163. //
  164. // 2) Next window is [a1, a2]. Since a1 == a2, then skip the right half of
  165. // the window i.e the duplication happen. Only slide the window.
  166. // Result: [a1], a2, b1, b2
  167. //
  168. // 3) Next window is [a2, b1], copy the right half of the window(b1 is
  169. // new) to the End and slide the window.
  170. // Result: [a1, b1], b1, b2
  171. //
  172. // 4) Next window is [b1, b2], same to 2), skip b2.
  173. // Result: [a1, b1], b1, b2
  174. // After resize, it will be [a, b]
  175. // Use pointers like below to do comparison inside the window
  176. // [a b c a b c]
  177. // | | | | |
  178. // LeftBoundary Left Right Left+I Right+I
  179. // A duplication found if Left < LeftBoundry.
  180. int32_t Right = I - 1;
  181. End = I;
  182. int32_t LeftBoundary = 0;
  183. while (Right + I < Context.size()) {
  184. // To avoids scanning a part of a sequence repeatedly, it finds out
  185. // the common suffix of two hald in the window. The common suffix will
  186. // serve as the common prefix of next possible pair of duplicate
  187. // sequences. The non-common part will be ignored and never scanned
  188. // again.
  189. // For example.
  190. // Input: [a, b1], c1, b2, c2
  191. // I = 2
  192. //
  193. // 1) For the window [a, b1, c1, b2], non-common-suffix for the right
  194. // part is 'c1', copy it and only slide the window 1 step.
  195. // Result: [a, b1, c1], b2, c2
  196. //
  197. // 2) Next window is [b1, c1, b2, c2], so duplication happen.
  198. // Result after resize: [a, b, c]
  199. int32_t Left = Right;
  200. while (Left >= LeftBoundary && Context[Left] == Context[Left + I]) {
  201. // Find the longest suffix inside the window. When stops, Left points
  202. // at the diverging point in the current sequence.
  203. Left--;
  204. }
  205. bool DuplicationFound = (Left < LeftBoundary);
  206. // Don't need to recheck the data before Right
  207. LeftBoundary = Right + 1;
  208. if (DuplicationFound) {
  209. // Duplication found, skip right half of the window.
  210. Right += I;
  211. } else {
  212. // Copy the non-common-suffix part of the adjacent sequence.
  213. std::copy(BeginIter + Right + 1, BeginIter + Left + I + 1,
  214. BeginIter + End);
  215. End += Left + I - Right;
  216. // Only slide the window by the size of non-common-suffix
  217. Right = Left + I;
  218. }
  219. }
  220. // Don't forget the remaining part that's not scanned.
  221. std::copy(BeginIter + Right + 1, Context.end(), BeginIter + End);
  222. End += Context.size() - Right - 1;
  223. I++;
  224. Context.resize(End);
  225. MaxDedupSize = std::min(static_cast<uint32_t>(End / 2), MaxDedupSize);
  226. }
  227. }
  228. private:
  229. void generateLineNumBasedProfile();
  230. // Lookup or create FunctionSamples for the context
  231. FunctionSamples &
  232. getFunctionProfileForContext(const SampleContextFrameVector &Context,
  233. bool WasLeafInlined = false);
  234. // For profiled only functions, on-demand compute their inline context
  235. // function byte size which is used by the pre-inliner.
  236. void computeSizeForProfiledFunctions();
  237. // Post processing for profiles before writing out, such as mermining
  238. // and trimming cold profiles, running preinliner on profiles.
  239. void postProcessProfiles();
  240. void populateBodySamplesForFunction(FunctionSamples &FunctionProfile,
  241. const RangeSample &RangeCounters);
  242. void populateBoundarySamplesForFunction(SampleContextFrames ContextId,
  243. FunctionSamples &FunctionProfile,
  244. const BranchSample &BranchCounters);
  245. void populateInferredFunctionSamples();
  246. void generateProbeBasedProfile();
  247. // Go through each address from range to extract the top frame probe by
  248. // looking up in the Address2ProbeMap
  249. void extractProbesFromRange(const RangeSample &RangeCounter,
  250. ProbeCounterMap &ProbeCounter);
  251. // Fill in function body samples from probes
  252. void populateBodySamplesWithProbes(const RangeSample &RangeCounter,
  253. SampleContextFrames ContextStack);
  254. // Fill in boundary samples for a call probe
  255. void populateBoundarySamplesWithProbes(const BranchSample &BranchCounter,
  256. SampleContextFrames ContextStack);
  257. // Helper function to get FunctionSamples for the leaf probe
  258. FunctionSamples &
  259. getFunctionProfileForLeafProbe(SampleContextFrames ContextStack,
  260. const MCDecodedPseudoProbe *LeafProbe);
  261. // Underlying context table serves for sample profile writer.
  262. std::unordered_set<SampleContextFrameVector, SampleContextFrameHash> Contexts;
  263. public:
  264. // Deduplicate adjacent repeated context sequences up to a given sequence
  265. // length. -1 means no size limit.
  266. static int32_t MaxCompressionSize;
  267. static int MaxContextDepth;
  268. };
  269. } // end namespace sampleprof
  270. } // end namespace llvm
  271. #endif