InstrProf.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. //===- InstrProf.cpp - Instrumented profiling format support --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for clang's instrumentation based PGO and
  10. // coverage.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/InstrProf.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/IR/Constant.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalValue.h"
  24. #include "llvm/IR/GlobalVariable.h"
  25. #include "llvm/IR/Instruction.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/IR/MDBuilder.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/Type.h"
  31. #include "llvm/ProfileData/InstrProfReader.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/Compression.h"
  36. #include "llvm/Support/Endian.h"
  37. #include "llvm/Support/Error.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/LEB128.h"
  40. #include "llvm/Support/ManagedStatic.h"
  41. #include "llvm/Support/MathExtras.h"
  42. #include "llvm/Support/Path.h"
  43. #include "llvm/Support/SwapByteOrder.h"
  44. #include <algorithm>
  45. #include <cassert>
  46. #include <cstddef>
  47. #include <cstdint>
  48. #include <cstring>
  49. #include <memory>
  50. #include <string>
  51. #include <system_error>
  52. #include <utility>
  53. #include <vector>
  54. using namespace llvm;
  55. static cl::opt<bool> StaticFuncFullModulePrefix(
  56. "static-func-full-module-prefix", cl::init(true), cl::Hidden,
  57. cl::desc("Use full module build paths in the profile counter names for "
  58. "static functions."));
  59. // This option is tailored to users that have different top-level directory in
  60. // profile-gen and profile-use compilation. Users need to specific the number
  61. // of levels to strip. A value larger than the number of directories in the
  62. // source file will strip all the directory names and only leave the basename.
  63. //
  64. // Note current ThinLTO module importing for the indirect-calls assumes
  65. // the source directory name not being stripped. A non-zero option value here
  66. // can potentially prevent some inter-module indirect-call-promotions.
  67. static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
  68. "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
  69. cl::desc("Strip specified level of directory name from source path in "
  70. "the profile counter name for static functions."));
  71. static std::string getInstrProfErrString(instrprof_error Err) {
  72. switch (Err) {
  73. case instrprof_error::success:
  74. return "Success";
  75. case instrprof_error::eof:
  76. return "End of File";
  77. case instrprof_error::unrecognized_format:
  78. return "Unrecognized instrumentation profile encoding format";
  79. case instrprof_error::bad_magic:
  80. return "Invalid instrumentation profile data (bad magic)";
  81. case instrprof_error::bad_header:
  82. return "Invalid instrumentation profile data (file header is corrupt)";
  83. case instrprof_error::unsupported_version:
  84. return "Unsupported instrumentation profile format version";
  85. case instrprof_error::unsupported_hash_type:
  86. return "Unsupported instrumentation profile hash type";
  87. case instrprof_error::too_large:
  88. return "Too much profile data";
  89. case instrprof_error::truncated:
  90. return "Truncated profile data";
  91. case instrprof_error::malformed:
  92. return "Malformed instrumentation profile data";
  93. case instrprof_error::unknown_function:
  94. return "No profile data available for function";
  95. case instrprof_error::hash_mismatch:
  96. return "Function control flow change detected (hash mismatch)";
  97. case instrprof_error::count_mismatch:
  98. return "Function basic block count change detected (counter mismatch)";
  99. case instrprof_error::counter_overflow:
  100. return "Counter overflow";
  101. case instrprof_error::value_site_count_mismatch:
  102. return "Function value site count change detected (counter mismatch)";
  103. case instrprof_error::compress_failed:
  104. return "Failed to compress data (zlib)";
  105. case instrprof_error::uncompress_failed:
  106. return "Failed to uncompress data (zlib)";
  107. case instrprof_error::empty_raw_profile:
  108. return "Empty raw profile file";
  109. case instrprof_error::zlib_unavailable:
  110. return "Profile uses zlib compression but the profile reader was built without zlib support";
  111. }
  112. llvm_unreachable("A value of instrprof_error has no message.");
  113. }
  114. namespace {
  115. // FIXME: This class is only here to support the transition to llvm::Error. It
  116. // will be removed once this transition is complete. Clients should prefer to
  117. // deal with the Error value directly, rather than converting to error_code.
  118. class InstrProfErrorCategoryType : public std::error_category {
  119. const char *name() const noexcept override { return "llvm.instrprof"; }
  120. std::string message(int IE) const override {
  121. return getInstrProfErrString(static_cast<instrprof_error>(IE));
  122. }
  123. };
  124. } // end anonymous namespace
  125. static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
  126. const std::error_category &llvm::instrprof_category() {
  127. return *ErrorCategory;
  128. }
  129. namespace {
  130. const char *InstrProfSectNameCommon[] = {
  131. #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
  132. SectNameCommon,
  133. #include "llvm/ProfileData/InstrProfData.inc"
  134. };
  135. const char *InstrProfSectNameCoff[] = {
  136. #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
  137. SectNameCoff,
  138. #include "llvm/ProfileData/InstrProfData.inc"
  139. };
  140. const char *InstrProfSectNamePrefix[] = {
  141. #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
  142. Prefix,
  143. #include "llvm/ProfileData/InstrProfData.inc"
  144. };
  145. } // namespace
  146. namespace llvm {
  147. cl::opt<bool> DoInstrProfNameCompression(
  148. "enable-name-compression",
  149. cl::desc("Enable name/filename string compression"), cl::init(true));
  150. std::string getInstrProfSectionName(InstrProfSectKind IPSK,
  151. Triple::ObjectFormatType OF,
  152. bool AddSegmentInfo) {
  153. std::string SectName;
  154. if (OF == Triple::MachO && AddSegmentInfo)
  155. SectName = InstrProfSectNamePrefix[IPSK];
  156. if (OF == Triple::COFF)
  157. SectName += InstrProfSectNameCoff[IPSK];
  158. else
  159. SectName += InstrProfSectNameCommon[IPSK];
  160. if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
  161. SectName += ",regular,live_support";
  162. return SectName;
  163. }
  164. void SoftInstrProfErrors::addError(instrprof_error IE) {
  165. if (IE == instrprof_error::success)
  166. return;
  167. if (FirstError == instrprof_error::success)
  168. FirstError = IE;
  169. switch (IE) {
  170. case instrprof_error::hash_mismatch:
  171. ++NumHashMismatches;
  172. break;
  173. case instrprof_error::count_mismatch:
  174. ++NumCountMismatches;
  175. break;
  176. case instrprof_error::counter_overflow:
  177. ++NumCounterOverflows;
  178. break;
  179. case instrprof_error::value_site_count_mismatch:
  180. ++NumValueSiteCountMismatches;
  181. break;
  182. default:
  183. llvm_unreachable("Not a soft error");
  184. }
  185. }
  186. std::string InstrProfError::message() const {
  187. return getInstrProfErrString(Err);
  188. }
  189. char InstrProfError::ID = 0;
  190. std::string getPGOFuncName(StringRef RawFuncName,
  191. GlobalValue::LinkageTypes Linkage,
  192. StringRef FileName,
  193. uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
  194. return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
  195. }
  196. // Strip NumPrefix level of directory name from PathNameStr. If the number of
  197. // directory separators is less than NumPrefix, strip all the directories and
  198. // leave base file name only.
  199. static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
  200. uint32_t Count = NumPrefix;
  201. uint32_t Pos = 0, LastPos = 0;
  202. for (auto & CI : PathNameStr) {
  203. ++Pos;
  204. if (llvm::sys::path::is_separator(CI)) {
  205. LastPos = Pos;
  206. --Count;
  207. }
  208. if (Count == 0)
  209. break;
  210. }
  211. return PathNameStr.substr(LastPos);
  212. }
  213. // Return the PGOFuncName. This function has some special handling when called
  214. // in LTO optimization. The following only applies when calling in LTO passes
  215. // (when \c InLTO is true): LTO's internalization privatizes many global linkage
  216. // symbols. This happens after value profile annotation, but those internal
  217. // linkage functions should not have a source prefix.
  218. // Additionally, for ThinLTO mode, exported internal functions are promoted
  219. // and renamed. We need to ensure that the original internal PGO name is
  220. // used when computing the GUID that is compared against the profiled GUIDs.
  221. // To differentiate compiler generated internal symbols from original ones,
  222. // PGOFuncName meta data are created and attached to the original internal
  223. // symbols in the value profile annotation step
  224. // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
  225. // data, its original linkage must be non-internal.
  226. std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
  227. if (!InLTO) {
  228. StringRef FileName(F.getParent()->getSourceFileName());
  229. uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
  230. if (StripLevel < StaticFuncStripDirNamePrefix)
  231. StripLevel = StaticFuncStripDirNamePrefix;
  232. if (StripLevel)
  233. FileName = stripDirPrefix(FileName, StripLevel);
  234. return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
  235. }
  236. // In LTO mode (when InLTO is true), first check if there is a meta data.
  237. if (MDNode *MD = getPGOFuncNameMetadata(F)) {
  238. StringRef S = cast<MDString>(MD->getOperand(0))->getString();
  239. return S.str();
  240. }
  241. // If there is no meta data, the function must be a global before the value
  242. // profile annotation pass. Its current linkage may be internal if it is
  243. // internalized in LTO mode.
  244. return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
  245. }
  246. StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
  247. if (FileName.empty())
  248. return PGOFuncName;
  249. // Drop the file name including ':'. See also getPGOFuncName.
  250. if (PGOFuncName.startswith(FileName))
  251. PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
  252. return PGOFuncName;
  253. }
  254. // \p FuncName is the string used as profile lookup key for the function. A
  255. // symbol is created to hold the name. Return the legalized symbol name.
  256. std::string getPGOFuncNameVarName(StringRef FuncName,
  257. GlobalValue::LinkageTypes Linkage) {
  258. std::string VarName = std::string(getInstrProfNameVarPrefix());
  259. VarName += FuncName;
  260. if (!GlobalValue::isLocalLinkage(Linkage))
  261. return VarName;
  262. // Now fix up illegal chars in local VarName that may upset the assembler.
  263. const char *InvalidChars = "-:<>/\"'";
  264. size_t found = VarName.find_first_of(InvalidChars);
  265. while (found != std::string::npos) {
  266. VarName[found] = '_';
  267. found = VarName.find_first_of(InvalidChars, found + 1);
  268. }
  269. return VarName;
  270. }
  271. GlobalVariable *createPGOFuncNameVar(Module &M,
  272. GlobalValue::LinkageTypes Linkage,
  273. StringRef PGOFuncName) {
  274. // We generally want to match the function's linkage, but available_externally
  275. // and extern_weak both have the wrong semantics, and anything that doesn't
  276. // need to link across compilation units doesn't need to be visible at all.
  277. if (Linkage == GlobalValue::ExternalWeakLinkage)
  278. Linkage = GlobalValue::LinkOnceAnyLinkage;
  279. else if (Linkage == GlobalValue::AvailableExternallyLinkage)
  280. Linkage = GlobalValue::LinkOnceODRLinkage;
  281. else if (Linkage == GlobalValue::InternalLinkage ||
  282. Linkage == GlobalValue::ExternalLinkage)
  283. Linkage = GlobalValue::PrivateLinkage;
  284. auto *Value =
  285. ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
  286. auto FuncNameVar =
  287. new GlobalVariable(M, Value->getType(), true, Linkage, Value,
  288. getPGOFuncNameVarName(PGOFuncName, Linkage));
  289. // Hide the symbol so that we correctly get a copy for each executable.
  290. if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
  291. FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
  292. return FuncNameVar;
  293. }
  294. GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
  295. return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
  296. }
  297. Error InstrProfSymtab::create(Module &M, bool InLTO) {
  298. for (Function &F : M) {
  299. // Function may not have a name: like using asm("") to overwrite the name.
  300. // Ignore in this case.
  301. if (!F.hasName())
  302. continue;
  303. const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
  304. if (Error E = addFuncName(PGOFuncName))
  305. return E;
  306. MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
  307. // In ThinLTO, local function may have been promoted to global and have
  308. // suffix added to the function name. We need to add the stripped function
  309. // name to the symbol table so that we can find a match from profile.
  310. if (InLTO) {
  311. auto pos = PGOFuncName.find('.');
  312. if (pos != std::string::npos) {
  313. const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
  314. if (Error E = addFuncName(OtherFuncName))
  315. return E;
  316. MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
  317. }
  318. }
  319. }
  320. Sorted = false;
  321. finalizeSymtab();
  322. return Error::success();
  323. }
  324. uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
  325. finalizeSymtab();
  326. auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
  327. return A.first < Address;
  328. });
  329. // Raw function pointer collected by value profiler may be from
  330. // external functions that are not instrumented. They won't have
  331. // mapping data to be used by the deserializer. Force the value to
  332. // be 0 in this case.
  333. if (It != AddrToMD5Map.end() && It->first == Address)
  334. return (uint64_t)It->second;
  335. return 0;
  336. }
  337. Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
  338. bool doCompression, std::string &Result) {
  339. assert(!NameStrs.empty() && "No name data to emit");
  340. uint8_t Header[16], *P = Header;
  341. std::string UncompressedNameStrings =
  342. join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
  343. assert(StringRef(UncompressedNameStrings)
  344. .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
  345. "PGO name is invalid (contains separator token)");
  346. unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
  347. P += EncLen;
  348. auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
  349. EncLen = encodeULEB128(CompressedLen, P);
  350. P += EncLen;
  351. char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
  352. unsigned HeaderLen = P - &Header[0];
  353. Result.append(HeaderStr, HeaderLen);
  354. Result += InputStr;
  355. return Error::success();
  356. };
  357. if (!doCompression) {
  358. return WriteStringToResult(0, UncompressedNameStrings);
  359. }
  360. SmallString<128> CompressedNameStrings;
  361. Error E = zlib::compress(StringRef(UncompressedNameStrings),
  362. CompressedNameStrings, zlib::BestSizeCompression);
  363. if (E) {
  364. consumeError(std::move(E));
  365. return make_error<InstrProfError>(instrprof_error::compress_failed);
  366. }
  367. return WriteStringToResult(CompressedNameStrings.size(),
  368. CompressedNameStrings);
  369. }
  370. StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
  371. auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
  372. StringRef NameStr =
  373. Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
  374. return NameStr;
  375. }
  376. Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
  377. std::string &Result, bool doCompression) {
  378. std::vector<std::string> NameStrs;
  379. for (auto *NameVar : NameVars) {
  380. NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
  381. }
  382. return collectPGOFuncNameStrings(
  383. NameStrs, zlib::isAvailable() && doCompression, Result);
  384. }
  385. Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
  386. const uint8_t *P = NameStrings.bytes_begin();
  387. const uint8_t *EndP = NameStrings.bytes_end();
  388. while (P < EndP) {
  389. uint32_t N;
  390. uint64_t UncompressedSize = decodeULEB128(P, &N);
  391. P += N;
  392. uint64_t CompressedSize = decodeULEB128(P, &N);
  393. P += N;
  394. bool isCompressed = (CompressedSize != 0);
  395. SmallString<128> UncompressedNameStrings;
  396. StringRef NameStrings;
  397. if (isCompressed) {
  398. if (!llvm::zlib::isAvailable())
  399. return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
  400. StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
  401. CompressedSize);
  402. if (Error E =
  403. zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
  404. UncompressedSize)) {
  405. consumeError(std::move(E));
  406. return make_error<InstrProfError>(instrprof_error::uncompress_failed);
  407. }
  408. P += CompressedSize;
  409. NameStrings = StringRef(UncompressedNameStrings.data(),
  410. UncompressedNameStrings.size());
  411. } else {
  412. NameStrings =
  413. StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
  414. P += UncompressedSize;
  415. }
  416. // Now parse the name strings.
  417. SmallVector<StringRef, 0> Names;
  418. NameStrings.split(Names, getInstrProfNameSeparator());
  419. for (StringRef &Name : Names)
  420. if (Error E = Symtab.addFuncName(Name))
  421. return E;
  422. while (P < EndP && *P == 0)
  423. P++;
  424. }
  425. return Error::success();
  426. }
  427. void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
  428. uint64_t FuncSum = 0;
  429. Sum.NumEntries += Counts.size();
  430. for (size_t F = 0, E = Counts.size(); F < E; ++F)
  431. FuncSum += Counts[F];
  432. Sum.CountSum += FuncSum;
  433. for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
  434. uint64_t KindSum = 0;
  435. uint32_t NumValueSites = getNumValueSites(VK);
  436. for (size_t I = 0; I < NumValueSites; ++I) {
  437. uint32_t NV = getNumValueDataForSite(VK, I);
  438. std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
  439. for (uint32_t V = 0; V < NV; V++)
  440. KindSum += VD[V].Count;
  441. }
  442. Sum.ValueCounts[VK] += KindSum;
  443. }
  444. }
  445. void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
  446. uint32_t ValueKind,
  447. OverlapStats &Overlap,
  448. OverlapStats &FuncLevelOverlap) {
  449. this->sortByTargetValues();
  450. Input.sortByTargetValues();
  451. double Score = 0.0f, FuncLevelScore = 0.0f;
  452. auto I = ValueData.begin();
  453. auto IE = ValueData.end();
  454. auto J = Input.ValueData.begin();
  455. auto JE = Input.ValueData.end();
  456. while (I != IE && J != JE) {
  457. if (I->Value == J->Value) {
  458. Score += OverlapStats::score(I->Count, J->Count,
  459. Overlap.Base.ValueCounts[ValueKind],
  460. Overlap.Test.ValueCounts[ValueKind]);
  461. FuncLevelScore += OverlapStats::score(
  462. I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
  463. FuncLevelOverlap.Test.ValueCounts[ValueKind]);
  464. ++I;
  465. } else if (I->Value < J->Value) {
  466. ++I;
  467. continue;
  468. }
  469. ++J;
  470. }
  471. Overlap.Overlap.ValueCounts[ValueKind] += Score;
  472. FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
  473. }
  474. // Return false on mismatch.
  475. void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
  476. InstrProfRecord &Other,
  477. OverlapStats &Overlap,
  478. OverlapStats &FuncLevelOverlap) {
  479. uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
  480. assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
  481. if (!ThisNumValueSites)
  482. return;
  483. std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
  484. getOrCreateValueSitesForKind(ValueKind);
  485. MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
  486. Other.getValueSitesForKind(ValueKind);
  487. for (uint32_t I = 0; I < ThisNumValueSites; I++)
  488. ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
  489. FuncLevelOverlap);
  490. }
  491. void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
  492. OverlapStats &FuncLevelOverlap,
  493. uint64_t ValueCutoff) {
  494. // FuncLevel CountSum for other should already computed and nonzero.
  495. assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
  496. accumulateCounts(FuncLevelOverlap.Base);
  497. bool Mismatch = (Counts.size() != Other.Counts.size());
  498. // Check if the value profiles mismatch.
  499. if (!Mismatch) {
  500. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
  501. uint32_t ThisNumValueSites = getNumValueSites(Kind);
  502. uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
  503. if (ThisNumValueSites != OtherNumValueSites) {
  504. Mismatch = true;
  505. break;
  506. }
  507. }
  508. }
  509. if (Mismatch) {
  510. Overlap.addOneMismatch(FuncLevelOverlap.Test);
  511. return;
  512. }
  513. // Compute overlap for value counts.
  514. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  515. overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
  516. double Score = 0.0;
  517. uint64_t MaxCount = 0;
  518. // Compute overlap for edge counts.
  519. for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
  520. Score += OverlapStats::score(Counts[I], Other.Counts[I],
  521. Overlap.Base.CountSum, Overlap.Test.CountSum);
  522. MaxCount = std::max(Other.Counts[I], MaxCount);
  523. }
  524. Overlap.Overlap.CountSum += Score;
  525. Overlap.Overlap.NumEntries += 1;
  526. if (MaxCount >= ValueCutoff) {
  527. double FuncScore = 0.0;
  528. for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
  529. FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
  530. FuncLevelOverlap.Base.CountSum,
  531. FuncLevelOverlap.Test.CountSum);
  532. FuncLevelOverlap.Overlap.CountSum = FuncScore;
  533. FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
  534. FuncLevelOverlap.Valid = true;
  535. }
  536. }
  537. void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
  538. uint64_t Weight,
  539. function_ref<void(instrprof_error)> Warn) {
  540. this->sortByTargetValues();
  541. Input.sortByTargetValues();
  542. auto I = ValueData.begin();
  543. auto IE = ValueData.end();
  544. for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
  545. ++J) {
  546. while (I != IE && I->Value < J->Value)
  547. ++I;
  548. if (I != IE && I->Value == J->Value) {
  549. bool Overflowed;
  550. I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
  551. if (Overflowed)
  552. Warn(instrprof_error::counter_overflow);
  553. ++I;
  554. continue;
  555. }
  556. ValueData.insert(I, *J);
  557. }
  558. }
  559. void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
  560. function_ref<void(instrprof_error)> Warn) {
  561. for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
  562. bool Overflowed;
  563. I->Count = SaturatingMultiply(I->Count, N, &Overflowed) / D;
  564. if (Overflowed)
  565. Warn(instrprof_error::counter_overflow);
  566. }
  567. }
  568. // Merge Value Profile data from Src record to this record for ValueKind.
  569. // Scale merged value counts by \p Weight.
  570. void InstrProfRecord::mergeValueProfData(
  571. uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
  572. function_ref<void(instrprof_error)> Warn) {
  573. uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
  574. uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
  575. if (ThisNumValueSites != OtherNumValueSites) {
  576. Warn(instrprof_error::value_site_count_mismatch);
  577. return;
  578. }
  579. if (!ThisNumValueSites)
  580. return;
  581. std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
  582. getOrCreateValueSitesForKind(ValueKind);
  583. MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
  584. Src.getValueSitesForKind(ValueKind);
  585. for (uint32_t I = 0; I < ThisNumValueSites; I++)
  586. ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
  587. }
  588. void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
  589. function_ref<void(instrprof_error)> Warn) {
  590. // If the number of counters doesn't match we either have bad data
  591. // or a hash collision.
  592. if (Counts.size() != Other.Counts.size()) {
  593. Warn(instrprof_error::count_mismatch);
  594. return;
  595. }
  596. for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
  597. bool Overflowed;
  598. Counts[I] =
  599. SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
  600. if (Overflowed)
  601. Warn(instrprof_error::counter_overflow);
  602. }
  603. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  604. mergeValueProfData(Kind, Other, Weight, Warn);
  605. }
  606. void InstrProfRecord::scaleValueProfData(
  607. uint32_t ValueKind, uint64_t N, uint64_t D,
  608. function_ref<void(instrprof_error)> Warn) {
  609. for (auto &R : getValueSitesForKind(ValueKind))
  610. R.scale(N, D, Warn);
  611. }
  612. void InstrProfRecord::scale(uint64_t N, uint64_t D,
  613. function_ref<void(instrprof_error)> Warn) {
  614. assert(D != 0 && "D cannot be 0");
  615. for (auto &Count : this->Counts) {
  616. bool Overflowed;
  617. Count = SaturatingMultiply(Count, N, &Overflowed) / D;
  618. if (Overflowed)
  619. Warn(instrprof_error::counter_overflow);
  620. }
  621. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  622. scaleValueProfData(Kind, N, D, Warn);
  623. }
  624. // Map indirect call target name hash to name string.
  625. uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
  626. InstrProfSymtab *SymTab) {
  627. if (!SymTab)
  628. return Value;
  629. if (ValueKind == IPVK_IndirectCallTarget)
  630. return SymTab->getFunctionHashFromAddress(Value);
  631. return Value;
  632. }
  633. void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
  634. InstrProfValueData *VData, uint32_t N,
  635. InstrProfSymtab *ValueMap) {
  636. for (uint32_t I = 0; I < N; I++) {
  637. VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
  638. }
  639. std::vector<InstrProfValueSiteRecord> &ValueSites =
  640. getOrCreateValueSitesForKind(ValueKind);
  641. if (N == 0)
  642. ValueSites.emplace_back();
  643. else
  644. ValueSites.emplace_back(VData, VData + N);
  645. }
  646. #define INSTR_PROF_COMMON_API_IMPL
  647. #include "llvm/ProfileData/InstrProfData.inc"
  648. /*!
  649. * ValueProfRecordClosure Interface implementation for InstrProfRecord
  650. * class. These C wrappers are used as adaptors so that C++ code can be
  651. * invoked as callbacks.
  652. */
  653. uint32_t getNumValueKindsInstrProf(const void *Record) {
  654. return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
  655. }
  656. uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
  657. return reinterpret_cast<const InstrProfRecord *>(Record)
  658. ->getNumValueSites(VKind);
  659. }
  660. uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
  661. return reinterpret_cast<const InstrProfRecord *>(Record)
  662. ->getNumValueData(VKind);
  663. }
  664. uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
  665. uint32_t S) {
  666. return reinterpret_cast<const InstrProfRecord *>(R)
  667. ->getNumValueDataForSite(VK, S);
  668. }
  669. void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
  670. uint32_t K, uint32_t S) {
  671. reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
  672. }
  673. ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
  674. ValueProfData *VD =
  675. (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
  676. memset(VD, 0, TotalSizeInBytes);
  677. return VD;
  678. }
  679. static ValueProfRecordClosure InstrProfRecordClosure = {
  680. nullptr,
  681. getNumValueKindsInstrProf,
  682. getNumValueSitesInstrProf,
  683. getNumValueDataInstrProf,
  684. getNumValueDataForSiteInstrProf,
  685. nullptr,
  686. getValueForSiteInstrProf,
  687. allocValueProfDataInstrProf};
  688. // Wrapper implementation using the closure mechanism.
  689. uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
  690. auto Closure = InstrProfRecordClosure;
  691. Closure.Record = &Record;
  692. return getValueProfDataSize(&Closure);
  693. }
  694. // Wrapper implementation using the closure mechanism.
  695. std::unique_ptr<ValueProfData>
  696. ValueProfData::serializeFrom(const InstrProfRecord &Record) {
  697. InstrProfRecordClosure.Record = &Record;
  698. std::unique_ptr<ValueProfData> VPD(
  699. serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
  700. return VPD;
  701. }
  702. void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
  703. InstrProfSymtab *SymTab) {
  704. Record.reserveSites(Kind, NumValueSites);
  705. InstrProfValueData *ValueData = getValueProfRecordValueData(this);
  706. for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
  707. uint8_t ValueDataCount = this->SiteCountArray[VSite];
  708. Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
  709. ValueData += ValueDataCount;
  710. }
  711. }
  712. // For writing/serializing, Old is the host endianness, and New is
  713. // byte order intended on disk. For Reading/deserialization, Old
  714. // is the on-disk source endianness, and New is the host endianness.
  715. void ValueProfRecord::swapBytes(support::endianness Old,
  716. support::endianness New) {
  717. using namespace support;
  718. if (Old == New)
  719. return;
  720. if (getHostEndianness() != Old) {
  721. sys::swapByteOrder<uint32_t>(NumValueSites);
  722. sys::swapByteOrder<uint32_t>(Kind);
  723. }
  724. uint32_t ND = getValueProfRecordNumValueData(this);
  725. InstrProfValueData *VD = getValueProfRecordValueData(this);
  726. // No need to swap byte array: SiteCountArrray.
  727. for (uint32_t I = 0; I < ND; I++) {
  728. sys::swapByteOrder<uint64_t>(VD[I].Value);
  729. sys::swapByteOrder<uint64_t>(VD[I].Count);
  730. }
  731. if (getHostEndianness() == Old) {
  732. sys::swapByteOrder<uint32_t>(NumValueSites);
  733. sys::swapByteOrder<uint32_t>(Kind);
  734. }
  735. }
  736. void ValueProfData::deserializeTo(InstrProfRecord &Record,
  737. InstrProfSymtab *SymTab) {
  738. if (NumValueKinds == 0)
  739. return;
  740. ValueProfRecord *VR = getFirstValueProfRecord(this);
  741. for (uint32_t K = 0; K < NumValueKinds; K++) {
  742. VR->deserializeTo(Record, SymTab);
  743. VR = getValueProfRecordNext(VR);
  744. }
  745. }
  746. template <class T>
  747. static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
  748. using namespace support;
  749. if (Orig == little)
  750. return endian::readNext<T, little, unaligned>(D);
  751. else
  752. return endian::readNext<T, big, unaligned>(D);
  753. }
  754. static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
  755. return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
  756. ValueProfData());
  757. }
  758. Error ValueProfData::checkIntegrity() {
  759. if (NumValueKinds > IPVK_Last + 1)
  760. return make_error<InstrProfError>(instrprof_error::malformed);
  761. // Total size needs to be mulltiple of quadword size.
  762. if (TotalSize % sizeof(uint64_t))
  763. return make_error<InstrProfError>(instrprof_error::malformed);
  764. ValueProfRecord *VR = getFirstValueProfRecord(this);
  765. for (uint32_t K = 0; K < this->NumValueKinds; K++) {
  766. if (VR->Kind > IPVK_Last)
  767. return make_error<InstrProfError>(instrprof_error::malformed);
  768. VR = getValueProfRecordNext(VR);
  769. if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
  770. return make_error<InstrProfError>(instrprof_error::malformed);
  771. }
  772. return Error::success();
  773. }
  774. Expected<std::unique_ptr<ValueProfData>>
  775. ValueProfData::getValueProfData(const unsigned char *D,
  776. const unsigned char *const BufferEnd,
  777. support::endianness Endianness) {
  778. using namespace support;
  779. if (D + sizeof(ValueProfData) > BufferEnd)
  780. return make_error<InstrProfError>(instrprof_error::truncated);
  781. const unsigned char *Header = D;
  782. uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
  783. if (D + TotalSize > BufferEnd)
  784. return make_error<InstrProfError>(instrprof_error::too_large);
  785. std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
  786. memcpy(VPD.get(), D, TotalSize);
  787. // Byte swap.
  788. VPD->swapBytesToHost(Endianness);
  789. Error E = VPD->checkIntegrity();
  790. if (E)
  791. return std::move(E);
  792. return std::move(VPD);
  793. }
  794. void ValueProfData::swapBytesToHost(support::endianness Endianness) {
  795. using namespace support;
  796. if (Endianness == getHostEndianness())
  797. return;
  798. sys::swapByteOrder<uint32_t>(TotalSize);
  799. sys::swapByteOrder<uint32_t>(NumValueKinds);
  800. ValueProfRecord *VR = getFirstValueProfRecord(this);
  801. for (uint32_t K = 0; K < NumValueKinds; K++) {
  802. VR->swapBytes(Endianness, getHostEndianness());
  803. VR = getValueProfRecordNext(VR);
  804. }
  805. }
  806. void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
  807. using namespace support;
  808. if (Endianness == getHostEndianness())
  809. return;
  810. ValueProfRecord *VR = getFirstValueProfRecord(this);
  811. for (uint32_t K = 0; K < NumValueKinds; K++) {
  812. ValueProfRecord *NVR = getValueProfRecordNext(VR);
  813. VR->swapBytes(getHostEndianness(), Endianness);
  814. VR = NVR;
  815. }
  816. sys::swapByteOrder<uint32_t>(TotalSize);
  817. sys::swapByteOrder<uint32_t>(NumValueKinds);
  818. }
  819. void annotateValueSite(Module &M, Instruction &Inst,
  820. const InstrProfRecord &InstrProfR,
  821. InstrProfValueKind ValueKind, uint32_t SiteIdx,
  822. uint32_t MaxMDCount) {
  823. uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
  824. if (!NV)
  825. return;
  826. uint64_t Sum = 0;
  827. std::unique_ptr<InstrProfValueData[]> VD =
  828. InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
  829. ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
  830. annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
  831. }
  832. void annotateValueSite(Module &M, Instruction &Inst,
  833. ArrayRef<InstrProfValueData> VDs,
  834. uint64_t Sum, InstrProfValueKind ValueKind,
  835. uint32_t MaxMDCount) {
  836. LLVMContext &Ctx = M.getContext();
  837. MDBuilder MDHelper(Ctx);
  838. SmallVector<Metadata *, 3> Vals;
  839. // Tag
  840. Vals.push_back(MDHelper.createString("VP"));
  841. // Value Kind
  842. Vals.push_back(MDHelper.createConstant(
  843. ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
  844. // Total Count
  845. Vals.push_back(
  846. MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
  847. // Value Profile Data
  848. uint32_t MDCount = MaxMDCount;
  849. for (auto &VD : VDs) {
  850. Vals.push_back(MDHelper.createConstant(
  851. ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
  852. Vals.push_back(MDHelper.createConstant(
  853. ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
  854. if (--MDCount == 0)
  855. break;
  856. }
  857. Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
  858. }
  859. bool getValueProfDataFromInst(const Instruction &Inst,
  860. InstrProfValueKind ValueKind,
  861. uint32_t MaxNumValueData,
  862. InstrProfValueData ValueData[],
  863. uint32_t &ActualNumValueData, uint64_t &TotalC) {
  864. MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
  865. if (!MD)
  866. return false;
  867. unsigned NOps = MD->getNumOperands();
  868. if (NOps < 5)
  869. return false;
  870. // Operand 0 is a string tag "VP":
  871. MDString *Tag = cast<MDString>(MD->getOperand(0));
  872. if (!Tag)
  873. return false;
  874. if (!Tag->getString().equals("VP"))
  875. return false;
  876. // Now check kind:
  877. ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  878. if (!KindInt)
  879. return false;
  880. if (KindInt->getZExtValue() != ValueKind)
  881. return false;
  882. // Get total count
  883. ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  884. if (!TotalCInt)
  885. return false;
  886. TotalC = TotalCInt->getZExtValue();
  887. ActualNumValueData = 0;
  888. for (unsigned I = 3; I < NOps; I += 2) {
  889. if (ActualNumValueData >= MaxNumValueData)
  890. break;
  891. ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
  892. ConstantInt *Count =
  893. mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
  894. if (!Value || !Count)
  895. return false;
  896. ValueData[ActualNumValueData].Value = Value->getZExtValue();
  897. ValueData[ActualNumValueData].Count = Count->getZExtValue();
  898. ActualNumValueData++;
  899. }
  900. return true;
  901. }
  902. MDNode *getPGOFuncNameMetadata(const Function &F) {
  903. return F.getMetadata(getPGOFuncNameMetadataName());
  904. }
  905. void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
  906. // Only for internal linkage functions.
  907. if (PGOFuncName == F.getName())
  908. return;
  909. // Don't create duplicated meta-data.
  910. if (getPGOFuncNameMetadata(F))
  911. return;
  912. LLVMContext &C = F.getContext();
  913. MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
  914. F.setMetadata(getPGOFuncNameMetadataName(), N);
  915. }
  916. bool needsComdatForCounter(const Function &F, const Module &M) {
  917. if (F.hasComdat())
  918. return true;
  919. if (!Triple(M.getTargetTriple()).supportsCOMDAT())
  920. return false;
  921. // See createPGOFuncNameVar for more details. To avoid link errors, profile
  922. // counters for function with available_externally linkage needs to be changed
  923. // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
  924. // created. Without using comdat, duplicate entries won't be removed by the
  925. // linker leading to increased data segement size and raw profile size. Even
  926. // worse, since the referenced counter from profile per-function data object
  927. // will be resolved to the common strong definition, the profile counts for
  928. // available_externally functions will end up being duplicated in raw profile
  929. // data. This can result in distorted profile as the counts of those dups
  930. // will be accumulated by the profile merger.
  931. GlobalValue::LinkageTypes Linkage = F.getLinkage();
  932. if (Linkage != GlobalValue::ExternalWeakLinkage &&
  933. Linkage != GlobalValue::AvailableExternallyLinkage)
  934. return false;
  935. return true;
  936. }
  937. // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
  938. bool isIRPGOFlagSet(const Module *M) {
  939. auto IRInstrVar =
  940. M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
  941. if (!IRInstrVar || IRInstrVar->isDeclaration() ||
  942. IRInstrVar->hasLocalLinkage())
  943. return false;
  944. // Check if the flag is set.
  945. if (!IRInstrVar->hasInitializer())
  946. return false;
  947. auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
  948. if (!InitVal)
  949. return false;
  950. return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
  951. }
  952. // Check if we can safely rename this Comdat function.
  953. bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
  954. if (F.getName().empty())
  955. return false;
  956. if (!needsComdatForCounter(F, *(F.getParent())))
  957. return false;
  958. // Unsafe to rename the address-taken function (which can be used in
  959. // function comparison).
  960. if (CheckAddressTaken && F.hasAddressTaken())
  961. return false;
  962. // Only safe to do if this function may be discarded if it is not used
  963. // in the compilation unit.
  964. if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
  965. return false;
  966. // For AvailableExternallyLinkage functions.
  967. if (!F.hasComdat()) {
  968. assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
  969. return true;
  970. }
  971. return true;
  972. }
  973. // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
  974. // aware this is an ir_level profile so it can set the version flag.
  975. void createIRLevelProfileFlagVar(Module &M, bool IsCS,
  976. bool InstrEntryBBEnabled) {
  977. const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
  978. Type *IntTy64 = Type::getInt64Ty(M.getContext());
  979. uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
  980. if (IsCS)
  981. ProfileVersion |= VARIANT_MASK_CSIR_PROF;
  982. if (InstrEntryBBEnabled)
  983. ProfileVersion |= VARIANT_MASK_INSTR_ENTRY;
  984. auto IRLevelVersionVariable = new GlobalVariable(
  985. M, IntTy64, true, GlobalValue::WeakAnyLinkage,
  986. Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
  987. IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
  988. Triple TT(M.getTargetTriple());
  989. if (TT.supportsCOMDAT()) {
  990. IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
  991. IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
  992. }
  993. }
  994. // Create the variable for the profile file name.
  995. void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
  996. if (InstrProfileOutput.empty())
  997. return;
  998. Constant *ProfileNameConst =
  999. ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
  1000. GlobalVariable *ProfileNameVar = new GlobalVariable(
  1001. M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
  1002. ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
  1003. Triple TT(M.getTargetTriple());
  1004. if (TT.supportsCOMDAT()) {
  1005. ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
  1006. ProfileNameVar->setComdat(M.getOrInsertComdat(
  1007. StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
  1008. }
  1009. }
  1010. Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
  1011. const std::string &TestFilename,
  1012. bool IsCS) {
  1013. auto getProfileSum = [IsCS](const std::string &Filename,
  1014. CountSumOrPercent &Sum) -> Error {
  1015. auto ReaderOrErr = InstrProfReader::create(Filename);
  1016. if (Error E = ReaderOrErr.takeError()) {
  1017. return E;
  1018. }
  1019. auto Reader = std::move(ReaderOrErr.get());
  1020. Reader->accumulateCounts(Sum, IsCS);
  1021. return Error::success();
  1022. };
  1023. auto Ret = getProfileSum(BaseFilename, Base);
  1024. if (Ret)
  1025. return Ret;
  1026. Ret = getProfileSum(TestFilename, Test);
  1027. if (Ret)
  1028. return Ret;
  1029. this->BaseFilename = &BaseFilename;
  1030. this->TestFilename = &TestFilename;
  1031. Valid = true;
  1032. return Error::success();
  1033. }
  1034. void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
  1035. Mismatch.NumEntries += 1;
  1036. Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
  1037. for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
  1038. if (Test.ValueCounts[I] >= 1.0f)
  1039. Mismatch.ValueCounts[I] +=
  1040. MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
  1041. }
  1042. }
  1043. void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
  1044. Unique.NumEntries += 1;
  1045. Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
  1046. for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
  1047. if (Test.ValueCounts[I] >= 1.0f)
  1048. Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
  1049. }
  1050. }
  1051. void OverlapStats::dump(raw_fd_ostream &OS) const {
  1052. if (!Valid)
  1053. return;
  1054. const char *EntryName =
  1055. (Level == ProgramLevel ? "functions" : "edge counters");
  1056. if (Level == ProgramLevel) {
  1057. OS << "Profile overlap infomation for base_profile: " << *BaseFilename
  1058. << " and test_profile: " << *TestFilename << "\nProgram level:\n";
  1059. } else {
  1060. OS << "Function level:\n"
  1061. << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
  1062. }
  1063. OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
  1064. if (Mismatch.NumEntries)
  1065. OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
  1066. << "\n";
  1067. if (Unique.NumEntries)
  1068. OS << " # of " << EntryName
  1069. << " only in test_profile: " << Unique.NumEntries << "\n";
  1070. OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
  1071. << "\n";
  1072. if (Mismatch.NumEntries)
  1073. OS << " Mismatched count percentage (Edge): "
  1074. << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
  1075. if (Unique.NumEntries)
  1076. OS << " Percentage of Edge profile only in test_profile: "
  1077. << format("%.3f%%", Unique.CountSum * 100) << "\n";
  1078. OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
  1079. << "\n"
  1080. << " Edge profile test count sum: " << format("%.0f", Test.CountSum)
  1081. << "\n";
  1082. for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
  1083. if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
  1084. continue;
  1085. char ProfileKindName[20];
  1086. switch (I) {
  1087. case IPVK_IndirectCallTarget:
  1088. strncpy(ProfileKindName, "IndirectCall", 19);
  1089. break;
  1090. case IPVK_MemOPSize:
  1091. strncpy(ProfileKindName, "MemOP", 19);
  1092. break;
  1093. default:
  1094. snprintf(ProfileKindName, 19, "VP[%d]", I);
  1095. break;
  1096. }
  1097. OS << " " << ProfileKindName
  1098. << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
  1099. << "\n";
  1100. if (Mismatch.NumEntries)
  1101. OS << " Mismatched count percentage (" << ProfileKindName
  1102. << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
  1103. if (Unique.NumEntries)
  1104. OS << " Percentage of " << ProfileKindName
  1105. << " profile only in test_profile: "
  1106. << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
  1107. OS << " " << ProfileKindName
  1108. << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
  1109. << "\n"
  1110. << " " << ProfileKindName
  1111. << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
  1112. << "\n";
  1113. }
  1114. }
  1115. } // end namespace llvm