InstrProf.h 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- InstrProf.h - Instrumented 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. // Instrumentation-based profiling data is generated by instrumented
  15. // binaries through library functions in compiler-rt, and read by the clang
  16. // frontend to feed PGO.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_PROFILEDATA_INSTRPROF_H
  20. #define LLVM_PROFILEDATA_INSTRPROF_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/BitmaskEnum.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/StringSet.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/IR/GlobalValue.h"
  28. #include "llvm/IR/ProfileSummary.h"
  29. #include "llvm/ProfileData/InstrProfData.inc"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Compiler.h"
  32. #include "llvm/Support/Endian.h"
  33. #include "llvm/Support/Error.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/Host.h"
  36. #include "llvm/Support/MD5.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <cstddef>
  42. #include <cstdint>
  43. #include <cstring>
  44. #include <list>
  45. #include <memory>
  46. #include <string>
  47. #include <system_error>
  48. #include <utility>
  49. #include <vector>
  50. namespace llvm {
  51. class Function;
  52. class GlobalVariable;
  53. struct InstrProfRecord;
  54. class InstrProfSymtab;
  55. class Instruction;
  56. class MDNode;
  57. class Module;
  58. enum InstrProfSectKind {
  59. #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
  60. #include "llvm/ProfileData/InstrProfData.inc"
  61. };
  62. /// Return the max count value. We reserver a few large values for special use.
  63. inline uint64_t getInstrMaxCountValue() {
  64. return std::numeric_limits<uint64_t>::max() - 2;
  65. }
  66. /// Return the name of the profile section corresponding to \p IPSK.
  67. ///
  68. /// The name of the section depends on the object format type \p OF. If
  69. /// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
  70. /// be added to the section name (this is the default).
  71. std::string getInstrProfSectionName(InstrProfSectKind IPSK,
  72. Triple::ObjectFormatType OF,
  73. bool AddSegmentInfo = true);
  74. /// Return the name profile runtime entry point to do value profiling
  75. /// for a given site.
  76. inline StringRef getInstrProfValueProfFuncName() {
  77. return INSTR_PROF_VALUE_PROF_FUNC_STR;
  78. }
  79. /// Return the name profile runtime entry point to do memop size value
  80. /// profiling.
  81. inline StringRef getInstrProfValueProfMemOpFuncName() {
  82. return INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR;
  83. }
  84. /// Return the name prefix of variables containing instrumented function names.
  85. inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
  86. /// Return the name prefix of variables containing per-function control data.
  87. inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
  88. /// Return the name prefix of profile counter variables.
  89. inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
  90. /// Return the name prefix of value profile variables.
  91. inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
  92. /// Return the name of value profile node array variables:
  93. inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
  94. /// Return the name of the variable holding the strings (possibly compressed)
  95. /// of all function's PGO names.
  96. inline StringRef getInstrProfNamesVarName() {
  97. return "__llvm_prf_nm";
  98. }
  99. /// Return the name of a covarage mapping variable (internal linkage)
  100. /// for each instrumented source module. Such variables are allocated
  101. /// in the __llvm_covmap section.
  102. inline StringRef getCoverageMappingVarName() {
  103. return "__llvm_coverage_mapping";
  104. }
  105. /// Return the name of the internal variable recording the array
  106. /// of PGO name vars referenced by the coverage mapping. The owning
  107. /// functions of those names are not emitted by FE (e.g, unused inline
  108. /// functions.)
  109. inline StringRef getCoverageUnusedNamesVarName() {
  110. return "__llvm_coverage_names";
  111. }
  112. /// Return the name of function that registers all the per-function control
  113. /// data at program startup time by calling __llvm_register_function. This
  114. /// function has internal linkage and is called by __llvm_profile_init
  115. /// runtime method. This function is not generated for these platforms:
  116. /// Darwin, Linux, and FreeBSD.
  117. inline StringRef getInstrProfRegFuncsName() {
  118. return "__llvm_profile_register_functions";
  119. }
  120. /// Return the name of the runtime interface that registers per-function control
  121. /// data for one instrumented function.
  122. inline StringRef getInstrProfRegFuncName() {
  123. return "__llvm_profile_register_function";
  124. }
  125. /// Return the name of the runtime interface that registers the PGO name strings.
  126. inline StringRef getInstrProfNamesRegFuncName() {
  127. return "__llvm_profile_register_names_function";
  128. }
  129. /// Return the name of the runtime initialization method that is generated by
  130. /// the compiler. The function calls __llvm_profile_register_functions and
  131. /// __llvm_profile_override_default_filename functions if needed. This function
  132. /// has internal linkage and invoked at startup time via init_array.
  133. inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
  134. /// Return the name of the hook variable defined in profile runtime library.
  135. /// A reference to the variable causes the linker to link in the runtime
  136. /// initialization module (which defines the hook variable).
  137. inline StringRef getInstrProfRuntimeHookVarName() {
  138. return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
  139. }
  140. /// Return the name of the compiler generated function that references the
  141. /// runtime hook variable. The function is a weak global.
  142. inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
  143. return "__llvm_profile_runtime_user";
  144. }
  145. inline StringRef getInstrProfCounterBiasVarName() {
  146. return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR);
  147. }
  148. /// Return the marker used to separate PGO names during serialization.
  149. inline StringRef getInstrProfNameSeparator() { return "\01"; }
  150. /// Return the modified name for function \c F suitable to be
  151. /// used the key for profile lookup. Variable \c InLTO indicates if this
  152. /// is called in LTO optimization passes.
  153. std::string getPGOFuncName(const Function &F, bool InLTO = false,
  154. uint64_t Version = INSTR_PROF_INDEX_VERSION);
  155. /// Return the modified name for a function suitable to be
  156. /// used the key for profile lookup. The function's original
  157. /// name is \c RawFuncName and has linkage of type \c Linkage.
  158. /// The function is defined in module \c FileName.
  159. std::string getPGOFuncName(StringRef RawFuncName,
  160. GlobalValue::LinkageTypes Linkage,
  161. StringRef FileName,
  162. uint64_t Version = INSTR_PROF_INDEX_VERSION);
  163. /// Return the name of the global variable used to store a function
  164. /// name in PGO instrumentation. \c FuncName is the name of the function
  165. /// returned by the \c getPGOFuncName call.
  166. std::string getPGOFuncNameVarName(StringRef FuncName,
  167. GlobalValue::LinkageTypes Linkage);
  168. /// Create and return the global variable for function name used in PGO
  169. /// instrumentation. \c FuncName is the name of the function returned
  170. /// by \c getPGOFuncName call.
  171. GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
  172. /// Create and return the global variable for function name used in PGO
  173. /// instrumentation. /// \c FuncName is the name of the function
  174. /// returned by \c getPGOFuncName call, \c M is the owning module,
  175. /// and \c Linkage is the linkage of the instrumented function.
  176. GlobalVariable *createPGOFuncNameVar(Module &M,
  177. GlobalValue::LinkageTypes Linkage,
  178. StringRef PGOFuncName);
  179. /// Return the initializer in string of the PGO name var \c NameVar.
  180. StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
  181. /// Given a PGO function name, remove the filename prefix and return
  182. /// the original (static) function name.
  183. StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
  184. StringRef FileName = "<unknown>");
  185. /// Given a vector of strings (function PGO names) \c NameStrs, the
  186. /// method generates a combined string \c Result that is ready to be
  187. /// serialized. The \c Result string is comprised of three fields:
  188. /// The first field is the length of the uncompressed strings, and the
  189. /// the second field is the length of the zlib-compressed string.
  190. /// Both fields are encoded in ULEB128. If \c doCompress is false, the
  191. /// third field is the uncompressed strings; otherwise it is the
  192. /// compressed string. When the string compression is off, the
  193. /// second field will have value zero.
  194. Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
  195. bool doCompression, std::string &Result);
  196. /// Produce \c Result string with the same format described above. The input
  197. /// is vector of PGO function name variables that are referenced.
  198. Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
  199. std::string &Result, bool doCompression = true);
  200. /// \c NameStrings is a string composed of one of more sub-strings encoded in
  201. /// the format described above. The substrings are separated by 0 or more zero
  202. /// bytes. This method decodes the string and populates the \c Symtab.
  203. Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab);
  204. /// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
  205. /// set in IR PGO compilation.
  206. bool isIRPGOFlagSet(const Module *M);
  207. /// Check if we can safely rename this Comdat function. Instances of the same
  208. /// comdat function may have different control flows thus can not share the
  209. /// same counter variable.
  210. bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
  211. enum InstrProfValueKind : uint32_t {
  212. #define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
  213. #include "llvm/ProfileData/InstrProfData.inc"
  214. };
  215. /// Get the value profile data for value site \p SiteIdx from \p InstrProfR
  216. /// and annotate the instruction \p Inst with the value profile meta data.
  217. /// Annotate up to \p MaxMDCount (default 3) number of records per value site.
  218. void annotateValueSite(Module &M, Instruction &Inst,
  219. const InstrProfRecord &InstrProfR,
  220. InstrProfValueKind ValueKind, uint32_t SiteIndx,
  221. uint32_t MaxMDCount = 3);
  222. /// Same as the above interface but using an ArrayRef, as well as \p Sum.
  223. void annotateValueSite(Module &M, Instruction &Inst,
  224. ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
  225. InstrProfValueKind ValueKind, uint32_t MaxMDCount);
  226. /// Extract the value profile data from \p Inst which is annotated with
  227. /// value profile meta data. Return false if there is no value data annotated,
  228. /// otherwise return true.
  229. bool getValueProfDataFromInst(const Instruction &Inst,
  230. InstrProfValueKind ValueKind,
  231. uint32_t MaxNumValueData,
  232. InstrProfValueData ValueData[],
  233. uint32_t &ActualNumValueData, uint64_t &TotalC,
  234. bool GetNoICPValue = false);
  235. inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
  236. /// Return the PGOFuncName meta data associated with a function.
  237. MDNode *getPGOFuncNameMetadata(const Function &F);
  238. /// Create the PGOFuncName meta data if PGOFuncName is different from
  239. /// function's raw name. This should only apply to internal linkage functions
  240. /// declared by users only.
  241. void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
  242. /// Check if we can use Comdat for profile variables. This will eliminate
  243. /// the duplicated profile variables for Comdat functions.
  244. bool needsComdatForCounter(const Function &F, const Module &M);
  245. /// An enum describing the attributes of an instrumented profile.
  246. enum class InstrProfKind {
  247. Unknown = 0x0,
  248. // A frontend clang profile, incompatible with other attrs.
  249. FrontendInstrumentation = 0x1,
  250. // An IR-level profile (default when -fprofile-generate is used).
  251. IRInstrumentation = 0x2,
  252. // A profile with entry basic block instrumentation.
  253. FunctionEntryInstrumentation = 0x4,
  254. // A context sensitive IR-level profile.
  255. ContextSensitive = 0x8,
  256. // Use single byte probes for coverage.
  257. SingleByteCoverage = 0x10,
  258. // Only instrument the function entry basic block.
  259. FunctionEntryOnly = 0x20,
  260. // A memory profile collected using -fprofile=memory.
  261. MemProf = 0x40,
  262. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/MemProf)
  263. };
  264. const std::error_category &instrprof_category();
  265. enum class instrprof_error {
  266. success = 0,
  267. eof,
  268. unrecognized_format,
  269. bad_magic,
  270. bad_header,
  271. unsupported_version,
  272. unsupported_hash_type,
  273. too_large,
  274. truncated,
  275. malformed,
  276. missing_debug_info_for_correlation,
  277. unexpected_debug_info_for_correlation,
  278. unable_to_correlate_profile,
  279. unknown_function,
  280. invalid_prof,
  281. hash_mismatch,
  282. count_mismatch,
  283. counter_overflow,
  284. value_site_count_mismatch,
  285. compress_failed,
  286. uncompress_failed,
  287. empty_raw_profile,
  288. zlib_unavailable
  289. };
  290. inline std::error_code make_error_code(instrprof_error E) {
  291. return std::error_code(static_cast<int>(E), instrprof_category());
  292. }
  293. class InstrProfError : public ErrorInfo<InstrProfError> {
  294. public:
  295. InstrProfError(instrprof_error Err, const Twine &ErrStr = Twine())
  296. : Err(Err), Msg(ErrStr.str()) {
  297. assert(Err != instrprof_error::success && "Not an error");
  298. }
  299. std::string message() const override;
  300. void log(raw_ostream &OS) const override { OS << message(); }
  301. std::error_code convertToErrorCode() const override {
  302. return make_error_code(Err);
  303. }
  304. instrprof_error get() const { return Err; }
  305. const std::string &getMessage() const { return Msg; }
  306. /// Consume an Error and return the raw enum value contained within it. The
  307. /// Error must either be a success value, or contain a single InstrProfError.
  308. static instrprof_error take(Error E) {
  309. auto Err = instrprof_error::success;
  310. handleAllErrors(std::move(E), [&Err](const InstrProfError &IPE) {
  311. assert(Err == instrprof_error::success && "Multiple errors encountered");
  312. Err = IPE.get();
  313. });
  314. return Err;
  315. }
  316. static char ID;
  317. private:
  318. instrprof_error Err;
  319. std::string Msg;
  320. };
  321. class SoftInstrProfErrors {
  322. /// Count the number of soft instrprof_errors encountered and keep track of
  323. /// the first such error for reporting purposes.
  324. /// The first soft error encountered.
  325. instrprof_error FirstError = instrprof_error::success;
  326. /// The number of hash mismatches.
  327. unsigned NumHashMismatches = 0;
  328. /// The number of count mismatches.
  329. unsigned NumCountMismatches = 0;
  330. /// The number of counter overflows.
  331. unsigned NumCounterOverflows = 0;
  332. /// The number of value site count mismatches.
  333. unsigned NumValueSiteCountMismatches = 0;
  334. public:
  335. SoftInstrProfErrors() = default;
  336. ~SoftInstrProfErrors() {
  337. assert(FirstError == instrprof_error::success &&
  338. "Unchecked soft error encountered");
  339. }
  340. /// Track a soft error (\p IE) and increment its associated counter.
  341. void addError(instrprof_error IE);
  342. /// Get the number of hash mismatches.
  343. unsigned getNumHashMismatches() const { return NumHashMismatches; }
  344. /// Get the number of count mismatches.
  345. unsigned getNumCountMismatches() const { return NumCountMismatches; }
  346. /// Get the number of counter overflows.
  347. unsigned getNumCounterOverflows() const { return NumCounterOverflows; }
  348. /// Get the number of value site count mismatches.
  349. unsigned getNumValueSiteCountMismatches() const {
  350. return NumValueSiteCountMismatches;
  351. }
  352. /// Return the first encountered error and reset FirstError to a success
  353. /// value.
  354. Error takeError() {
  355. if (FirstError == instrprof_error::success)
  356. return Error::success();
  357. auto E = make_error<InstrProfError>(FirstError);
  358. FirstError = instrprof_error::success;
  359. return E;
  360. }
  361. };
  362. namespace object {
  363. class SectionRef;
  364. } // end namespace object
  365. namespace IndexedInstrProf {
  366. uint64_t ComputeHash(StringRef K);
  367. } // end namespace IndexedInstrProf
  368. /// A symbol table used for function PGO name look-up with keys
  369. /// (such as pointers, md5hash values) to the function. A function's
  370. /// PGO name or name's md5hash are used in retrieving the profile
  371. /// data of the function. See \c getPGOFuncName() method for details
  372. /// on how PGO name is formed.
  373. class InstrProfSymtab {
  374. public:
  375. using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
  376. private:
  377. StringRef Data;
  378. uint64_t Address = 0;
  379. // Unique name strings.
  380. StringSet<> NameTab;
  381. // A map from MD5 keys to function name strings.
  382. std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
  383. // A map from MD5 keys to function define. We only populate this map
  384. // when build the Symtab from a Module.
  385. std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
  386. // A map from function runtime address to function name MD5 hash.
  387. // This map is only populated and used by raw instr profile reader.
  388. AddrHashMap AddrToMD5Map;
  389. bool Sorted = false;
  390. static StringRef getExternalSymbol() {
  391. return "** External Symbol **";
  392. }
  393. // If the symtab is created by a series of calls to \c addFuncName, \c
  394. // finalizeSymtab needs to be called before looking up function names.
  395. // This is required because the underlying map is a vector (for space
  396. // efficiency) which needs to be sorted.
  397. inline void finalizeSymtab();
  398. public:
  399. InstrProfSymtab() = default;
  400. /// Create InstrProfSymtab from an object file section which
  401. /// contains function PGO names. When section may contain raw
  402. /// string data or string data in compressed form. This method
  403. /// only initialize the symtab with reference to the data and
  404. /// the section base address. The decompression will be delayed
  405. /// until before it is used. See also \c create(StringRef) method.
  406. Error create(object::SectionRef &Section);
  407. /// This interface is used by reader of CoverageMapping test
  408. /// format.
  409. inline Error create(StringRef D, uint64_t BaseAddr);
  410. /// \c NameStrings is a string composed of one of more sub-strings
  411. /// encoded in the format described in \c collectPGOFuncNameStrings.
  412. /// This method is a wrapper to \c readPGOFuncNameStrings method.
  413. inline Error create(StringRef NameStrings);
  414. /// A wrapper interface to populate the PGO symtab with functions
  415. /// decls from module \c M. This interface is used by transformation
  416. /// passes such as indirect function call promotion. Variable \c InLTO
  417. /// indicates if this is called from LTO optimization passes.
  418. Error create(Module &M, bool InLTO = false);
  419. /// Create InstrProfSymtab from a set of names iteratable from
  420. /// \p IterRange. This interface is used by IndexedProfReader.
  421. template <typename NameIterRange> Error create(const NameIterRange &IterRange);
  422. /// Update the symtab by adding \p FuncName to the table. This interface
  423. /// is used by the raw and text profile readers.
  424. Error addFuncName(StringRef FuncName) {
  425. if (FuncName.empty())
  426. return make_error<InstrProfError>(instrprof_error::malformed,
  427. "function name is empty");
  428. auto Ins = NameTab.insert(FuncName);
  429. if (Ins.second) {
  430. MD5NameMap.push_back(std::make_pair(
  431. IndexedInstrProf::ComputeHash(FuncName), Ins.first->getKey()));
  432. Sorted = false;
  433. }
  434. return Error::success();
  435. }
  436. /// Map a function address to its name's MD5 hash. This interface
  437. /// is only used by the raw profiler reader.
  438. void mapAddress(uint64_t Addr, uint64_t MD5Val) {
  439. AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
  440. }
  441. /// Return a function's hash, or 0, if the function isn't in this SymTab.
  442. uint64_t getFunctionHashFromAddress(uint64_t Address);
  443. /// Return function's PGO name from the function name's symbol
  444. /// address in the object file. If an error occurs, return
  445. /// an empty string.
  446. StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
  447. /// Return function's PGO name from the name's md5 hash value.
  448. /// If not found, return an empty string.
  449. inline StringRef getFuncName(uint64_t FuncMD5Hash);
  450. /// Just like getFuncName, except that it will return a non-empty StringRef
  451. /// if the function is external to this symbol table. All such cases
  452. /// will be represented using the same StringRef value.
  453. inline StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash);
  454. /// True if Symbol is the value used to represent external symbols.
  455. static bool isExternalSymbol(const StringRef &Symbol) {
  456. return Symbol == InstrProfSymtab::getExternalSymbol();
  457. }
  458. /// Return function from the name's md5 hash. Return nullptr if not found.
  459. inline Function *getFunction(uint64_t FuncMD5Hash);
  460. /// Return the function's original assembly name by stripping off
  461. /// the prefix attached (to symbols with priviate linkage). For
  462. /// global functions, it returns the same string as getFuncName.
  463. inline StringRef getOrigFuncName(uint64_t FuncMD5Hash);
  464. /// Return the name section data.
  465. inline StringRef getNameData() const { return Data; }
  466. /// Dump the symbols in this table.
  467. void dumpNames(raw_ostream &OS) const {
  468. for (StringRef S : NameTab.keys())
  469. OS << S << "\n";
  470. }
  471. };
  472. Error InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
  473. Data = D;
  474. Address = BaseAddr;
  475. return Error::success();
  476. }
  477. Error InstrProfSymtab::create(StringRef NameStrings) {
  478. return readPGOFuncNameStrings(NameStrings, *this);
  479. }
  480. template <typename NameIterRange>
  481. Error InstrProfSymtab::create(const NameIterRange &IterRange) {
  482. for (auto Name : IterRange)
  483. if (Error E = addFuncName(Name))
  484. return E;
  485. finalizeSymtab();
  486. return Error::success();
  487. }
  488. void InstrProfSymtab::finalizeSymtab() {
  489. if (Sorted)
  490. return;
  491. llvm::sort(MD5NameMap, less_first());
  492. llvm::sort(MD5FuncMap, less_first());
  493. llvm::sort(AddrToMD5Map, less_first());
  494. AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
  495. AddrToMD5Map.end());
  496. Sorted = true;
  497. }
  498. StringRef InstrProfSymtab::getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash) {
  499. StringRef ret = getFuncName(FuncMD5Hash);
  500. if (ret.empty())
  501. return InstrProfSymtab::getExternalSymbol();
  502. return ret;
  503. }
  504. StringRef InstrProfSymtab::getFuncName(uint64_t FuncMD5Hash) {
  505. finalizeSymtab();
  506. auto Result = llvm::lower_bound(MD5NameMap, FuncMD5Hash,
  507. [](const std::pair<uint64_t, StringRef> &LHS,
  508. uint64_t RHS) { return LHS.first < RHS; });
  509. if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
  510. return Result->second;
  511. return StringRef();
  512. }
  513. Function* InstrProfSymtab::getFunction(uint64_t FuncMD5Hash) {
  514. finalizeSymtab();
  515. auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
  516. [](const std::pair<uint64_t, Function *> &LHS,
  517. uint64_t RHS) { return LHS.first < RHS; });
  518. if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
  519. return Result->second;
  520. return nullptr;
  521. }
  522. // See also getPGOFuncName implementation. These two need to be
  523. // matched.
  524. StringRef InstrProfSymtab::getOrigFuncName(uint64_t FuncMD5Hash) {
  525. StringRef PGOName = getFuncName(FuncMD5Hash);
  526. size_t S = PGOName.find_first_of(':');
  527. if (S == StringRef::npos)
  528. return PGOName;
  529. return PGOName.drop_front(S + 1);
  530. }
  531. // To store the sums of profile count values, or the percentage of
  532. // the sums of the total count values.
  533. struct CountSumOrPercent {
  534. uint64_t NumEntries;
  535. double CountSum;
  536. double ValueCounts[IPVK_Last - IPVK_First + 1];
  537. CountSumOrPercent() : NumEntries(0), CountSum(0.0f), ValueCounts() {}
  538. void reset() {
  539. NumEntries = 0;
  540. CountSum = 0.0f;
  541. for (double &VC : ValueCounts)
  542. VC = 0.0f;
  543. }
  544. };
  545. // Function level or program level overlap information.
  546. struct OverlapStats {
  547. enum OverlapStatsLevel { ProgramLevel, FunctionLevel };
  548. // Sum of the total count values for the base profile.
  549. CountSumOrPercent Base;
  550. // Sum of the total count values for the test profile.
  551. CountSumOrPercent Test;
  552. // Overlap lap score. Should be in range of [0.0f to 1.0f].
  553. CountSumOrPercent Overlap;
  554. CountSumOrPercent Mismatch;
  555. CountSumOrPercent Unique;
  556. OverlapStatsLevel Level;
  557. const std::string *BaseFilename;
  558. const std::string *TestFilename;
  559. StringRef FuncName;
  560. uint64_t FuncHash;
  561. bool Valid;
  562. OverlapStats(OverlapStatsLevel L = ProgramLevel)
  563. : Level(L), BaseFilename(nullptr), TestFilename(nullptr), FuncHash(0),
  564. Valid(false) {}
  565. void dump(raw_fd_ostream &OS) const;
  566. void setFuncInfo(StringRef Name, uint64_t Hash) {
  567. FuncName = Name;
  568. FuncHash = Hash;
  569. }
  570. Error accumulateCounts(const std::string &BaseFilename,
  571. const std::string &TestFilename, bool IsCS);
  572. void addOneMismatch(const CountSumOrPercent &MismatchFunc);
  573. void addOneUnique(const CountSumOrPercent &UniqueFunc);
  574. static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
  575. double Sum2) {
  576. if (Sum1 < 1.0f || Sum2 < 1.0f)
  577. return 0.0f;
  578. return std::min(Val1 / Sum1, Val2 / Sum2);
  579. }
  580. };
  581. // This is used to filter the functions whose overlap information
  582. // to be output.
  583. struct OverlapFuncFilters {
  584. uint64_t ValueCutoff;
  585. const std::string NameFilter;
  586. };
  587. struct InstrProfValueSiteRecord {
  588. /// Value profiling data pairs at a given value site.
  589. std::list<InstrProfValueData> ValueData;
  590. InstrProfValueSiteRecord() { ValueData.clear(); }
  591. template <class InputIterator>
  592. InstrProfValueSiteRecord(InputIterator F, InputIterator L)
  593. : ValueData(F, L) {}
  594. /// Sort ValueData ascending by Value
  595. void sortByTargetValues() {
  596. ValueData.sort(
  597. [](const InstrProfValueData &left, const InstrProfValueData &right) {
  598. return left.Value < right.Value;
  599. });
  600. }
  601. /// Sort ValueData Descending by Count
  602. inline void sortByCount();
  603. /// Merge data from another InstrProfValueSiteRecord
  604. /// Optionally scale merged counts by \p Weight.
  605. void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
  606. function_ref<void(instrprof_error)> Warn);
  607. /// Scale up value profile data counts by N (Numerator) / D (Denominator).
  608. void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
  609. /// Compute the overlap b/w this record and Input record.
  610. void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind,
  611. OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
  612. };
  613. /// Profiling information for a single function.
  614. struct InstrProfRecord {
  615. std::vector<uint64_t> Counts;
  616. InstrProfRecord() = default;
  617. InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
  618. InstrProfRecord(InstrProfRecord &&) = default;
  619. InstrProfRecord(const InstrProfRecord &RHS)
  620. : Counts(RHS.Counts),
  621. ValueData(RHS.ValueData
  622. ? std::make_unique<ValueProfData>(*RHS.ValueData)
  623. : nullptr) {}
  624. InstrProfRecord &operator=(InstrProfRecord &&) = default;
  625. InstrProfRecord &operator=(const InstrProfRecord &RHS) {
  626. Counts = RHS.Counts;
  627. if (!RHS.ValueData) {
  628. ValueData = nullptr;
  629. return *this;
  630. }
  631. if (!ValueData)
  632. ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
  633. else
  634. *ValueData = *RHS.ValueData;
  635. return *this;
  636. }
  637. /// Return the number of value profile kinds with non-zero number
  638. /// of profile sites.
  639. inline uint32_t getNumValueKinds() const;
  640. /// Return the number of instrumented sites for ValueKind.
  641. inline uint32_t getNumValueSites(uint32_t ValueKind) const;
  642. /// Return the total number of ValueData for ValueKind.
  643. inline uint32_t getNumValueData(uint32_t ValueKind) const;
  644. /// Return the number of value data collected for ValueKind at profiling
  645. /// site: Site.
  646. inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
  647. uint32_t Site) const;
  648. /// Return the array of profiled values at \p Site. If \p TotalC
  649. /// is not null, the total count of all target values at this site
  650. /// will be stored in \c *TotalC.
  651. inline std::unique_ptr<InstrProfValueData[]>
  652. getValueForSite(uint32_t ValueKind, uint32_t Site,
  653. uint64_t *TotalC = nullptr) const;
  654. /// Get the target value/counts of kind \p ValueKind collected at site
  655. /// \p Site and store the result in array \p Dest. Return the total
  656. /// counts of all target values at this site.
  657. inline uint64_t getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
  658. uint32_t Site) const;
  659. /// Reserve space for NumValueSites sites.
  660. inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
  661. /// Add ValueData for ValueKind at value Site.
  662. void addValueData(uint32_t ValueKind, uint32_t Site,
  663. InstrProfValueData *VData, uint32_t N,
  664. InstrProfSymtab *SymTab);
  665. /// Merge the counts in \p Other into this one.
  666. /// Optionally scale merged counts by \p Weight.
  667. void merge(InstrProfRecord &Other, uint64_t Weight,
  668. function_ref<void(instrprof_error)> Warn);
  669. /// Scale up profile counts (including value profile data) by
  670. /// a factor of (N / D).
  671. void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
  672. /// Sort value profile data (per site) by count.
  673. void sortValueData() {
  674. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  675. for (auto &SR : getValueSitesForKind(Kind))
  676. SR.sortByCount();
  677. }
  678. /// Clear value data entries and edge counters.
  679. void Clear() {
  680. Counts.clear();
  681. clearValueData();
  682. }
  683. /// Clear value data entries
  684. void clearValueData() { ValueData = nullptr; }
  685. /// Compute the sums of all counts and store in Sum.
  686. void accumulateCounts(CountSumOrPercent &Sum) const;
  687. /// Compute the overlap b/w this IntrprofRecord and Other.
  688. void overlap(InstrProfRecord &Other, OverlapStats &Overlap,
  689. OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
  690. /// Compute the overlap of value profile counts.
  691. void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
  692. OverlapStats &Overlap,
  693. OverlapStats &FuncLevelOverlap);
  694. enum CountPseudoKind {
  695. NotPseudo = 0,
  696. PseudoHot,
  697. PseudoWarm,
  698. };
  699. enum PseudoCountVal {
  700. HotFunctionVal = -1,
  701. WarmFunctionVal = -2,
  702. };
  703. CountPseudoKind getCountPseudoKind() const {
  704. uint64_t FirstCount = Counts[0];
  705. if (FirstCount == (uint64_t)HotFunctionVal)
  706. return PseudoHot;
  707. if (FirstCount == (uint64_t)WarmFunctionVal)
  708. return PseudoWarm;
  709. return NotPseudo;
  710. }
  711. void setPseudoCount(CountPseudoKind Kind) {
  712. if (Kind == PseudoHot)
  713. Counts[0] = (uint64_t)HotFunctionVal;
  714. else if (Kind == PseudoWarm)
  715. Counts[0] = (uint64_t)WarmFunctionVal;
  716. }
  717. private:
  718. struct ValueProfData {
  719. std::vector<InstrProfValueSiteRecord> IndirectCallSites;
  720. std::vector<InstrProfValueSiteRecord> MemOPSizes;
  721. };
  722. std::unique_ptr<ValueProfData> ValueData;
  723. MutableArrayRef<InstrProfValueSiteRecord>
  724. getValueSitesForKind(uint32_t ValueKind) {
  725. // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
  726. // implemented in LLVM) to call the const overload of this function, then
  727. // cast away the constness from the result.
  728. auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
  729. ValueKind);
  730. return MutableArrayRef(
  731. const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
  732. }
  733. ArrayRef<InstrProfValueSiteRecord>
  734. getValueSitesForKind(uint32_t ValueKind) const {
  735. if (!ValueData)
  736. return std::nullopt;
  737. switch (ValueKind) {
  738. case IPVK_IndirectCallTarget:
  739. return ValueData->IndirectCallSites;
  740. case IPVK_MemOPSize:
  741. return ValueData->MemOPSizes;
  742. default:
  743. llvm_unreachable("Unknown value kind!");
  744. }
  745. }
  746. std::vector<InstrProfValueSiteRecord> &
  747. getOrCreateValueSitesForKind(uint32_t ValueKind) {
  748. if (!ValueData)
  749. ValueData = std::make_unique<ValueProfData>();
  750. switch (ValueKind) {
  751. case IPVK_IndirectCallTarget:
  752. return ValueData->IndirectCallSites;
  753. case IPVK_MemOPSize:
  754. return ValueData->MemOPSizes;
  755. default:
  756. llvm_unreachable("Unknown value kind!");
  757. }
  758. }
  759. // Map indirect call target name hash to name string.
  760. uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
  761. InstrProfSymtab *SymTab);
  762. // Merge Value Profile data from Src record to this record for ValueKind.
  763. // Scale merged value counts by \p Weight.
  764. void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
  765. uint64_t Weight,
  766. function_ref<void(instrprof_error)> Warn);
  767. // Scale up value profile data count by N (Numerator) / D (Denominator).
  768. void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
  769. function_ref<void(instrprof_error)> Warn);
  770. };
  771. struct NamedInstrProfRecord : InstrProfRecord {
  772. StringRef Name;
  773. uint64_t Hash;
  774. // We reserve this bit as the flag for context sensitive profile record.
  775. static const int CS_FLAG_IN_FUNC_HASH = 60;
  776. NamedInstrProfRecord() = default;
  777. NamedInstrProfRecord(StringRef Name, uint64_t Hash,
  778. std::vector<uint64_t> Counts)
  779. : InstrProfRecord(std::move(Counts)), Name(Name), Hash(Hash) {}
  780. static bool hasCSFlagInHash(uint64_t FuncHash) {
  781. return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
  782. }
  783. static void setCSFlagInHash(uint64_t &FuncHash) {
  784. FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
  785. }
  786. };
  787. uint32_t InstrProfRecord::getNumValueKinds() const {
  788. uint32_t NumValueKinds = 0;
  789. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  790. NumValueKinds += !(getValueSitesForKind(Kind).empty());
  791. return NumValueKinds;
  792. }
  793. uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
  794. uint32_t N = 0;
  795. for (const auto &SR : getValueSitesForKind(ValueKind))
  796. N += SR.ValueData.size();
  797. return N;
  798. }
  799. uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
  800. return getValueSitesForKind(ValueKind).size();
  801. }
  802. uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
  803. uint32_t Site) const {
  804. return getValueSitesForKind(ValueKind)[Site].ValueData.size();
  805. }
  806. std::unique_ptr<InstrProfValueData[]>
  807. InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site,
  808. uint64_t *TotalC) const {
  809. uint64_t Dummy = 0;
  810. uint64_t &TotalCount = (TotalC == nullptr ? Dummy : *TotalC);
  811. uint32_t N = getNumValueDataForSite(ValueKind, Site);
  812. if (N == 0) {
  813. TotalCount = 0;
  814. return std::unique_ptr<InstrProfValueData[]>(nullptr);
  815. }
  816. auto VD = std::make_unique<InstrProfValueData[]>(N);
  817. TotalCount = getValueForSite(VD.get(), ValueKind, Site);
  818. return VD;
  819. }
  820. uint64_t InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
  821. uint32_t ValueKind,
  822. uint32_t Site) const {
  823. uint32_t I = 0;
  824. uint64_t TotalCount = 0;
  825. for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
  826. Dest[I].Value = V.Value;
  827. Dest[I].Count = V.Count;
  828. TotalCount = SaturatingAdd(TotalCount, V.Count);
  829. I++;
  830. }
  831. return TotalCount;
  832. }
  833. void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
  834. if (!NumValueSites)
  835. return;
  836. getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
  837. }
  838. inline support::endianness getHostEndianness() {
  839. return sys::IsLittleEndianHost ? support::little : support::big;
  840. }
  841. // Include definitions for value profile data
  842. #define INSTR_PROF_VALUE_PROF_DATA
  843. #include "llvm/ProfileData/InstrProfData.inc"
  844. void InstrProfValueSiteRecord::sortByCount() {
  845. ValueData.sort(
  846. [](const InstrProfValueData &left, const InstrProfValueData &right) {
  847. return left.Count > right.Count;
  848. });
  849. // Now truncate
  850. size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
  851. if (ValueData.size() > max_s)
  852. ValueData.resize(max_s);
  853. }
  854. namespace IndexedInstrProf {
  855. enum class HashT : uint32_t {
  856. MD5,
  857. Last = MD5
  858. };
  859. inline uint64_t ComputeHash(HashT Type, StringRef K) {
  860. switch (Type) {
  861. case HashT::MD5:
  862. return MD5Hash(K);
  863. }
  864. llvm_unreachable("Unhandled hash type");
  865. }
  866. const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
  867. enum ProfVersion {
  868. // Version 1 is the first version. In this version, the value of
  869. // a key/value pair can only include profile data of a single function.
  870. // Due to this restriction, the number of block counters for a given
  871. // function is not recorded but derived from the length of the value.
  872. Version1 = 1,
  873. // The version 2 format supports recording profile data of multiple
  874. // functions which share the same key in one value field. To support this,
  875. // the number block counters is recorded as an uint64_t field right after the
  876. // function structural hash.
  877. Version2 = 2,
  878. // Version 3 supports value profile data. The value profile data is expected
  879. // to follow the block counter profile data.
  880. Version3 = 3,
  881. // In this version, profile summary data \c IndexedInstrProf::Summary is
  882. // stored after the profile header.
  883. Version4 = 4,
  884. // In this version, the frontend PGO stable hash algorithm defaults to V2.
  885. Version5 = 5,
  886. // In this version, the frontend PGO stable hash algorithm got fixed and
  887. // may produce hashes different from Version5.
  888. Version6 = 6,
  889. // An additional counter is added around logical operators.
  890. Version7 = 7,
  891. // An additional (optional) memory profile type is added.
  892. Version8 = 8,
  893. // Binary ids are added.
  894. Version9 = 9,
  895. // The current version is 9.
  896. CurrentVersion = INSTR_PROF_INDEX_VERSION
  897. };
  898. const uint64_t Version = ProfVersion::CurrentVersion;
  899. const HashT HashType = HashT::MD5;
  900. inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
  901. // This structure defines the file header of the LLVM profile
  902. // data file in indexed-format.
  903. struct Header {
  904. uint64_t Magic;
  905. uint64_t Version;
  906. uint64_t Unused; // Becomes unused since version 4
  907. uint64_t HashType;
  908. uint64_t HashOffset;
  909. uint64_t MemProfOffset;
  910. uint64_t BinaryIdOffset;
  911. // New fields should only be added at the end to ensure that the size
  912. // computation is correct. The methods below need to be updated to ensure that
  913. // the new field is read correctly.
  914. // Reads a header struct from the buffer.
  915. static Expected<Header> readFromBuffer(const unsigned char *Buffer);
  916. // Returns the size of the header in bytes for all valid fields based on the
  917. // version. I.e a older version header will return a smaller size.
  918. size_t size() const;
  919. // Returns the format version in little endian. The header retains the version
  920. // in native endian of the compiler runtime.
  921. uint64_t formatVersion() const;
  922. };
  923. // Profile summary data recorded in the profile data file in indexed
  924. // format. It is introduced in version 4. The summary data follows
  925. // right after the profile file header.
  926. struct Summary {
  927. struct Entry {
  928. uint64_t Cutoff; ///< The required percentile of total execution count.
  929. uint64_t
  930. MinBlockCount; ///< The minimum execution count for this percentile.
  931. uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
  932. };
  933. // The field kind enumerator to assigned value mapping should remain
  934. // unchanged when a new kind is added or an old kind gets deleted in
  935. // the future.
  936. enum SummaryFieldKind {
  937. /// The total number of functions instrumented.
  938. TotalNumFunctions = 0,
  939. /// Total number of instrumented blocks/edges.
  940. TotalNumBlocks = 1,
  941. /// The maximal execution count among all functions.
  942. /// This field does not exist for profile data from IR based
  943. /// instrumentation.
  944. MaxFunctionCount = 2,
  945. /// Max block count of the program.
  946. MaxBlockCount = 3,
  947. /// Max internal block count of the program (excluding entry blocks).
  948. MaxInternalBlockCount = 4,
  949. /// The sum of all instrumented block counts.
  950. TotalBlockCount = 5,
  951. NumKinds = TotalBlockCount + 1
  952. };
  953. // The number of summmary fields following the summary header.
  954. uint64_t NumSummaryFields;
  955. // The number of Cutoff Entries (Summary::Entry) following summary fields.
  956. uint64_t NumCutoffEntries;
  957. Summary() = delete;
  958. Summary(uint32_t Size) { memset(this, 0, Size); }
  959. void operator delete(void *ptr) { ::operator delete(ptr); }
  960. static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries) {
  961. return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
  962. NumSumFields * sizeof(uint64_t);
  963. }
  964. const uint64_t *getSummaryDataBase() const {
  965. return reinterpret_cast<const uint64_t *>(this + 1);
  966. }
  967. uint64_t *getSummaryDataBase() {
  968. return reinterpret_cast<uint64_t *>(this + 1);
  969. }
  970. const Entry *getCutoffEntryBase() const {
  971. return reinterpret_cast<const Entry *>(
  972. &getSummaryDataBase()[NumSummaryFields]);
  973. }
  974. Entry *getCutoffEntryBase() {
  975. return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
  976. }
  977. uint64_t get(SummaryFieldKind K) const {
  978. return getSummaryDataBase()[K];
  979. }
  980. void set(SummaryFieldKind K, uint64_t V) {
  981. getSummaryDataBase()[K] = V;
  982. }
  983. const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
  984. void setEntry(uint32_t I, const ProfileSummaryEntry &E) {
  985. Entry &ER = getCutoffEntryBase()[I];
  986. ER.Cutoff = E.Cutoff;
  987. ER.MinBlockCount = E.MinCount;
  988. ER.NumBlocks = E.NumCounts;
  989. }
  990. };
  991. inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
  992. return std::unique_ptr<Summary>(new (::operator new(TotalSize))
  993. Summary(TotalSize));
  994. }
  995. } // end namespace IndexedInstrProf
  996. namespace RawInstrProf {
  997. // Version 1: First version
  998. // Version 2: Added value profile data section. Per-function control data
  999. // struct has more fields to describe value profile information.
  1000. // Version 3: Compressed name section support. Function PGO name reference
  1001. // from control data struct is changed from raw pointer to Name's MD5 value.
  1002. // Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
  1003. // raw header.
  1004. // Version 5: Bit 60 of FuncHash is reserved for the flag for the context
  1005. // sensitive records.
  1006. // Version 6: Added binary id.
  1007. // Version 7: Reorder binary id and include version in signature.
  1008. // Version 8: Use relative counter pointer.
  1009. const uint64_t Version = INSTR_PROF_RAW_VERSION;
  1010. template <class IntPtrT> inline uint64_t getMagic();
  1011. template <> inline uint64_t getMagic<uint64_t>() {
  1012. return INSTR_PROF_RAW_MAGIC_64;
  1013. }
  1014. template <> inline uint64_t getMagic<uint32_t>() {
  1015. return INSTR_PROF_RAW_MAGIC_32;
  1016. }
  1017. // Per-function profile data header/control structure.
  1018. // The definition should match the structure defined in
  1019. // compiler-rt/lib/profile/InstrProfiling.h.
  1020. // It should also match the synthesized type in
  1021. // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
  1022. template <class IntPtrT> struct alignas(8) ProfileData {
  1023. #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
  1024. #include "llvm/ProfileData/InstrProfData.inc"
  1025. };
  1026. // File header structure of the LLVM profile data in raw format.
  1027. // The definition should match the header referenced in
  1028. // compiler-rt/lib/profile/InstrProfilingFile.c and
  1029. // InstrProfilingBuffer.c.
  1030. struct Header {
  1031. #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
  1032. #include "llvm/ProfileData/InstrProfData.inc"
  1033. };
  1034. } // end namespace RawInstrProf
  1035. // Parse MemOP Size range option.
  1036. void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart,
  1037. int64_t &RangeLast);
  1038. // Create the variable for the profile file name.
  1039. void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
  1040. // Whether to compress function names in profile records, and filenames in
  1041. // code coverage mappings. Used by the Instrumentation library and unit tests.
  1042. extern cl::opt<bool> DoInstrProfNameCompression;
  1043. } // end namespace llvm
  1044. #endif // LLVM_PROFILEDATA_INSTRPROF_H
  1045. #ifdef __GNUC__
  1046. #pragma GCC diagnostic pop
  1047. #endif