SampleProf.h 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SampleProf.h - Sampling profiling format support ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file contains common definitions used in the reading and writing of
  15. // sample profile data.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
  19. #define LLVM_PROFILEDATA_SAMPLEPROF_H
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/GlobalValue.h"
  27. #include "llvm/Support/Allocator.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorOr.h"
  30. #include "llvm/Support/MathExtras.h"
  31. #include <algorithm>
  32. #include <cstdint>
  33. #include <list>
  34. #include <map>
  35. #include <set>
  36. #include <sstream>
  37. #include <string>
  38. #include <system_error>
  39. #include <unordered_map>
  40. #include <utility>
  41. namespace llvm {
  42. class DILocation;
  43. class raw_ostream;
  44. const std::error_category &sampleprof_category();
  45. enum class sampleprof_error {
  46. success = 0,
  47. bad_magic,
  48. unsupported_version,
  49. too_large,
  50. truncated,
  51. malformed,
  52. unrecognized_format,
  53. unsupported_writing_format,
  54. truncated_name_table,
  55. not_implemented,
  56. counter_overflow,
  57. ostream_seek_unsupported,
  58. uncompress_failed,
  59. zlib_unavailable,
  60. hash_mismatch
  61. };
  62. inline std::error_code make_error_code(sampleprof_error E) {
  63. return std::error_code(static_cast<int>(E), sampleprof_category());
  64. }
  65. inline sampleprof_error MergeResult(sampleprof_error &Accumulator,
  66. sampleprof_error Result) {
  67. // Prefer first error encountered as later errors may be secondary effects of
  68. // the initial problem.
  69. if (Accumulator == sampleprof_error::success &&
  70. Result != sampleprof_error::success)
  71. Accumulator = Result;
  72. return Accumulator;
  73. }
  74. } // end namespace llvm
  75. namespace std {
  76. template <>
  77. struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
  78. } // end namespace std
  79. namespace llvm {
  80. namespace sampleprof {
  81. enum SampleProfileFormat {
  82. SPF_None = 0,
  83. SPF_Text = 0x1,
  84. SPF_Compact_Binary = 0x2,
  85. SPF_GCC = 0x3,
  86. SPF_Ext_Binary = 0x4,
  87. SPF_Binary = 0xff
  88. };
  89. static inline uint64_t SPMagic(SampleProfileFormat Format = SPF_Binary) {
  90. return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
  91. uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
  92. uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
  93. uint64_t('2') << (64 - 56) | uint64_t(Format);
  94. }
  95. /// Get the proper representation of a string according to whether the
  96. /// current Format uses MD5 to represent the string.
  97. static inline StringRef getRepInFormat(StringRef Name, bool UseMD5,
  98. std::string &GUIDBuf) {
  99. if (Name.empty() || !UseMD5)
  100. return Name;
  101. GUIDBuf = std::to_string(Function::getGUID(Name));
  102. return GUIDBuf;
  103. }
  104. static inline uint64_t SPVersion() { return 103; }
  105. // Section Type used by SampleProfileExtBinaryBaseReader and
  106. // SampleProfileExtBinaryBaseWriter. Never change the existing
  107. // value of enum. Only append new ones.
  108. enum SecType {
  109. SecInValid = 0,
  110. SecProfSummary = 1,
  111. SecNameTable = 2,
  112. SecProfileSymbolList = 3,
  113. SecFuncOffsetTable = 4,
  114. SecFuncMetadata = 5,
  115. SecCSNameTable = 6,
  116. // marker for the first type of profile.
  117. SecFuncProfileFirst = 32,
  118. SecLBRProfile = SecFuncProfileFirst
  119. };
  120. static inline std::string getSecName(SecType Type) {
  121. switch ((int)Type) { // Avoid -Wcovered-switch-default
  122. case SecInValid:
  123. return "InvalidSection";
  124. case SecProfSummary:
  125. return "ProfileSummarySection";
  126. case SecNameTable:
  127. return "NameTableSection";
  128. case SecProfileSymbolList:
  129. return "ProfileSymbolListSection";
  130. case SecFuncOffsetTable:
  131. return "FuncOffsetTableSection";
  132. case SecFuncMetadata:
  133. return "FunctionMetadata";
  134. case SecCSNameTable:
  135. return "CSNameTableSection";
  136. case SecLBRProfile:
  137. return "LBRProfileSection";
  138. default:
  139. return "UnknownSection";
  140. }
  141. }
  142. // Entry type of section header table used by SampleProfileExtBinaryBaseReader
  143. // and SampleProfileExtBinaryBaseWriter.
  144. struct SecHdrTableEntry {
  145. SecType Type;
  146. uint64_t Flags;
  147. uint64_t Offset;
  148. uint64_t Size;
  149. // The index indicating the location of the current entry in
  150. // SectionHdrLayout table.
  151. uint32_t LayoutIndex;
  152. };
  153. // Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
  154. // common flags will be saved in the lower 32bits and section specific flags
  155. // will be saved in the higher 32 bits.
  156. enum class SecCommonFlags : uint32_t {
  157. SecFlagInValid = 0,
  158. SecFlagCompress = (1 << 0),
  159. // Indicate the section contains only profile without context.
  160. SecFlagFlat = (1 << 1)
  161. };
  162. // Section specific flags are defined here.
  163. // !!!Note: Everytime a new enum class is created here, please add
  164. // a new check in verifySecFlag.
  165. enum class SecNameTableFlags : uint32_t {
  166. SecFlagInValid = 0,
  167. SecFlagMD5Name = (1 << 0),
  168. // Store MD5 in fixed length instead of ULEB128 so NameTable can be
  169. // accessed like an array.
  170. SecFlagFixedLengthMD5 = (1 << 1),
  171. // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
  172. // the suffix when doing profile matching when seeing the flag.
  173. SecFlagUniqSuffix = (1 << 2)
  174. };
  175. enum class SecProfSummaryFlags : uint32_t {
  176. SecFlagInValid = 0,
  177. /// SecFlagPartial means the profile is for common/shared code.
  178. /// The common profile is usually merged from profiles collected
  179. /// from running other targets.
  180. SecFlagPartial = (1 << 0),
  181. /// SecFlagContext means this is context-sensitive flat profile for
  182. /// CSSPGO
  183. SecFlagFullContext = (1 << 1),
  184. /// SecFlagFSDiscriminator means this profile uses flow-sensitive
  185. /// discriminators.
  186. SecFlagFSDiscriminator = (1 << 2),
  187. /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
  188. /// contexts thus this is CS preinliner computed.
  189. SecFlagIsPreInlined = (1 << 4),
  190. };
  191. enum class SecFuncMetadataFlags : uint32_t {
  192. SecFlagInvalid = 0,
  193. SecFlagIsProbeBased = (1 << 0),
  194. SecFlagHasAttribute = (1 << 1),
  195. };
  196. enum class SecFuncOffsetFlags : uint32_t {
  197. SecFlagInvalid = 0,
  198. // Store function offsets in an order of contexts. The order ensures that
  199. // callee contexts of a given context laid out next to it.
  200. SecFlagOrdered = (1 << 0),
  201. };
  202. // Verify section specific flag is used for the correct section.
  203. template <class SecFlagType>
  204. static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
  205. // No verification is needed for common flags.
  206. if (std::is_same<SecCommonFlags, SecFlagType>())
  207. return;
  208. // Verification starts here for section specific flag.
  209. bool IsFlagLegal = false;
  210. switch (Type) {
  211. case SecNameTable:
  212. IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
  213. break;
  214. case SecProfSummary:
  215. IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
  216. break;
  217. case SecFuncMetadata:
  218. IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
  219. break;
  220. default:
  221. case SecFuncOffsetTable:
  222. IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
  223. break;
  224. }
  225. if (!IsFlagLegal)
  226. llvm_unreachable("Misuse of a flag in an incompatible section");
  227. }
  228. template <class SecFlagType>
  229. static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
  230. verifySecFlag(Entry.Type, Flag);
  231. auto FVal = static_cast<uint64_t>(Flag);
  232. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  233. Entry.Flags |= IsCommon ? FVal : (FVal << 32);
  234. }
  235. template <class SecFlagType>
  236. static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
  237. verifySecFlag(Entry.Type, Flag);
  238. auto FVal = static_cast<uint64_t>(Flag);
  239. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  240. Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
  241. }
  242. template <class SecFlagType>
  243. static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
  244. verifySecFlag(Entry.Type, Flag);
  245. auto FVal = static_cast<uint64_t>(Flag);
  246. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  247. return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
  248. }
  249. /// Represents the relative location of an instruction.
  250. ///
  251. /// Instruction locations are specified by the line offset from the
  252. /// beginning of the function (marked by the line where the function
  253. /// header is) and the discriminator value within that line.
  254. ///
  255. /// The discriminator value is useful to distinguish instructions
  256. /// that are on the same line but belong to different basic blocks
  257. /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
  258. struct LineLocation {
  259. LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
  260. void print(raw_ostream &OS) const;
  261. void dump() const;
  262. bool operator<(const LineLocation &O) const {
  263. return LineOffset < O.LineOffset ||
  264. (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
  265. }
  266. bool operator==(const LineLocation &O) const {
  267. return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
  268. }
  269. bool operator!=(const LineLocation &O) const {
  270. return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
  271. }
  272. uint32_t LineOffset;
  273. uint32_t Discriminator;
  274. };
  275. struct LineLocationHash {
  276. uint64_t operator()(const LineLocation &Loc) const {
  277. return std::hash<std::uint64_t>{}((((uint64_t)Loc.LineOffset) << 32) |
  278. Loc.Discriminator);
  279. }
  280. };
  281. raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc);
  282. /// Representation of a single sample record.
  283. ///
  284. /// A sample record is represented by a positive integer value, which
  285. /// indicates how frequently was the associated line location executed.
  286. ///
  287. /// Additionally, if the associated location contains a function call,
  288. /// the record will hold a list of all the possible called targets. For
  289. /// direct calls, this will be the exact function being invoked. For
  290. /// indirect calls (function pointers, virtual table dispatch), this
  291. /// will be a list of one or more functions.
  292. class SampleRecord {
  293. public:
  294. using CallTarget = std::pair<StringRef, uint64_t>;
  295. struct CallTargetComparator {
  296. bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
  297. if (LHS.second != RHS.second)
  298. return LHS.second > RHS.second;
  299. return LHS.first < RHS.first;
  300. }
  301. };
  302. using SortedCallTargetSet = std::set<CallTarget, CallTargetComparator>;
  303. using CallTargetMap = StringMap<uint64_t>;
  304. SampleRecord() = default;
  305. /// Increment the number of samples for this record by \p S.
  306. /// Optionally scale sample count \p S by \p Weight.
  307. ///
  308. /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
  309. /// around unsigned integers.
  310. sampleprof_error addSamples(uint64_t S, uint64_t Weight = 1) {
  311. bool Overflowed;
  312. NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
  313. return Overflowed ? sampleprof_error::counter_overflow
  314. : sampleprof_error::success;
  315. }
  316. /// Decrease the number of samples for this record by \p S. Return the amout
  317. /// of samples actually decreased.
  318. uint64_t removeSamples(uint64_t S) {
  319. if (S > NumSamples)
  320. S = NumSamples;
  321. NumSamples -= S;
  322. return S;
  323. }
  324. /// Add called function \p F with samples \p S.
  325. /// Optionally scale sample count \p S by \p Weight.
  326. ///
  327. /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
  328. /// around unsigned integers.
  329. sampleprof_error addCalledTarget(StringRef F, uint64_t S,
  330. uint64_t Weight = 1) {
  331. uint64_t &TargetSamples = CallTargets[F];
  332. bool Overflowed;
  333. TargetSamples =
  334. SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
  335. return Overflowed ? sampleprof_error::counter_overflow
  336. : sampleprof_error::success;
  337. }
  338. /// Remove called function from the call target map. Return the target sample
  339. /// count of the called function.
  340. uint64_t removeCalledTarget(StringRef F) {
  341. uint64_t Count = 0;
  342. auto I = CallTargets.find(F);
  343. if (I != CallTargets.end()) {
  344. Count = I->second;
  345. CallTargets.erase(I);
  346. }
  347. return Count;
  348. }
  349. /// Return true if this sample record contains function calls.
  350. bool hasCalls() const { return !CallTargets.empty(); }
  351. uint64_t getSamples() const { return NumSamples; }
  352. const CallTargetMap &getCallTargets() const { return CallTargets; }
  353. const SortedCallTargetSet getSortedCallTargets() const {
  354. return SortCallTargets(CallTargets);
  355. }
  356. uint64_t getCallTargetSum() const {
  357. uint64_t Sum = 0;
  358. for (const auto &I : CallTargets)
  359. Sum += I.second;
  360. return Sum;
  361. }
  362. /// Sort call targets in descending order of call frequency.
  363. static const SortedCallTargetSet SortCallTargets(const CallTargetMap &Targets) {
  364. SortedCallTargetSet SortedTargets;
  365. for (const auto &[Target, Frequency] : Targets) {
  366. SortedTargets.emplace(Target, Frequency);
  367. }
  368. return SortedTargets;
  369. }
  370. /// Prorate call targets by a distribution factor.
  371. static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets,
  372. float DistributionFactor) {
  373. CallTargetMap AdjustedTargets;
  374. for (const auto &[Target, Frequency] : Targets) {
  375. AdjustedTargets[Target] = Frequency * DistributionFactor;
  376. }
  377. return AdjustedTargets;
  378. }
  379. /// Merge the samples in \p Other into this record.
  380. /// Optionally scale sample counts by \p Weight.
  381. sampleprof_error merge(const SampleRecord &Other, uint64_t Weight = 1);
  382. void print(raw_ostream &OS, unsigned Indent) const;
  383. void dump() const;
  384. private:
  385. uint64_t NumSamples = 0;
  386. CallTargetMap CallTargets;
  387. };
  388. raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample);
  389. // State of context associated with FunctionSamples
  390. enum ContextStateMask {
  391. UnknownContext = 0x0, // Profile without context
  392. RawContext = 0x1, // Full context profile from input profile
  393. SyntheticContext = 0x2, // Synthetic context created for context promotion
  394. InlinedContext = 0x4, // Profile for context that is inlined into caller
  395. MergedContext = 0x8 // Profile for context merged into base profile
  396. };
  397. // Attribute of context associated with FunctionSamples
  398. enum ContextAttributeMask {
  399. ContextNone = 0x0,
  400. ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
  401. ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
  402. ContextDuplicatedIntoBase =
  403. 0x4, // Leaf of context is duplicated into the base profile
  404. };
  405. // Represents a context frame with function name and line location
  406. struct SampleContextFrame {
  407. StringRef FuncName;
  408. LineLocation Location;
  409. SampleContextFrame() : Location(0, 0) {}
  410. SampleContextFrame(StringRef FuncName, LineLocation Location)
  411. : FuncName(FuncName), Location(Location) {}
  412. bool operator==(const SampleContextFrame &That) const {
  413. return Location == That.Location && FuncName == That.FuncName;
  414. }
  415. bool operator!=(const SampleContextFrame &That) const {
  416. return !(*this == That);
  417. }
  418. std::string toString(bool OutputLineLocation) const {
  419. std::ostringstream OContextStr;
  420. OContextStr << FuncName.str();
  421. if (OutputLineLocation) {
  422. OContextStr << ":" << Location.LineOffset;
  423. if (Location.Discriminator)
  424. OContextStr << "." << Location.Discriminator;
  425. }
  426. return OContextStr.str();
  427. }
  428. };
  429. static inline hash_code hash_value(const SampleContextFrame &arg) {
  430. return hash_combine(arg.FuncName, arg.Location.LineOffset,
  431. arg.Location.Discriminator);
  432. }
  433. using SampleContextFrameVector = SmallVector<SampleContextFrame, 1>;
  434. using SampleContextFrames = ArrayRef<SampleContextFrame>;
  435. struct SampleContextFrameHash {
  436. uint64_t operator()(const SampleContextFrameVector &S) const {
  437. return hash_combine_range(S.begin(), S.end());
  438. }
  439. };
  440. // Sample context for FunctionSamples. It consists of the calling context,
  441. // the function name and context state. Internally sample context is represented
  442. // using ArrayRef, which is also the input for constructing a `SampleContext`.
  443. // It can accept and represent both full context string as well as context-less
  444. // function name.
  445. // For a CS profile, a full context vector can look like:
  446. // `main:3 _Z5funcAi:1 _Z8funcLeafi`
  447. // For a base CS profile without calling context, the context vector should only
  448. // contain the leaf frame name.
  449. // For a non-CS profile, the context vector should be empty.
  450. class SampleContext {
  451. public:
  452. SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
  453. SampleContext(StringRef Name)
  454. : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
  455. SampleContext(SampleContextFrames Context,
  456. ContextStateMask CState = RawContext)
  457. : Attributes(ContextNone) {
  458. assert(!Context.empty() && "Context is empty");
  459. setContext(Context, CState);
  460. }
  461. // Give a context string, decode and populate internal states like
  462. // Function name, Calling context and context state. Example of input
  463. // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
  464. SampleContext(StringRef ContextStr,
  465. std::list<SampleContextFrameVector> &CSNameTable,
  466. ContextStateMask CState = RawContext)
  467. : Attributes(ContextNone) {
  468. assert(!ContextStr.empty());
  469. // Note that `[]` wrapped input indicates a full context string, otherwise
  470. // it's treated as context-less function name only.
  471. bool HasContext = ContextStr.startswith("[");
  472. if (!HasContext) {
  473. State = UnknownContext;
  474. Name = ContextStr;
  475. } else {
  476. CSNameTable.emplace_back();
  477. SampleContextFrameVector &Context = CSNameTable.back();
  478. createCtxVectorFromStr(ContextStr, Context);
  479. setContext(Context, CState);
  480. }
  481. }
  482. /// Create a context vector from a given context string and save it in
  483. /// `Context`.
  484. static void createCtxVectorFromStr(StringRef ContextStr,
  485. SampleContextFrameVector &Context) {
  486. // Remove encapsulating '[' and ']' if any
  487. ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
  488. StringRef ContextRemain = ContextStr;
  489. StringRef ChildContext;
  490. StringRef CalleeName;
  491. while (!ContextRemain.empty()) {
  492. auto ContextSplit = ContextRemain.split(" @ ");
  493. ChildContext = ContextSplit.first;
  494. ContextRemain = ContextSplit.second;
  495. LineLocation CallSiteLoc(0, 0);
  496. decodeContextString(ChildContext, CalleeName, CallSiteLoc);
  497. Context.emplace_back(CalleeName, CallSiteLoc);
  498. }
  499. }
  500. // Decode context string for a frame to get function name and location.
  501. // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
  502. static void decodeContextString(StringRef ContextStr, StringRef &FName,
  503. LineLocation &LineLoc) {
  504. // Get function name
  505. auto EntrySplit = ContextStr.split(':');
  506. FName = EntrySplit.first;
  507. LineLoc = {0, 0};
  508. if (!EntrySplit.second.empty()) {
  509. // Get line offset, use signed int for getAsInteger so string will
  510. // be parsed as signed.
  511. int LineOffset = 0;
  512. auto LocSplit = EntrySplit.second.split('.');
  513. LocSplit.first.getAsInteger(10, LineOffset);
  514. LineLoc.LineOffset = LineOffset;
  515. // Get discriminator
  516. if (!LocSplit.second.empty())
  517. LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
  518. }
  519. }
  520. operator SampleContextFrames() const { return FullContext; }
  521. bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
  522. void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
  523. uint32_t getAllAttributes() { return Attributes; }
  524. void setAllAttributes(uint32_t A) { Attributes = A; }
  525. bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
  526. void setState(ContextStateMask S) { State |= (uint32_t)S; }
  527. void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
  528. bool hasContext() const { return State != UnknownContext; }
  529. bool isBaseContext() const { return FullContext.size() == 1; }
  530. StringRef getName() const { return Name; }
  531. SampleContextFrames getContextFrames() const { return FullContext; }
  532. static std::string getContextString(SampleContextFrames Context,
  533. bool IncludeLeafLineLocation = false) {
  534. std::ostringstream OContextStr;
  535. for (uint32_t I = 0; I < Context.size(); I++) {
  536. if (OContextStr.str().size()) {
  537. OContextStr << " @ ";
  538. }
  539. OContextStr << Context[I].toString(I != Context.size() - 1 ||
  540. IncludeLeafLineLocation);
  541. }
  542. return OContextStr.str();
  543. }
  544. std::string toString() const {
  545. if (!hasContext())
  546. return Name.str();
  547. return getContextString(FullContext, false);
  548. }
  549. uint64_t getHashCode() const {
  550. return hasContext() ? hash_value(getContextFrames())
  551. : hash_value(getName());
  552. }
  553. /// Set the name of the function and clear the current context.
  554. void setName(StringRef FunctionName) {
  555. Name = FunctionName;
  556. FullContext = SampleContextFrames();
  557. State = UnknownContext;
  558. }
  559. void setContext(SampleContextFrames Context,
  560. ContextStateMask CState = RawContext) {
  561. assert(CState != UnknownContext);
  562. FullContext = Context;
  563. Name = Context.back().FuncName;
  564. State = CState;
  565. }
  566. bool operator==(const SampleContext &That) const {
  567. return State == That.State && Name == That.Name &&
  568. FullContext == That.FullContext;
  569. }
  570. bool operator!=(const SampleContext &That) const { return !(*this == That); }
  571. bool operator<(const SampleContext &That) const {
  572. if (State != That.State)
  573. return State < That.State;
  574. if (!hasContext()) {
  575. return Name < That.Name;
  576. }
  577. uint64_t I = 0;
  578. while (I < std::min(FullContext.size(), That.FullContext.size())) {
  579. auto &Context1 = FullContext[I];
  580. auto &Context2 = That.FullContext[I];
  581. auto V = Context1.FuncName.compare(Context2.FuncName);
  582. if (V)
  583. return V < 0;
  584. if (Context1.Location != Context2.Location)
  585. return Context1.Location < Context2.Location;
  586. I++;
  587. }
  588. return FullContext.size() < That.FullContext.size();
  589. }
  590. struct Hash {
  591. uint64_t operator()(const SampleContext &Context) const {
  592. return Context.getHashCode();
  593. }
  594. };
  595. bool IsPrefixOf(const SampleContext &That) const {
  596. auto ThisContext = FullContext;
  597. auto ThatContext = That.FullContext;
  598. if (ThatContext.size() < ThisContext.size())
  599. return false;
  600. ThatContext = ThatContext.take_front(ThisContext.size());
  601. // Compare Leaf frame first
  602. if (ThisContext.back().FuncName != ThatContext.back().FuncName)
  603. return false;
  604. // Compare leading context
  605. return ThisContext.drop_back() == ThatContext.drop_back();
  606. }
  607. private:
  608. /// Mangled name of the function.
  609. StringRef Name;
  610. // Full context including calling context and leaf function name
  611. SampleContextFrames FullContext;
  612. // State of the associated sample profile
  613. uint32_t State;
  614. // Attribute of the associated sample profile
  615. uint32_t Attributes;
  616. };
  617. static inline hash_code hash_value(const SampleContext &arg) {
  618. return arg.hasContext() ? hash_value(arg.getContextFrames())
  619. : hash_value(arg.getName());
  620. }
  621. class FunctionSamples;
  622. class SampleProfileReaderItaniumRemapper;
  623. using BodySampleMap = std::map<LineLocation, SampleRecord>;
  624. // NOTE: Using a StringMap here makes parsed profiles consume around 17% more
  625. // memory, which is *very* significant for large profiles.
  626. using FunctionSamplesMap = std::map<std::string, FunctionSamples, std::less<>>;
  627. using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
  628. /// Representation of the samples collected for a function.
  629. ///
  630. /// This data structure contains all the collected samples for the body
  631. /// of a function. Each sample corresponds to a LineLocation instance
  632. /// within the body of the function.
  633. class FunctionSamples {
  634. public:
  635. FunctionSamples() = default;
  636. void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
  637. void dump() const;
  638. sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight = 1) {
  639. bool Overflowed;
  640. TotalSamples =
  641. SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
  642. return Overflowed ? sampleprof_error::counter_overflow
  643. : sampleprof_error::success;
  644. }
  645. void removeTotalSamples(uint64_t Num) {
  646. if (TotalSamples < Num)
  647. TotalSamples = 0;
  648. else
  649. TotalSamples -= Num;
  650. }
  651. void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
  652. sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight = 1) {
  653. bool Overflowed;
  654. TotalHeadSamples =
  655. SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
  656. return Overflowed ? sampleprof_error::counter_overflow
  657. : sampleprof_error::success;
  658. }
  659. sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
  660. uint64_t Num, uint64_t Weight = 1) {
  661. return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
  662. Num, Weight);
  663. }
  664. sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
  665. uint32_t Discriminator,
  666. StringRef FName, uint64_t Num,
  667. uint64_t Weight = 1) {
  668. return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
  669. FName, Num, Weight);
  670. }
  671. // Remove a call target and decrease the body sample correspondingly. Return
  672. // the number of body samples actually decreased.
  673. uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset,
  674. uint32_t Discriminator,
  675. StringRef FName) {
  676. uint64_t Count = 0;
  677. auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
  678. if (I != BodySamples.end()) {
  679. Count = I->second.removeCalledTarget(FName);
  680. Count = I->second.removeSamples(Count);
  681. if (!I->second.getSamples())
  682. BodySamples.erase(I);
  683. }
  684. return Count;
  685. }
  686. sampleprof_error addBodySamplesForProbe(uint32_t Index, uint64_t Num,
  687. uint64_t Weight = 1) {
  688. SampleRecord S;
  689. S.addSamples(Num, Weight);
  690. return BodySamples[LineLocation(Index, 0)].merge(S, Weight);
  691. }
  692. // Accumulate all call target samples to update the body samples.
  693. void updateCallsiteSamples() {
  694. for (auto &I : BodySamples) {
  695. uint64_t TargetSamples = I.second.getCallTargetSum();
  696. // It's possible that the body sample count can be greater than the call
  697. // target sum. E.g, if some call targets are external targets, they won't
  698. // be considered valid call targets, but the body sample count which is
  699. // from lbr ranges can actually include them.
  700. if (TargetSamples > I.second.getSamples())
  701. I.second.addSamples(TargetSamples - I.second.getSamples());
  702. }
  703. }
  704. // Accumulate all body samples to set total samples.
  705. void updateTotalSamples() {
  706. setTotalSamples(0);
  707. for (const auto &I : BodySamples)
  708. addTotalSamples(I.second.getSamples());
  709. for (auto &I : CallsiteSamples) {
  710. for (auto &CS : I.second) {
  711. CS.second.updateTotalSamples();
  712. addTotalSamples(CS.second.getTotalSamples());
  713. }
  714. }
  715. }
  716. // Set current context and all callee contexts to be synthetic.
  717. void SetContextSynthetic() {
  718. Context.setState(SyntheticContext);
  719. for (auto &I : CallsiteSamples) {
  720. for (auto &CS : I.second) {
  721. CS.second.SetContextSynthetic();
  722. }
  723. }
  724. }
  725. /// Return the number of samples collected at the given location.
  726. /// Each location is specified by \p LineOffset and \p Discriminator.
  727. /// If the location is not found in profile, return error.
  728. ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
  729. uint32_t Discriminator) const {
  730. const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
  731. if (ret == BodySamples.end())
  732. return std::error_code();
  733. return ret->second.getSamples();
  734. }
  735. /// Returns the call target map collected at a given location.
  736. /// Each location is specified by \p LineOffset and \p Discriminator.
  737. /// If the location is not found in profile, return error.
  738. ErrorOr<SampleRecord::CallTargetMap>
  739. findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
  740. const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
  741. if (ret == BodySamples.end())
  742. return std::error_code();
  743. return ret->second.getCallTargets();
  744. }
  745. /// Returns the call target map collected at a given location specified by \p
  746. /// CallSite. If the location is not found in profile, return error.
  747. ErrorOr<SampleRecord::CallTargetMap>
  748. findCallTargetMapAt(const LineLocation &CallSite) const {
  749. const auto &Ret = BodySamples.find(CallSite);
  750. if (Ret == BodySamples.end())
  751. return std::error_code();
  752. return Ret->second.getCallTargets();
  753. }
  754. /// Return the function samples at the given callsite location.
  755. FunctionSamplesMap &functionSamplesAt(const LineLocation &Loc) {
  756. return CallsiteSamples[Loc];
  757. }
  758. /// Returns the FunctionSamplesMap at the given \p Loc.
  759. const FunctionSamplesMap *
  760. findFunctionSamplesMapAt(const LineLocation &Loc) const {
  761. auto iter = CallsiteSamples.find(Loc);
  762. if (iter == CallsiteSamples.end())
  763. return nullptr;
  764. return &iter->second;
  765. }
  766. /// Returns a pointer to FunctionSamples at the given callsite location
  767. /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
  768. /// the restriction to return the FunctionSamples at callsite location
  769. /// \p Loc with the maximum total sample count. If \p Remapper is not
  770. /// nullptr, use \p Remapper to find FunctionSamples with equivalent name
  771. /// as \p CalleeName.
  772. const FunctionSamples *
  773. findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName,
  774. SampleProfileReaderItaniumRemapper *Remapper) const;
  775. bool empty() const { return TotalSamples == 0; }
  776. /// Return the total number of samples collected inside the function.
  777. uint64_t getTotalSamples() const { return TotalSamples; }
  778. /// For top-level functions, return the total number of branch samples that
  779. /// have the function as the branch target (or 0 otherwise). This is the raw
  780. /// data fetched from the profile. This should be equivalent to the sample of
  781. /// the first instruction of the symbol. But as we directly get this info for
  782. /// raw profile without referring to potentially inaccurate debug info, this
  783. /// gives more accurate profile data and is preferred for standalone symbols.
  784. uint64_t getHeadSamples() const { return TotalHeadSamples; }
  785. /// Return an estimate of the sample count of the function entry basic block.
  786. /// The function can be either a standalone symbol or an inlined function.
  787. /// For Context-Sensitive profiles, this will prefer returning the head
  788. /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
  789. /// the function body's samples or callsite samples.
  790. uint64_t getHeadSamplesEstimate() const {
  791. if (FunctionSamples::ProfileIsCS && getHeadSamples()) {
  792. // For CS profile, if we already have more accurate head samples
  793. // counted by branch sample from caller, use them as entry samples.
  794. return getHeadSamples();
  795. }
  796. uint64_t Count = 0;
  797. // Use either BodySamples or CallsiteSamples which ever has the smaller
  798. // lineno.
  799. if (!BodySamples.empty() &&
  800. (CallsiteSamples.empty() ||
  801. BodySamples.begin()->first < CallsiteSamples.begin()->first))
  802. Count = BodySamples.begin()->second.getSamples();
  803. else if (!CallsiteSamples.empty()) {
  804. // An indirect callsite may be promoted to several inlined direct calls.
  805. // We need to get the sum of them.
  806. for (const auto &N_FS : CallsiteSamples.begin()->second)
  807. Count += N_FS.second.getHeadSamplesEstimate();
  808. }
  809. // Return at least 1 if total sample is not 0.
  810. return Count ? Count : TotalSamples > 0;
  811. }
  812. /// Return all the samples collected in the body of the function.
  813. const BodySampleMap &getBodySamples() const { return BodySamples; }
  814. /// Return all the callsite samples collected in the body of the function.
  815. const CallsiteSampleMap &getCallsiteSamples() const {
  816. return CallsiteSamples;
  817. }
  818. /// Return the maximum of sample counts in a function body. When SkipCallSite
  819. /// is false, which is the default, the return count includes samples in the
  820. /// inlined functions. When SkipCallSite is true, the return count only
  821. /// considers the body samples.
  822. uint64_t getMaxCountInside(bool SkipCallSite = false) const {
  823. uint64_t MaxCount = 0;
  824. for (const auto &L : getBodySamples())
  825. MaxCount = std::max(MaxCount, L.second.getSamples());
  826. if (SkipCallSite)
  827. return MaxCount;
  828. for (const auto &C : getCallsiteSamples())
  829. for (const FunctionSamplesMap::value_type &F : C.second)
  830. MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
  831. return MaxCount;
  832. }
  833. /// Merge the samples in \p Other into this one.
  834. /// Optionally scale samples by \p Weight.
  835. sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight = 1) {
  836. sampleprof_error Result = sampleprof_error::success;
  837. if (!GUIDToFuncNameMap)
  838. GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
  839. if (Context.getName().empty())
  840. Context = Other.getContext();
  841. if (FunctionHash == 0) {
  842. // Set the function hash code for the target profile.
  843. FunctionHash = Other.getFunctionHash();
  844. } else if (FunctionHash != Other.getFunctionHash()) {
  845. // The two profiles coming with different valid hash codes indicates
  846. // either:
  847. // 1. They are same-named static functions from different compilation
  848. // units (without using -unique-internal-linkage-names), or
  849. // 2. They are really the same function but from different compilations.
  850. // Let's bail out in either case for now, which means one profile is
  851. // dropped.
  852. return sampleprof_error::hash_mismatch;
  853. }
  854. MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
  855. MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
  856. for (const auto &I : Other.getBodySamples()) {
  857. const LineLocation &Loc = I.first;
  858. const SampleRecord &Rec = I.second;
  859. MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
  860. }
  861. for (const auto &I : Other.getCallsiteSamples()) {
  862. const LineLocation &Loc = I.first;
  863. FunctionSamplesMap &FSMap = functionSamplesAt(Loc);
  864. for (const auto &Rec : I.second)
  865. MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
  866. }
  867. return Result;
  868. }
  869. /// Recursively traverses all children, if the total sample count of the
  870. /// corresponding function is no less than \p Threshold, add its corresponding
  871. /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
  872. /// to \p S.
  873. void findInlinedFunctions(DenseSet<GlobalValue::GUID> &S,
  874. const StringMap<Function *> &SymbolMap,
  875. uint64_t Threshold) const {
  876. if (TotalSamples <= Threshold)
  877. return;
  878. auto isDeclaration = [](const Function *F) {
  879. return !F || F->isDeclaration();
  880. };
  881. if (isDeclaration(SymbolMap.lookup(getFuncName()))) {
  882. // Add to the import list only when it's defined out of module.
  883. S.insert(getGUID(getName()));
  884. }
  885. // Import hot CallTargets, which may not be available in IR because full
  886. // profile annotation cannot be done until backend compilation in ThinLTO.
  887. for (const auto &BS : BodySamples)
  888. for (const auto &TS : BS.second.getCallTargets())
  889. if (TS.getValue() > Threshold) {
  890. const Function *Callee = SymbolMap.lookup(getFuncName(TS.getKey()));
  891. if (isDeclaration(Callee))
  892. S.insert(getGUID(TS.getKey()));
  893. }
  894. for (const auto &CS : CallsiteSamples)
  895. for (const auto &NameFS : CS.second)
  896. NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
  897. }
  898. /// Set the name of the function.
  899. void setName(StringRef FunctionName) { Context.setName(FunctionName); }
  900. /// Return the function name.
  901. StringRef getName() const { return Context.getName(); }
  902. /// Return the original function name.
  903. StringRef getFuncName() const { return getFuncName(getName()); }
  904. void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
  905. uint64_t getFunctionHash() const { return FunctionHash; }
  906. /// Return the canonical name for a function, taking into account
  907. /// suffix elision policy attributes.
  908. static StringRef getCanonicalFnName(const Function &F) {
  909. auto AttrName = "sample-profile-suffix-elision-policy";
  910. auto Attr = F.getFnAttribute(AttrName).getValueAsString();
  911. return getCanonicalFnName(F.getName(), Attr);
  912. }
  913. /// Name suffixes which canonicalization should handle to avoid
  914. /// profile mismatch.
  915. static constexpr const char *LLVMSuffix = ".llvm.";
  916. static constexpr const char *PartSuffix = ".part.";
  917. static constexpr const char *UniqSuffix = ".__uniq.";
  918. static StringRef getCanonicalFnName(StringRef FnName,
  919. StringRef Attr = "selected") {
  920. // Note the sequence of the suffixes in the knownSuffixes array matters.
  921. // If suffix "A" is appended after the suffix "B", "A" should be in front
  922. // of "B" in knownSuffixes.
  923. const char *knownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
  924. if (Attr == "" || Attr == "all") {
  925. return FnName.split('.').first;
  926. } else if (Attr == "selected") {
  927. StringRef Cand(FnName);
  928. for (const auto &Suf : knownSuffixes) {
  929. StringRef Suffix(Suf);
  930. // If the profile contains ".__uniq." suffix, don't strip the
  931. // suffix for names in the IR.
  932. if (Suffix == UniqSuffix && FunctionSamples::HasUniqSuffix)
  933. continue;
  934. auto It = Cand.rfind(Suffix);
  935. if (It == StringRef::npos)
  936. continue;
  937. auto Dit = Cand.rfind('.');
  938. if (Dit == It + Suffix.size() - 1)
  939. Cand = Cand.substr(0, It);
  940. }
  941. return Cand;
  942. } else if (Attr == "none") {
  943. return FnName;
  944. } else {
  945. assert(false && "internal error: unknown suffix elision policy");
  946. }
  947. return FnName;
  948. }
  949. /// Translate \p Name into its original name.
  950. /// When profile doesn't use MD5, \p Name needs no translation.
  951. /// When profile uses MD5, \p Name in current FunctionSamples
  952. /// is actually GUID of the original function name. getFuncName will
  953. /// translate \p Name in current FunctionSamples into its original name
  954. /// by looking up in the function map GUIDToFuncNameMap.
  955. /// If the original name doesn't exist in the map, return empty StringRef.
  956. StringRef getFuncName(StringRef Name) const {
  957. if (!UseMD5)
  958. return Name;
  959. assert(GUIDToFuncNameMap && "GUIDToFuncNameMap needs to be populated first");
  960. return GUIDToFuncNameMap->lookup(std::stoull(Name.data()));
  961. }
  962. /// Returns the line offset to the start line of the subprogram.
  963. /// We assume that a single function will not exceed 65535 LOC.
  964. static unsigned getOffset(const DILocation *DIL);
  965. /// Returns a unique call site identifier for a given debug location of a call
  966. /// instruction. This is wrapper of two scenarios, the probe-based profile and
  967. /// regular profile, to hide implementation details from the sample loader and
  968. /// the context tracker.
  969. static LineLocation getCallSiteIdentifier(const DILocation *DIL,
  970. bool ProfileIsFS = false);
  971. /// Returns a unique hash code for a combination of a callsite location and
  972. /// the callee function name.
  973. static uint64_t getCallSiteHash(StringRef CalleeName,
  974. const LineLocation &Callsite);
  975. /// Get the FunctionSamples of the inline instance where DIL originates
  976. /// from.
  977. ///
  978. /// The FunctionSamples of the instruction (Machine or IR) associated to
  979. /// \p DIL is the inlined instance in which that instruction is coming from.
  980. /// We traverse the inline stack of that instruction, and match it with the
  981. /// tree nodes in the profile.
  982. ///
  983. /// \returns the FunctionSamples pointer to the inlined instance.
  984. /// If \p Remapper is not nullptr, it will be used to find matching
  985. /// FunctionSamples with not exactly the same but equivalent name.
  986. const FunctionSamples *findFunctionSamples(
  987. const DILocation *DIL,
  988. SampleProfileReaderItaniumRemapper *Remapper = nullptr) const;
  989. static bool ProfileIsProbeBased;
  990. static bool ProfileIsCS;
  991. static bool ProfileIsPreInlined;
  992. SampleContext &getContext() const { return Context; }
  993. void setContext(const SampleContext &FContext) { Context = FContext; }
  994. /// Whether the profile uses MD5 to represent string.
  995. static bool UseMD5;
  996. /// Whether the profile contains any ".__uniq." suffix in a name.
  997. static bool HasUniqSuffix;
  998. /// If this profile uses flow sensitive discriminators.
  999. static bool ProfileIsFS;
  1000. /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
  1001. /// all the function symbols defined or declared in current module.
  1002. DenseMap<uint64_t, StringRef> *GUIDToFuncNameMap = nullptr;
  1003. // Assume the input \p Name is a name coming from FunctionSamples itself.
  1004. // If UseMD5 is true, the name is already a GUID and we
  1005. // don't want to return the GUID of GUID.
  1006. static uint64_t getGUID(StringRef Name) {
  1007. return UseMD5 ? std::stoull(Name.data()) : Function::getGUID(Name);
  1008. }
  1009. // Find all the names in the current FunctionSamples including names in
  1010. // all the inline instances and names of call targets.
  1011. void findAllNames(DenseSet<StringRef> &NameSet) const;
  1012. private:
  1013. /// CFG hash value for the function.
  1014. uint64_t FunctionHash = 0;
  1015. /// Calling context for function profile
  1016. mutable SampleContext Context;
  1017. /// Total number of samples collected inside this function.
  1018. ///
  1019. /// Samples are cumulative, they include all the samples collected
  1020. /// inside this function and all its inlined callees.
  1021. uint64_t TotalSamples = 0;
  1022. /// Total number of samples collected at the head of the function.
  1023. /// This is an approximation of the number of calls made to this function
  1024. /// at runtime.
  1025. uint64_t TotalHeadSamples = 0;
  1026. /// Map instruction locations to collected samples.
  1027. ///
  1028. /// Each entry in this map contains the number of samples
  1029. /// collected at the corresponding line offset. All line locations
  1030. /// are an offset from the start of the function.
  1031. BodySampleMap BodySamples;
  1032. /// Map call sites to collected samples for the called function.
  1033. ///
  1034. /// Each entry in this map corresponds to all the samples
  1035. /// collected for the inlined function call at the given
  1036. /// location. For example, given:
  1037. ///
  1038. /// void foo() {
  1039. /// 1 bar();
  1040. /// ...
  1041. /// 8 baz();
  1042. /// }
  1043. ///
  1044. /// If the bar() and baz() calls were inlined inside foo(), this
  1045. /// map will contain two entries. One for all the samples collected
  1046. /// in the call to bar() at line offset 1, the other for all the samples
  1047. /// collected in the call to baz() at line offset 8.
  1048. CallsiteSampleMap CallsiteSamples;
  1049. };
  1050. raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
  1051. using SampleProfileMap =
  1052. std::unordered_map<SampleContext, FunctionSamples, SampleContext::Hash>;
  1053. using NameFunctionSamples = std::pair<SampleContext, const FunctionSamples *>;
  1054. void sortFuncProfiles(const SampleProfileMap &ProfileMap,
  1055. std::vector<NameFunctionSamples> &SortedProfiles);
  1056. /// Sort a LocationT->SampleT map by LocationT.
  1057. ///
  1058. /// It produces a sorted list of <LocationT, SampleT> records by ascending
  1059. /// order of LocationT.
  1060. template <class LocationT, class SampleT> class SampleSorter {
  1061. public:
  1062. using SamplesWithLoc = std::pair<const LocationT, SampleT>;
  1063. using SamplesWithLocList = SmallVector<const SamplesWithLoc *, 20>;
  1064. SampleSorter(const std::map<LocationT, SampleT> &Samples) {
  1065. for (const auto &I : Samples)
  1066. V.push_back(&I);
  1067. llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
  1068. return A->first < B->first;
  1069. });
  1070. }
  1071. const SamplesWithLocList &get() const { return V; }
  1072. private:
  1073. SamplesWithLocList V;
  1074. };
  1075. /// SampleContextTrimmer impelements helper functions to trim, merge cold
  1076. /// context profiles. It also supports context profile canonicalization to make
  1077. /// sure ProfileMap's key is consistent with FunctionSample's name/context.
  1078. class SampleContextTrimmer {
  1079. public:
  1080. SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles){};
  1081. // Trim and merge cold context profile when requested. TrimBaseProfileOnly
  1082. // should only be effective when TrimColdContext is true. On top of
  1083. // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
  1084. // cold profiles or only cold base profiles. Trimming base profiles only is
  1085. // mainly to honor the preinliner decsion. Note that when MergeColdContext is
  1086. // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
  1087. // be ignored.
  1088. void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold,
  1089. bool TrimColdContext,
  1090. bool MergeColdContext,
  1091. uint32_t ColdContextFrameLength,
  1092. bool TrimBaseProfileOnly);
  1093. // Canonicalize context profile name and attributes.
  1094. void canonicalizeContextProfiles();
  1095. private:
  1096. SampleProfileMap &ProfileMap;
  1097. };
  1098. // CSProfileConverter converts a full context-sensitive flat sample profile into
  1099. // a nested context-sensitive sample profile.
  1100. class CSProfileConverter {
  1101. public:
  1102. CSProfileConverter(SampleProfileMap &Profiles);
  1103. void convertProfiles();
  1104. struct FrameNode {
  1105. FrameNode(StringRef FName = StringRef(),
  1106. FunctionSamples *FSamples = nullptr,
  1107. LineLocation CallLoc = {0, 0})
  1108. : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc){};
  1109. // Map line+discriminator location to child frame
  1110. std::map<uint64_t, FrameNode> AllChildFrames;
  1111. // Function name for current frame
  1112. StringRef FuncName;
  1113. // Function Samples for current frame
  1114. FunctionSamples *FuncSamples;
  1115. // Callsite location in parent context
  1116. LineLocation CallSiteLoc;
  1117. FrameNode *getOrCreateChildFrame(const LineLocation &CallSite,
  1118. StringRef CalleeName);
  1119. };
  1120. private:
  1121. // Nest all children profiles into the profile of Node.
  1122. void convertProfiles(FrameNode &Node);
  1123. FrameNode *getOrCreateContextPath(const SampleContext &Context);
  1124. SampleProfileMap &ProfileMap;
  1125. FrameNode RootFrame;
  1126. };
  1127. /// ProfileSymbolList records the list of function symbols shown up
  1128. /// in the binary used to generate the profile. It is useful to
  1129. /// to discriminate a function being so cold as not to shown up
  1130. /// in the profile and a function newly added.
  1131. class ProfileSymbolList {
  1132. public:
  1133. /// copy indicates whether we need to copy the underlying memory
  1134. /// for the input Name.
  1135. void add(StringRef Name, bool copy = false) {
  1136. if (!copy) {
  1137. Syms.insert(Name);
  1138. return;
  1139. }
  1140. Syms.insert(Name.copy(Allocator));
  1141. }
  1142. bool contains(StringRef Name) { return Syms.count(Name); }
  1143. void merge(const ProfileSymbolList &List) {
  1144. for (auto Sym : List.Syms)
  1145. add(Sym, true);
  1146. }
  1147. unsigned size() { return Syms.size(); }
  1148. void setToCompress(bool TC) { ToCompress = TC; }
  1149. bool toCompress() { return ToCompress; }
  1150. std::error_code read(const uint8_t *Data, uint64_t ListSize);
  1151. std::error_code write(raw_ostream &OS);
  1152. void dump(raw_ostream &OS = dbgs()) const;
  1153. private:
  1154. // Determine whether or not to compress the symbol list when
  1155. // writing it into profile. The variable is unused when the symbol
  1156. // list is read from an existing profile.
  1157. bool ToCompress = false;
  1158. DenseSet<StringRef> Syms;
  1159. BumpPtrAllocator Allocator;
  1160. };
  1161. } // end namespace sampleprof
  1162. using namespace sampleprof;
  1163. // Provide DenseMapInfo for SampleContext.
  1164. template <> struct DenseMapInfo<SampleContext> {
  1165. static inline SampleContext getEmptyKey() { return SampleContext(); }
  1166. static inline SampleContext getTombstoneKey() { return SampleContext("@"); }
  1167. static unsigned getHashValue(const SampleContext &Val) {
  1168. return Val.getHashCode();
  1169. }
  1170. static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
  1171. return LHS == RHS;
  1172. }
  1173. };
  1174. // Prepend "__uniq" before the hash for tools like profilers to understand
  1175. // that this symbol is of internal linkage type. The "__uniq" is the
  1176. // pre-determined prefix that is used to tell tools that this symbol was
  1177. // created with -funique-internal-linakge-symbols and the tools can strip or
  1178. // keep the prefix as needed.
  1179. inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
  1180. llvm::MD5 Md5;
  1181. Md5.update(FName);
  1182. llvm::MD5::MD5Result R;
  1183. Md5.final(R);
  1184. SmallString<32> Str;
  1185. llvm::MD5::stringifyResult(R, Str);
  1186. // Convert MD5hash to Decimal. Demangler suffixes can either contain
  1187. // numbers or characters but not both.
  1188. llvm::APInt IntHash(128, Str.str(), 16);
  1189. return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
  1190. .insert(0, FunctionSamples::UniqSuffix);
  1191. }
  1192. } // end namespace llvm
  1193. #endif // LLVM_PROFILEDATA_SAMPLEPROF_H
  1194. #ifdef __GNUC__
  1195. #pragma GCC diagnostic pop
  1196. #endif