InstrProf.h 42 KB

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