llvm-profdata.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669
  1. //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
  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. // llvm-profdata merges .profdata files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/SmallSet.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  16. #include "llvm/IR/LLVMContext.h"
  17. #include "llvm/Object/Binary.h"
  18. #include "llvm/ProfileData/InstrProfCorrelator.h"
  19. #include "llvm/ProfileData/InstrProfReader.h"
  20. #include "llvm/ProfileData/InstrProfWriter.h"
  21. #include "llvm/ProfileData/ProfileCommon.h"
  22. #include "llvm/ProfileData/RawMemProfReader.h"
  23. #include "llvm/ProfileData/SampleProfReader.h"
  24. #include "llvm/ProfileData/SampleProfWriter.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/Discriminator.h"
  27. #include "llvm/Support/Errc.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/Format.h"
  30. #include "llvm/Support/FormattedStream.h"
  31. #include "llvm/Support/InitLLVM.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/ThreadPool.h"
  35. #include "llvm/Support/Threading.h"
  36. #include "llvm/Support/WithColor.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <algorithm>
  39. using namespace llvm;
  40. enum ProfileFormat {
  41. PF_None = 0,
  42. PF_Text,
  43. PF_Compact_Binary,
  44. PF_Ext_Binary,
  45. PF_GCC,
  46. PF_Binary
  47. };
  48. static void warn(Twine Message, std::string Whence = "",
  49. std::string Hint = "") {
  50. WithColor::warning();
  51. if (!Whence.empty())
  52. errs() << Whence << ": ";
  53. errs() << Message << "\n";
  54. if (!Hint.empty())
  55. WithColor::note() << Hint << "\n";
  56. }
  57. static void warn(Error E, StringRef Whence = "") {
  58. if (E.isA<InstrProfError>()) {
  59. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  60. warn(IPE.message(), std::string(Whence), std::string(""));
  61. });
  62. }
  63. }
  64. static void exitWithError(Twine Message, std::string Whence = "",
  65. std::string Hint = "") {
  66. WithColor::error();
  67. if (!Whence.empty())
  68. errs() << Whence << ": ";
  69. errs() << Message << "\n";
  70. if (!Hint.empty())
  71. WithColor::note() << Hint << "\n";
  72. ::exit(1);
  73. }
  74. static void exitWithError(Error E, StringRef Whence = "") {
  75. if (E.isA<InstrProfError>()) {
  76. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  77. instrprof_error instrError = IPE.get();
  78. StringRef Hint = "";
  79. if (instrError == instrprof_error::unrecognized_format) {
  80. // Hint in case user missed specifying the profile type.
  81. Hint = "Perhaps you forgot to use the --sample or --memory option?";
  82. }
  83. exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
  84. });
  85. }
  86. exitWithError(toString(std::move(E)), std::string(Whence));
  87. }
  88. static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
  89. exitWithError(EC.message(), std::string(Whence));
  90. }
  91. namespace {
  92. enum ProfileKinds { instr, sample, memory };
  93. enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
  94. }
  95. static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
  96. StringRef Whence = "") {
  97. if (FailMode == failIfAnyAreInvalid)
  98. exitWithErrorCode(EC, Whence);
  99. else
  100. warn(EC.message(), std::string(Whence));
  101. }
  102. static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
  103. StringRef WhenceFunction = "",
  104. bool ShowHint = true) {
  105. if (!WhenceFile.empty())
  106. errs() << WhenceFile << ": ";
  107. if (!WhenceFunction.empty())
  108. errs() << WhenceFunction << ": ";
  109. auto IPE = instrprof_error::success;
  110. E = handleErrors(std::move(E),
  111. [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
  112. IPE = E->get();
  113. return Error(std::move(E));
  114. });
  115. errs() << toString(std::move(E)) << "\n";
  116. if (ShowHint) {
  117. StringRef Hint = "";
  118. if (IPE != instrprof_error::success) {
  119. switch (IPE) {
  120. case instrprof_error::hash_mismatch:
  121. case instrprof_error::count_mismatch:
  122. case instrprof_error::value_site_count_mismatch:
  123. Hint = "Make sure that all profile data to be merged is generated "
  124. "from the same binary.";
  125. break;
  126. default:
  127. break;
  128. }
  129. }
  130. if (!Hint.empty())
  131. errs() << Hint << "\n";
  132. }
  133. }
  134. namespace {
  135. /// A remapper from original symbol names to new symbol names based on a file
  136. /// containing a list of mappings from old name to new name.
  137. class SymbolRemapper {
  138. std::unique_ptr<MemoryBuffer> File;
  139. DenseMap<StringRef, StringRef> RemappingTable;
  140. public:
  141. /// Build a SymbolRemapper from a file containing a list of old/new symbols.
  142. static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
  143. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  144. if (!BufOrError)
  145. exitWithErrorCode(BufOrError.getError(), InputFile);
  146. auto Remapper = std::make_unique<SymbolRemapper>();
  147. Remapper->File = std::move(BufOrError.get());
  148. for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
  149. !LineIt.is_at_eof(); ++LineIt) {
  150. std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
  151. if (Parts.first.empty() || Parts.second.empty() ||
  152. Parts.second.count(' ')) {
  153. exitWithError("unexpected line in remapping file",
  154. (InputFile + ":" + Twine(LineIt.line_number())).str(),
  155. "expected 'old_symbol new_symbol'");
  156. }
  157. Remapper->RemappingTable.insert(Parts);
  158. }
  159. return Remapper;
  160. }
  161. /// Attempt to map the given old symbol into a new symbol.
  162. ///
  163. /// \return The new symbol, or \p Name if no such symbol was found.
  164. StringRef operator()(StringRef Name) {
  165. StringRef New = RemappingTable.lookup(Name);
  166. return New.empty() ? Name : New;
  167. }
  168. };
  169. }
  170. struct WeightedFile {
  171. std::string Filename;
  172. uint64_t Weight;
  173. };
  174. typedef SmallVector<WeightedFile, 5> WeightedFileVector;
  175. /// Keep track of merged data and reported errors.
  176. struct WriterContext {
  177. std::mutex Lock;
  178. InstrProfWriter Writer;
  179. std::vector<std::pair<Error, std::string>> Errors;
  180. std::mutex &ErrLock;
  181. SmallSet<instrprof_error, 4> &WriterErrorCodes;
  182. WriterContext(bool IsSparse, std::mutex &ErrLock,
  183. SmallSet<instrprof_error, 4> &WriterErrorCodes)
  184. : Writer(IsSparse), ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {
  185. }
  186. };
  187. /// Computer the overlap b/w profile BaseFilename and TestFileName,
  188. /// and store the program level result to Overlap.
  189. static void overlapInput(const std::string &BaseFilename,
  190. const std::string &TestFilename, WriterContext *WC,
  191. OverlapStats &Overlap,
  192. const OverlapFuncFilters &FuncFilter,
  193. raw_fd_ostream &OS, bool IsCS) {
  194. auto ReaderOrErr = InstrProfReader::create(TestFilename);
  195. if (Error E = ReaderOrErr.takeError()) {
  196. // Skip the empty profiles by returning sliently.
  197. instrprof_error IPE = InstrProfError::take(std::move(E));
  198. if (IPE != instrprof_error::empty_raw_profile)
  199. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
  200. return;
  201. }
  202. auto Reader = std::move(ReaderOrErr.get());
  203. for (auto &I : *Reader) {
  204. OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
  205. FuncOverlap.setFuncInfo(I.Name, I.Hash);
  206. WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
  207. FuncOverlap.dump(OS);
  208. }
  209. }
  210. /// Load an input into a writer context.
  211. static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
  212. const InstrProfCorrelator *Correlator,
  213. WriterContext *WC) {
  214. std::unique_lock<std::mutex> CtxGuard{WC->Lock};
  215. // Copy the filename, because llvm::ThreadPool copied the input "const
  216. // WeightedFile &" by value, making a reference to the filename within it
  217. // invalid outside of this packaged task.
  218. std::string Filename = Input.Filename;
  219. auto ReaderOrErr = InstrProfReader::create(Input.Filename, Correlator);
  220. if (Error E = ReaderOrErr.takeError()) {
  221. // Skip the empty profiles by returning sliently.
  222. instrprof_error IPE = InstrProfError::take(std::move(E));
  223. if (IPE != instrprof_error::empty_raw_profile)
  224. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
  225. return;
  226. }
  227. auto Reader = std::move(ReaderOrErr.get());
  228. if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
  229. consumeError(std::move(E));
  230. WC->Errors.emplace_back(
  231. make_error<StringError>(
  232. "Merge IR generated profile with Clang generated profile.",
  233. std::error_code()),
  234. Filename);
  235. return;
  236. }
  237. for (auto &I : *Reader) {
  238. if (Remapper)
  239. I.Name = (*Remapper)(I.Name);
  240. const StringRef FuncName = I.Name;
  241. bool Reported = false;
  242. WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
  243. if (Reported) {
  244. consumeError(std::move(E));
  245. return;
  246. }
  247. Reported = true;
  248. // Only show hint the first time an error occurs.
  249. instrprof_error IPE = InstrProfError::take(std::move(E));
  250. std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
  251. bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
  252. handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
  253. FuncName, firstTime);
  254. });
  255. }
  256. if (Reader->hasError())
  257. if (Error E = Reader->getError())
  258. WC->Errors.emplace_back(std::move(E), Filename);
  259. }
  260. /// Merge the \p Src writer context into \p Dst.
  261. static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
  262. for (auto &ErrorPair : Src->Errors)
  263. Dst->Errors.push_back(std::move(ErrorPair));
  264. Src->Errors.clear();
  265. Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
  266. instrprof_error IPE = InstrProfError::take(std::move(E));
  267. std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
  268. bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
  269. if (firstTime)
  270. warn(toString(make_error<InstrProfError>(IPE)));
  271. });
  272. }
  273. static void writeInstrProfile(StringRef OutputFilename,
  274. ProfileFormat OutputFormat,
  275. InstrProfWriter &Writer) {
  276. std::error_code EC;
  277. raw_fd_ostream Output(OutputFilename.data(), EC,
  278. OutputFormat == PF_Text ? sys::fs::OF_TextWithCRLF
  279. : sys::fs::OF_None);
  280. if (EC)
  281. exitWithErrorCode(EC, OutputFilename);
  282. if (OutputFormat == PF_Text) {
  283. if (Error E = Writer.writeText(Output))
  284. warn(std::move(E));
  285. } else {
  286. if (Output.is_displayed())
  287. exitWithError("cannot write a non-text format profile to the terminal");
  288. if (Error E = Writer.write(Output))
  289. warn(std::move(E));
  290. }
  291. }
  292. static void mergeInstrProfile(const WeightedFileVector &Inputs,
  293. StringRef DebugInfoFilename,
  294. SymbolRemapper *Remapper,
  295. StringRef OutputFilename,
  296. ProfileFormat OutputFormat, bool OutputSparse,
  297. unsigned NumThreads, FailureMode FailMode) {
  298. if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
  299. OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
  300. exitWithError("unknown format is specified");
  301. std::unique_ptr<InstrProfCorrelator> Correlator;
  302. if (!DebugInfoFilename.empty()) {
  303. if (auto Err =
  304. InstrProfCorrelator::get(DebugInfoFilename).moveInto(Correlator))
  305. exitWithError(std::move(Err), DebugInfoFilename);
  306. if (auto Err = Correlator->correlateProfileData())
  307. exitWithError(std::move(Err), DebugInfoFilename);
  308. }
  309. std::mutex ErrorLock;
  310. SmallSet<instrprof_error, 4> WriterErrorCodes;
  311. // If NumThreads is not specified, auto-detect a good default.
  312. if (NumThreads == 0)
  313. NumThreads = std::min(hardware_concurrency().compute_thread_count(),
  314. unsigned((Inputs.size() + 1) / 2));
  315. // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
  316. // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
  317. // merged, thus the emitted file ends up with a PF_Unknown kind.
  318. // Initialize the writer contexts.
  319. SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
  320. for (unsigned I = 0; I < NumThreads; ++I)
  321. Contexts.emplace_back(std::make_unique<WriterContext>(
  322. OutputSparse, ErrorLock, WriterErrorCodes));
  323. if (NumThreads == 1) {
  324. for (const auto &Input : Inputs)
  325. loadInput(Input, Remapper, Correlator.get(), Contexts[0].get());
  326. } else {
  327. ThreadPool Pool(hardware_concurrency(NumThreads));
  328. // Load the inputs in parallel (N/NumThreads serial steps).
  329. unsigned Ctx = 0;
  330. for (const auto &Input : Inputs) {
  331. Pool.async(loadInput, Input, Remapper, Correlator.get(),
  332. Contexts[Ctx].get());
  333. Ctx = (Ctx + 1) % NumThreads;
  334. }
  335. Pool.wait();
  336. // Merge the writer contexts together (~ lg(NumThreads) serial steps).
  337. unsigned Mid = Contexts.size() / 2;
  338. unsigned End = Contexts.size();
  339. assert(Mid > 0 && "Expected more than one context");
  340. do {
  341. for (unsigned I = 0; I < Mid; ++I)
  342. Pool.async(mergeWriterContexts, Contexts[I].get(),
  343. Contexts[I + Mid].get());
  344. Pool.wait();
  345. if (End & 1) {
  346. Pool.async(mergeWriterContexts, Contexts[0].get(),
  347. Contexts[End - 1].get());
  348. Pool.wait();
  349. }
  350. End = Mid;
  351. Mid /= 2;
  352. } while (Mid > 0);
  353. }
  354. // Handle deferred errors encountered during merging. If the number of errors
  355. // is equal to the number of inputs the merge failed.
  356. unsigned NumErrors = 0;
  357. for (std::unique_ptr<WriterContext> &WC : Contexts) {
  358. for (auto &ErrorPair : WC->Errors) {
  359. ++NumErrors;
  360. warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
  361. }
  362. }
  363. if (NumErrors == Inputs.size() ||
  364. (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
  365. exitWithError("no profile can be merged");
  366. writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
  367. }
  368. /// The profile entry for a function in instrumentation profile.
  369. struct InstrProfileEntry {
  370. uint64_t MaxCount = 0;
  371. float ZeroCounterRatio = 0.0;
  372. InstrProfRecord *ProfRecord;
  373. InstrProfileEntry(InstrProfRecord *Record);
  374. InstrProfileEntry() = default;
  375. };
  376. InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
  377. ProfRecord = Record;
  378. uint64_t CntNum = Record->Counts.size();
  379. uint64_t ZeroCntNum = 0;
  380. for (size_t I = 0; I < CntNum; ++I) {
  381. MaxCount = std::max(MaxCount, Record->Counts[I]);
  382. ZeroCntNum += !Record->Counts[I];
  383. }
  384. ZeroCounterRatio = (float)ZeroCntNum / CntNum;
  385. }
  386. /// Either set all the counters in the instr profile entry \p IFE to -1
  387. /// in order to drop the profile or scale up the counters in \p IFP to
  388. /// be above hot threshold. We use the ratio of zero counters in the
  389. /// profile of a function to decide the profile is helpful or harmful
  390. /// for performance, and to choose whether to scale up or drop it.
  391. static void updateInstrProfileEntry(InstrProfileEntry &IFE,
  392. uint64_t HotInstrThreshold,
  393. float ZeroCounterThreshold) {
  394. InstrProfRecord *ProfRecord = IFE.ProfRecord;
  395. if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
  396. // If all or most of the counters of the function are zero, the
  397. // profile is unaccountable and shuld be dropped. Reset all the
  398. // counters to be -1 and PGO profile-use will drop the profile.
  399. // All counters being -1 also implies that the function is hot so
  400. // PGO profile-use will also set the entry count metadata to be
  401. // above hot threshold.
  402. for (size_t I = 0; I < ProfRecord->Counts.size(); ++I)
  403. ProfRecord->Counts[I] = -1;
  404. return;
  405. }
  406. // Scale up the MaxCount to be multiple times above hot threshold.
  407. const unsigned MultiplyFactor = 3;
  408. uint64_t Numerator = HotInstrThreshold * MultiplyFactor;
  409. uint64_t Denominator = IFE.MaxCount;
  410. ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
  411. warn(toString(make_error<InstrProfError>(E)));
  412. });
  413. }
  414. const uint64_t ColdPercentileIdx = 15;
  415. const uint64_t HotPercentileIdx = 11;
  416. using sampleprof::FSDiscriminatorPass;
  417. // Internal options to set FSDiscriminatorPass. Used in merge and show
  418. // commands.
  419. static cl::opt<FSDiscriminatorPass> FSDiscriminatorPassOption(
  420. "fs-discriminator-pass", cl::init(PassLast), cl::Hidden,
  421. cl::desc("Zero out the discriminator bits for the FS discrimiantor "
  422. "pass beyond this value. The enum values are defined in "
  423. "Support/Discriminator.h"),
  424. cl::values(clEnumVal(Base, "Use base discriminators only"),
  425. clEnumVal(Pass1, "Use base and pass 1 discriminators"),
  426. clEnumVal(Pass2, "Use base and pass 1-2 discriminators"),
  427. clEnumVal(Pass3, "Use base and pass 1-3 discriminators"),
  428. clEnumVal(PassLast, "Use all discriminator bits (default)")));
  429. static unsigned getDiscriminatorMask() {
  430. return getN1Bits(getFSPassBitEnd(FSDiscriminatorPassOption.getValue()));
  431. }
  432. /// Adjust the instr profile in \p WC based on the sample profile in
  433. /// \p Reader.
  434. static void
  435. adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
  436. std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
  437. unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
  438. unsigned InstrProfColdThreshold) {
  439. // Function to its entry in instr profile.
  440. StringMap<InstrProfileEntry> InstrProfileMap;
  441. InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
  442. for (auto &PD : WC->Writer.getProfileData()) {
  443. // Populate IPBuilder.
  444. for (const auto &PDV : PD.getValue()) {
  445. InstrProfRecord Record = PDV.second;
  446. IPBuilder.addRecord(Record);
  447. }
  448. // If a function has multiple entries in instr profile, skip it.
  449. if (PD.getValue().size() != 1)
  450. continue;
  451. // Initialize InstrProfileMap.
  452. InstrProfRecord *R = &PD.getValue().begin()->second;
  453. InstrProfileMap[PD.getKey()] = InstrProfileEntry(R);
  454. }
  455. ProfileSummary InstrPS = *IPBuilder.getSummary();
  456. ProfileSummary SamplePS = Reader->getSummary();
  457. // Compute cold thresholds for instr profile and sample profile.
  458. uint64_t ColdSampleThreshold =
  459. ProfileSummaryBuilder::getEntryForPercentile(
  460. SamplePS.getDetailedSummary(),
  461. ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
  462. .MinCount;
  463. uint64_t HotInstrThreshold =
  464. ProfileSummaryBuilder::getEntryForPercentile(
  465. InstrPS.getDetailedSummary(),
  466. ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
  467. .MinCount;
  468. uint64_t ColdInstrThreshold =
  469. InstrProfColdThreshold
  470. ? InstrProfColdThreshold
  471. : ProfileSummaryBuilder::getEntryForPercentile(
  472. InstrPS.getDetailedSummary(),
  473. ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
  474. .MinCount;
  475. // Find hot/warm functions in sample profile which is cold in instr profile
  476. // and adjust the profiles of those functions in the instr profile.
  477. for (const auto &PD : Reader->getProfiles()) {
  478. auto &FContext = PD.first;
  479. const sampleprof::FunctionSamples &FS = PD.second;
  480. auto It = InstrProfileMap.find(FContext.toString());
  481. if (FS.getHeadSamples() > ColdSampleThreshold &&
  482. It != InstrProfileMap.end() &&
  483. It->second.MaxCount <= ColdInstrThreshold &&
  484. FS.getBodySamples().size() >= SupplMinSizeThreshold) {
  485. updateInstrProfileEntry(It->second, HotInstrThreshold,
  486. ZeroCounterThreshold);
  487. }
  488. }
  489. }
  490. /// The main function to supplement instr profile with sample profile.
  491. /// \Inputs contains the instr profile. \p SampleFilename specifies the
  492. /// sample profile. \p OutputFilename specifies the output profile name.
  493. /// \p OutputFormat specifies the output profile format. \p OutputSparse
  494. /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
  495. /// specifies the minimal size for the functions whose profile will be
  496. /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
  497. /// a function contains too many zero counters and whether its profile
  498. /// should be dropped. \p InstrProfColdThreshold is the user specified
  499. /// cold threshold which will override the cold threshold got from the
  500. /// instr profile summary.
  501. static void supplementInstrProfile(
  502. const WeightedFileVector &Inputs, StringRef SampleFilename,
  503. StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse,
  504. unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
  505. unsigned InstrProfColdThreshold) {
  506. if (OutputFilename.compare("-") == 0)
  507. exitWithError("cannot write indexed profdata format to stdout");
  508. if (Inputs.size() != 1)
  509. exitWithError("expect one input to be an instr profile");
  510. if (Inputs[0].Weight != 1)
  511. exitWithError("expect instr profile doesn't have weight");
  512. StringRef InstrFilename = Inputs[0].Filename;
  513. // Read sample profile.
  514. LLVMContext Context;
  515. auto ReaderOrErr = sampleprof::SampleProfileReader::create(
  516. SampleFilename.str(), Context, FSDiscriminatorPassOption);
  517. if (std::error_code EC = ReaderOrErr.getError())
  518. exitWithErrorCode(EC, SampleFilename);
  519. auto Reader = std::move(ReaderOrErr.get());
  520. if (std::error_code EC = Reader->read())
  521. exitWithErrorCode(EC, SampleFilename);
  522. // Read instr profile.
  523. std::mutex ErrorLock;
  524. SmallSet<instrprof_error, 4> WriterErrorCodes;
  525. auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
  526. WriterErrorCodes);
  527. loadInput(Inputs[0], nullptr, nullptr, WC.get());
  528. if (WC->Errors.size() > 0)
  529. exitWithError(std::move(WC->Errors[0].first), InstrFilename);
  530. adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
  531. InstrProfColdThreshold);
  532. writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
  533. }
  534. /// Make a copy of the given function samples with all symbol names remapped
  535. /// by the provided symbol remapper.
  536. static sampleprof::FunctionSamples
  537. remapSamples(const sampleprof::FunctionSamples &Samples,
  538. SymbolRemapper &Remapper, sampleprof_error &Error) {
  539. sampleprof::FunctionSamples Result;
  540. Result.setName(Remapper(Samples.getName()));
  541. Result.addTotalSamples(Samples.getTotalSamples());
  542. Result.addHeadSamples(Samples.getHeadSamples());
  543. for (const auto &BodySample : Samples.getBodySamples()) {
  544. uint32_t MaskedDiscriminator =
  545. BodySample.first.Discriminator & getDiscriminatorMask();
  546. Result.addBodySamples(BodySample.first.LineOffset, MaskedDiscriminator,
  547. BodySample.second.getSamples());
  548. for (const auto &Target : BodySample.second.getCallTargets()) {
  549. Result.addCalledTargetSamples(BodySample.first.LineOffset,
  550. MaskedDiscriminator,
  551. Remapper(Target.first()), Target.second);
  552. }
  553. }
  554. for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
  555. sampleprof::FunctionSamplesMap &Target =
  556. Result.functionSamplesAt(CallsiteSamples.first);
  557. for (const auto &Callsite : CallsiteSamples.second) {
  558. sampleprof::FunctionSamples Remapped =
  559. remapSamples(Callsite.second, Remapper, Error);
  560. MergeResult(Error,
  561. Target[std::string(Remapped.getName())].merge(Remapped));
  562. }
  563. }
  564. return Result;
  565. }
  566. static sampleprof::SampleProfileFormat FormatMap[] = {
  567. sampleprof::SPF_None,
  568. sampleprof::SPF_Text,
  569. sampleprof::SPF_Compact_Binary,
  570. sampleprof::SPF_Ext_Binary,
  571. sampleprof::SPF_GCC,
  572. sampleprof::SPF_Binary};
  573. static std::unique_ptr<MemoryBuffer>
  574. getInputFileBuf(const StringRef &InputFile) {
  575. if (InputFile == "")
  576. return {};
  577. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  578. if (!BufOrError)
  579. exitWithErrorCode(BufOrError.getError(), InputFile);
  580. return std::move(*BufOrError);
  581. }
  582. static void populateProfileSymbolList(MemoryBuffer *Buffer,
  583. sampleprof::ProfileSymbolList &PSL) {
  584. if (!Buffer)
  585. return;
  586. SmallVector<StringRef, 32> SymbolVec;
  587. StringRef Data = Buffer->getBuffer();
  588. Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  589. for (StringRef SymbolStr : SymbolVec)
  590. PSL.add(SymbolStr.trim());
  591. }
  592. static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
  593. ProfileFormat OutputFormat,
  594. MemoryBuffer *Buffer,
  595. sampleprof::ProfileSymbolList &WriterList,
  596. bool CompressAllSections, bool UseMD5,
  597. bool GenPartialProfile) {
  598. populateProfileSymbolList(Buffer, WriterList);
  599. if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
  600. warn("Profile Symbol list is not empty but the output format is not "
  601. "ExtBinary format. The list will be lost in the output. ");
  602. Writer.setProfileSymbolList(&WriterList);
  603. if (CompressAllSections) {
  604. if (OutputFormat != PF_Ext_Binary)
  605. warn("-compress-all-section is ignored. Specify -extbinary to enable it");
  606. else
  607. Writer.setToCompressAllSections();
  608. }
  609. if (UseMD5) {
  610. if (OutputFormat != PF_Ext_Binary)
  611. warn("-use-md5 is ignored. Specify -extbinary to enable it");
  612. else
  613. Writer.setUseMD5();
  614. }
  615. if (GenPartialProfile) {
  616. if (OutputFormat != PF_Ext_Binary)
  617. warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
  618. else
  619. Writer.setPartialProfile();
  620. }
  621. }
  622. static void
  623. mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
  624. StringRef OutputFilename, ProfileFormat OutputFormat,
  625. StringRef ProfileSymbolListFile, bool CompressAllSections,
  626. bool UseMD5, bool GenPartialProfile, bool GenCSNestedProfile,
  627. bool SampleMergeColdContext, bool SampleTrimColdContext,
  628. bool SampleColdContextFrameDepth, FailureMode FailMode) {
  629. using namespace sampleprof;
  630. SampleProfileMap ProfileMap;
  631. SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
  632. LLVMContext Context;
  633. sampleprof::ProfileSymbolList WriterList;
  634. Optional<bool> ProfileIsProbeBased;
  635. Optional<bool> ProfileIsCSFlat;
  636. for (const auto &Input : Inputs) {
  637. auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context,
  638. FSDiscriminatorPassOption);
  639. if (std::error_code EC = ReaderOrErr.getError()) {
  640. warnOrExitGivenError(FailMode, EC, Input.Filename);
  641. continue;
  642. }
  643. // We need to keep the readers around until after all the files are
  644. // read so that we do not lose the function names stored in each
  645. // reader's memory. The function names are needed to write out the
  646. // merged profile map.
  647. Readers.push_back(std::move(ReaderOrErr.get()));
  648. const auto Reader = Readers.back().get();
  649. if (std::error_code EC = Reader->read()) {
  650. warnOrExitGivenError(FailMode, EC, Input.Filename);
  651. Readers.pop_back();
  652. continue;
  653. }
  654. SampleProfileMap &Profiles = Reader->getProfiles();
  655. if (ProfileIsProbeBased.hasValue() &&
  656. ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
  657. exitWithError(
  658. "cannot merge probe-based profile with non-probe-based profile");
  659. ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
  660. if (ProfileIsCSFlat.hasValue() &&
  661. ProfileIsCSFlat != FunctionSamples::ProfileIsCSFlat)
  662. exitWithError("cannot merge CS profile with non-CS profile");
  663. ProfileIsCSFlat = FunctionSamples::ProfileIsCSFlat;
  664. for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end();
  665. I != E; ++I) {
  666. sampleprof_error Result = sampleprof_error::success;
  667. FunctionSamples Remapped =
  668. Remapper ? remapSamples(I->second, *Remapper, Result)
  669. : FunctionSamples();
  670. FunctionSamples &Samples = Remapper ? Remapped : I->second;
  671. SampleContext FContext = Samples.getContext();
  672. MergeResult(Result, ProfileMap[FContext].merge(Samples, Input.Weight));
  673. if (Result != sampleprof_error::success) {
  674. std::error_code EC = make_error_code(Result);
  675. handleMergeWriterError(errorCodeToError(EC), Input.Filename,
  676. FContext.toString());
  677. }
  678. }
  679. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  680. Reader->getProfileSymbolList();
  681. if (ReaderList)
  682. WriterList.merge(*ReaderList);
  683. }
  684. if (ProfileIsCSFlat && (SampleMergeColdContext || SampleTrimColdContext)) {
  685. // Use threshold calculated from profile summary unless specified.
  686. SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
  687. auto Summary = Builder.computeSummaryForProfiles(ProfileMap);
  688. uint64_t SampleProfColdThreshold =
  689. ProfileSummaryBuilder::getColdCountThreshold(
  690. (Summary->getDetailedSummary()));
  691. // Trim and merge cold context profile using cold threshold above;
  692. SampleContextTrimmer(ProfileMap)
  693. .trimAndMergeColdContextProfiles(
  694. SampleProfColdThreshold, SampleTrimColdContext,
  695. SampleMergeColdContext, SampleColdContextFrameDepth, false);
  696. }
  697. if (ProfileIsCSFlat && GenCSNestedProfile) {
  698. CSProfileConverter CSConverter(ProfileMap);
  699. CSConverter.convertProfiles();
  700. ProfileIsCSFlat = FunctionSamples::ProfileIsCSFlat = false;
  701. }
  702. auto WriterOrErr =
  703. SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
  704. if (std::error_code EC = WriterOrErr.getError())
  705. exitWithErrorCode(EC, OutputFilename);
  706. auto Writer = std::move(WriterOrErr.get());
  707. // WriterList will have StringRef refering to string in Buffer.
  708. // Make sure Buffer lives as long as WriterList.
  709. auto Buffer = getInputFileBuf(ProfileSymbolListFile);
  710. handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
  711. CompressAllSections, UseMD5, GenPartialProfile);
  712. if (std::error_code EC = Writer->write(ProfileMap))
  713. exitWithErrorCode(std::move(EC));
  714. }
  715. static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
  716. StringRef WeightStr, FileName;
  717. std::tie(WeightStr, FileName) = WeightedFilename.split(',');
  718. uint64_t Weight;
  719. if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
  720. exitWithError("input weight must be a positive integer");
  721. return {std::string(FileName), Weight};
  722. }
  723. static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
  724. StringRef Filename = WF.Filename;
  725. uint64_t Weight = WF.Weight;
  726. // If it's STDIN just pass it on.
  727. if (Filename == "-") {
  728. WNI.push_back({std::string(Filename), Weight});
  729. return;
  730. }
  731. llvm::sys::fs::file_status Status;
  732. llvm::sys::fs::status(Filename, Status);
  733. if (!llvm::sys::fs::exists(Status))
  734. exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
  735. Filename);
  736. // If it's a source file, collect it.
  737. if (llvm::sys::fs::is_regular_file(Status)) {
  738. WNI.push_back({std::string(Filename), Weight});
  739. return;
  740. }
  741. if (llvm::sys::fs::is_directory(Status)) {
  742. std::error_code EC;
  743. for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
  744. F != E && !EC; F.increment(EC)) {
  745. if (llvm::sys::fs::is_regular_file(F->path())) {
  746. addWeightedInput(WNI, {F->path(), Weight});
  747. }
  748. }
  749. if (EC)
  750. exitWithErrorCode(EC, Filename);
  751. }
  752. }
  753. static void parseInputFilenamesFile(MemoryBuffer *Buffer,
  754. WeightedFileVector &WFV) {
  755. if (!Buffer)
  756. return;
  757. SmallVector<StringRef, 8> Entries;
  758. StringRef Data = Buffer->getBuffer();
  759. Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  760. for (const StringRef &FileWeightEntry : Entries) {
  761. StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
  762. // Skip comments.
  763. if (SanitizedEntry.startswith("#"))
  764. continue;
  765. // If there's no comma, it's an unweighted profile.
  766. else if (!SanitizedEntry.contains(','))
  767. addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
  768. else
  769. addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
  770. }
  771. }
  772. static int merge_main(int argc, const char *argv[]) {
  773. cl::list<std::string> InputFilenames(cl::Positional,
  774. cl::desc("<filename...>"));
  775. cl::list<std::string> WeightedInputFilenames("weighted-input",
  776. cl::desc("<weight>,<filename>"));
  777. cl::opt<std::string> InputFilenamesFile(
  778. "input-files", cl::init(""),
  779. cl::desc("Path to file containing newline-separated "
  780. "[<weight>,]<filename> entries"));
  781. cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
  782. cl::aliasopt(InputFilenamesFile));
  783. cl::opt<bool> DumpInputFileList(
  784. "dump-input-file-list", cl::init(false), cl::Hidden,
  785. cl::desc("Dump the list of input files and their weights, then exit"));
  786. cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
  787. cl::desc("Symbol remapping file"));
  788. cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
  789. cl::aliasopt(RemappingFile));
  790. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  791. cl::init("-"), cl::desc("Output file"));
  792. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  793. cl::aliasopt(OutputFilename));
  794. cl::opt<ProfileKinds> ProfileKind(
  795. cl::desc("Profile kind:"), cl::init(instr),
  796. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  797. clEnumVal(sample, "Sample profile")));
  798. cl::opt<ProfileFormat> OutputFormat(
  799. cl::desc("Format of output profile"), cl::init(PF_Binary),
  800. cl::values(
  801. clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
  802. clEnumValN(PF_Compact_Binary, "compbinary",
  803. "Compact binary encoding"),
  804. clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  805. clEnumValN(PF_Text, "text", "Text encoding"),
  806. clEnumValN(PF_GCC, "gcc",
  807. "GCC encoding (only meaningful for -sample)")));
  808. cl::opt<FailureMode> FailureMode(
  809. "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
  810. cl::values(clEnumValN(failIfAnyAreInvalid, "any",
  811. "Fail if any profile is invalid."),
  812. clEnumValN(failIfAllAreInvalid, "all",
  813. "Fail only if all profiles are invalid.")));
  814. cl::opt<bool> OutputSparse("sparse", cl::init(false),
  815. cl::desc("Generate a sparse profile (only meaningful for -instr)"));
  816. cl::opt<unsigned> NumThreads(
  817. "num-threads", cl::init(0),
  818. cl::desc("Number of merge threads to use (default: autodetect)"));
  819. cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
  820. cl::aliasopt(NumThreads));
  821. cl::opt<std::string> ProfileSymbolListFile(
  822. "prof-sym-list", cl::init(""),
  823. cl::desc("Path to file containing the list of function symbols "
  824. "used to populate profile symbol list"));
  825. cl::opt<bool> CompressAllSections(
  826. "compress-all-sections", cl::init(false), cl::Hidden,
  827. cl::desc("Compress all sections when writing the profile (only "
  828. "meaningful for -extbinary)"));
  829. cl::opt<bool> UseMD5(
  830. "use-md5", cl::init(false), cl::Hidden,
  831. cl::desc("Choose to use MD5 to represent string in name table (only "
  832. "meaningful for -extbinary)"));
  833. cl::opt<bool> SampleMergeColdContext(
  834. "sample-merge-cold-context", cl::init(false), cl::Hidden,
  835. cl::desc(
  836. "Merge context sample profiles whose count is below cold threshold"));
  837. cl::opt<bool> SampleTrimColdContext(
  838. "sample-trim-cold-context", cl::init(false), cl::Hidden,
  839. cl::desc(
  840. "Trim context sample profiles whose count is below cold threshold"));
  841. cl::opt<uint32_t> SampleColdContextFrameDepth(
  842. "sample-frame-depth-for-cold-context", cl::init(1), cl::ZeroOrMore,
  843. cl::desc("Keep the last K frames while merging cold profile. 1 means the "
  844. "context-less base profile"));
  845. cl::opt<bool> GenPartialProfile(
  846. "gen-partial-profile", cl::init(false), cl::Hidden,
  847. cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
  848. cl::opt<std::string> SupplInstrWithSample(
  849. "supplement-instr-with-sample", cl::init(""), cl::Hidden,
  850. cl::desc("Supplement an instr profile with sample profile, to correct "
  851. "the profile unrepresentativeness issue. The sample "
  852. "profile is the input of the flag. Output will be in instr "
  853. "format (The flag only works with -instr)"));
  854. cl::opt<float> ZeroCounterThreshold(
  855. "zero-counter-threshold", cl::init(0.7), cl::Hidden,
  856. cl::desc("For the function which is cold in instr profile but hot in "
  857. "sample profile, if the ratio of the number of zero counters "
  858. "divided by the the total number of counters is above the "
  859. "threshold, the profile of the function will be regarded as "
  860. "being harmful for performance and will be dropped."));
  861. cl::opt<unsigned> SupplMinSizeThreshold(
  862. "suppl-min-size-threshold", cl::init(10), cl::Hidden,
  863. cl::desc("If the size of a function is smaller than the threshold, "
  864. "assume it can be inlined by PGO early inliner and it won't "
  865. "be adjusted based on sample profile."));
  866. cl::opt<unsigned> InstrProfColdThreshold(
  867. "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
  868. cl::desc("User specified cold threshold for instr profile which will "
  869. "override the cold threshold got from profile summary. "));
  870. cl::opt<bool> GenCSNestedProfile(
  871. "gen-cs-nested-profile", cl::Hidden, cl::init(false),
  872. cl::desc("Generate nested function profiles for CSSPGO"));
  873. cl::opt<std::string> DebugInfoFilename(
  874. "debug-info", cl::init(""),
  875. cl::desc("Use the provided debug info to correlate the raw profile."));
  876. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
  877. WeightedFileVector WeightedInputs;
  878. for (StringRef Filename : InputFilenames)
  879. addWeightedInput(WeightedInputs, {std::string(Filename), 1});
  880. for (StringRef WeightedFilename : WeightedInputFilenames)
  881. addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
  882. // Make sure that the file buffer stays alive for the duration of the
  883. // weighted input vector's lifetime.
  884. auto Buffer = getInputFileBuf(InputFilenamesFile);
  885. parseInputFilenamesFile(Buffer.get(), WeightedInputs);
  886. if (WeightedInputs.empty())
  887. exitWithError("no input files specified. See " +
  888. sys::path::filename(argv[0]) + " -help");
  889. if (DumpInputFileList) {
  890. for (auto &WF : WeightedInputs)
  891. outs() << WF.Weight << "," << WF.Filename << "\n";
  892. return 0;
  893. }
  894. std::unique_ptr<SymbolRemapper> Remapper;
  895. if (!RemappingFile.empty())
  896. Remapper = SymbolRemapper::create(RemappingFile);
  897. if (!SupplInstrWithSample.empty()) {
  898. if (ProfileKind != instr)
  899. exitWithError(
  900. "-supplement-instr-with-sample can only work with -instr. ");
  901. supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename,
  902. OutputFormat, OutputSparse, SupplMinSizeThreshold,
  903. ZeroCounterThreshold, InstrProfColdThreshold);
  904. return 0;
  905. }
  906. if (ProfileKind == instr)
  907. mergeInstrProfile(WeightedInputs, DebugInfoFilename, Remapper.get(),
  908. OutputFilename, OutputFormat, OutputSparse, NumThreads,
  909. FailureMode);
  910. else
  911. mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
  912. OutputFormat, ProfileSymbolListFile, CompressAllSections,
  913. UseMD5, GenPartialProfile, GenCSNestedProfile,
  914. SampleMergeColdContext, SampleTrimColdContext,
  915. SampleColdContextFrameDepth, FailureMode);
  916. return 0;
  917. }
  918. /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
  919. static void overlapInstrProfile(const std::string &BaseFilename,
  920. const std::string &TestFilename,
  921. const OverlapFuncFilters &FuncFilter,
  922. raw_fd_ostream &OS, bool IsCS) {
  923. std::mutex ErrorLock;
  924. SmallSet<instrprof_error, 4> WriterErrorCodes;
  925. WriterContext Context(false, ErrorLock, WriterErrorCodes);
  926. WeightedFile WeightedInput{BaseFilename, 1};
  927. OverlapStats Overlap;
  928. Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
  929. if (E)
  930. exitWithError(std::move(E), "error in getting profile count sums");
  931. if (Overlap.Base.CountSum < 1.0f) {
  932. OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
  933. exit(0);
  934. }
  935. if (Overlap.Test.CountSum < 1.0f) {
  936. OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
  937. exit(0);
  938. }
  939. loadInput(WeightedInput, nullptr, nullptr, &Context);
  940. overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
  941. IsCS);
  942. Overlap.dump(OS);
  943. }
  944. namespace {
  945. struct SampleOverlapStats {
  946. SampleContext BaseName;
  947. SampleContext TestName;
  948. // Number of overlap units
  949. uint64_t OverlapCount;
  950. // Total samples of overlap units
  951. uint64_t OverlapSample;
  952. // Number of and total samples of units that only present in base or test
  953. // profile
  954. uint64_t BaseUniqueCount;
  955. uint64_t BaseUniqueSample;
  956. uint64_t TestUniqueCount;
  957. uint64_t TestUniqueSample;
  958. // Number of units and total samples in base or test profile
  959. uint64_t BaseCount;
  960. uint64_t BaseSample;
  961. uint64_t TestCount;
  962. uint64_t TestSample;
  963. // Number of and total samples of units that present in at least one profile
  964. uint64_t UnionCount;
  965. uint64_t UnionSample;
  966. // Weighted similarity
  967. double Similarity;
  968. // For SampleOverlapStats instances representing functions, weights of the
  969. // function in base and test profiles
  970. double BaseWeight;
  971. double TestWeight;
  972. SampleOverlapStats()
  973. : OverlapCount(0), OverlapSample(0), BaseUniqueCount(0),
  974. BaseUniqueSample(0), TestUniqueCount(0), TestUniqueSample(0),
  975. BaseCount(0), BaseSample(0), TestCount(0), TestSample(0), UnionCount(0),
  976. UnionSample(0), Similarity(0.0), BaseWeight(0.0), TestWeight(0.0) {}
  977. };
  978. } // end anonymous namespace
  979. namespace {
  980. struct FuncSampleStats {
  981. uint64_t SampleSum;
  982. uint64_t MaxSample;
  983. uint64_t HotBlockCount;
  984. FuncSampleStats() : SampleSum(0), MaxSample(0), HotBlockCount(0) {}
  985. FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
  986. uint64_t HotBlockCount)
  987. : SampleSum(SampleSum), MaxSample(MaxSample),
  988. HotBlockCount(HotBlockCount) {}
  989. };
  990. } // end anonymous namespace
  991. namespace {
  992. enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
  993. // Class for updating merging steps for two sorted maps. The class should be
  994. // instantiated with a map iterator type.
  995. template <class T> class MatchStep {
  996. public:
  997. MatchStep() = delete;
  998. MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
  999. : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
  1000. SecondEnd(SecondEnd), Status(MS_None) {}
  1001. bool areBothFinished() const {
  1002. return (FirstIter == FirstEnd && SecondIter == SecondEnd);
  1003. }
  1004. bool isFirstFinished() const { return FirstIter == FirstEnd; }
  1005. bool isSecondFinished() const { return SecondIter == SecondEnd; }
  1006. /// Advance one step based on the previous match status unless the previous
  1007. /// status is MS_None. Then update Status based on the comparison between two
  1008. /// container iterators at the current step. If the previous status is
  1009. /// MS_None, it means two iterators are at the beginning and no comparison has
  1010. /// been made, so we simply update Status without advancing the iterators.
  1011. void updateOneStep();
  1012. T getFirstIter() const { return FirstIter; }
  1013. T getSecondIter() const { return SecondIter; }
  1014. MatchStatus getMatchStatus() const { return Status; }
  1015. private:
  1016. // Current iterator and end iterator of the first container.
  1017. T FirstIter;
  1018. T FirstEnd;
  1019. // Current iterator and end iterator of the second container.
  1020. T SecondIter;
  1021. T SecondEnd;
  1022. // Match status of the current step.
  1023. MatchStatus Status;
  1024. };
  1025. } // end anonymous namespace
  1026. template <class T> void MatchStep<T>::updateOneStep() {
  1027. switch (Status) {
  1028. case MS_Match:
  1029. ++FirstIter;
  1030. ++SecondIter;
  1031. break;
  1032. case MS_FirstUnique:
  1033. ++FirstIter;
  1034. break;
  1035. case MS_SecondUnique:
  1036. ++SecondIter;
  1037. break;
  1038. case MS_None:
  1039. break;
  1040. }
  1041. // Update Status according to iterators at the current step.
  1042. if (areBothFinished())
  1043. return;
  1044. if (FirstIter != FirstEnd &&
  1045. (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
  1046. Status = MS_FirstUnique;
  1047. else if (SecondIter != SecondEnd &&
  1048. (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
  1049. Status = MS_SecondUnique;
  1050. else
  1051. Status = MS_Match;
  1052. }
  1053. // Return the sum of line/block samples, the max line/block sample, and the
  1054. // number of line/block samples above the given threshold in a function
  1055. // including its inlinees.
  1056. static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
  1057. FuncSampleStats &FuncStats,
  1058. uint64_t HotThreshold) {
  1059. for (const auto &L : Func.getBodySamples()) {
  1060. uint64_t Sample = L.second.getSamples();
  1061. FuncStats.SampleSum += Sample;
  1062. FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
  1063. if (Sample >= HotThreshold)
  1064. ++FuncStats.HotBlockCount;
  1065. }
  1066. for (const auto &C : Func.getCallsiteSamples()) {
  1067. for (const auto &F : C.second)
  1068. getFuncSampleStats(F.second, FuncStats, HotThreshold);
  1069. }
  1070. }
  1071. /// Predicate that determines if a function is hot with a given threshold. We
  1072. /// keep it separate from its callsites for possible extension in the future.
  1073. static bool isFunctionHot(const FuncSampleStats &FuncStats,
  1074. uint64_t HotThreshold) {
  1075. // We intentionally compare the maximum sample count in a function with the
  1076. // HotThreshold to get an approximate determination on hot functions.
  1077. return (FuncStats.MaxSample >= HotThreshold);
  1078. }
  1079. namespace {
  1080. class SampleOverlapAggregator {
  1081. public:
  1082. SampleOverlapAggregator(const std::string &BaseFilename,
  1083. const std::string &TestFilename,
  1084. double LowSimilarityThreshold, double Epsilon,
  1085. const OverlapFuncFilters &FuncFilter)
  1086. : BaseFilename(BaseFilename), TestFilename(TestFilename),
  1087. LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
  1088. FuncFilter(FuncFilter) {}
  1089. /// Detect 0-sample input profile and report to output stream. This interface
  1090. /// should be called after loadProfiles().
  1091. bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
  1092. /// Write out function-level similarity statistics for functions specified by
  1093. /// options --function, --value-cutoff, and --similarity-cutoff.
  1094. void dumpFuncSimilarity(raw_fd_ostream &OS) const;
  1095. /// Write out program-level similarity and overlap statistics.
  1096. void dumpProgramSummary(raw_fd_ostream &OS) const;
  1097. /// Write out hot-function and hot-block statistics for base_profile,
  1098. /// test_profile, and their overlap. For both cases, the overlap HO is
  1099. /// calculated as follows:
  1100. /// Given the number of functions (or blocks) that are hot in both profiles
  1101. /// HCommon and the number of functions (or blocks) that are hot in at
  1102. /// least one profile HUnion, HO = HCommon / HUnion.
  1103. void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
  1104. /// This function tries matching functions in base and test profiles. For each
  1105. /// pair of matched functions, it aggregates the function-level
  1106. /// similarity into a profile-level similarity. It also dump function-level
  1107. /// similarity information of functions specified by --function,
  1108. /// --value-cutoff, and --similarity-cutoff options. The program-level
  1109. /// similarity PS is computed as follows:
  1110. /// Given function-level similarity FS(A) for all function A, the
  1111. /// weight of function A in base profile WB(A), and the weight of function
  1112. /// A in test profile WT(A), compute PS(base_profile, test_profile) =
  1113. /// sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
  1114. /// meaning no-overlap.
  1115. void computeSampleProfileOverlap(raw_fd_ostream &OS);
  1116. /// Initialize ProfOverlap with the sum of samples in base and test
  1117. /// profiles. This function also computes and keeps the sum of samples and
  1118. /// max sample counts of each function in BaseStats and TestStats for later
  1119. /// use to avoid re-computations.
  1120. void initializeSampleProfileOverlap();
  1121. /// Load profiles specified by BaseFilename and TestFilename.
  1122. std::error_code loadProfiles();
  1123. using FuncSampleStatsMap =
  1124. std::unordered_map<SampleContext, FuncSampleStats, SampleContext::Hash>;
  1125. private:
  1126. SampleOverlapStats ProfOverlap;
  1127. SampleOverlapStats HotFuncOverlap;
  1128. SampleOverlapStats HotBlockOverlap;
  1129. std::string BaseFilename;
  1130. std::string TestFilename;
  1131. std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
  1132. std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
  1133. // BaseStats and TestStats hold FuncSampleStats for each function, with
  1134. // function name as the key.
  1135. FuncSampleStatsMap BaseStats;
  1136. FuncSampleStatsMap TestStats;
  1137. // Low similarity threshold in floating point number
  1138. double LowSimilarityThreshold;
  1139. // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
  1140. // for tracking hot blocks.
  1141. uint64_t BaseHotThreshold;
  1142. uint64_t TestHotThreshold;
  1143. // A small threshold used to round the results of floating point accumulations
  1144. // to resolve imprecision.
  1145. const double Epsilon;
  1146. std::multimap<double, SampleOverlapStats, std::greater<double>>
  1147. FuncSimilarityDump;
  1148. // FuncFilter carries specifications in options --value-cutoff and
  1149. // --function.
  1150. OverlapFuncFilters FuncFilter;
  1151. // Column offsets for printing the function-level details table.
  1152. static const unsigned int TestWeightCol = 15;
  1153. static const unsigned int SimilarityCol = 30;
  1154. static const unsigned int OverlapCol = 43;
  1155. static const unsigned int BaseUniqueCol = 53;
  1156. static const unsigned int TestUniqueCol = 67;
  1157. static const unsigned int BaseSampleCol = 81;
  1158. static const unsigned int TestSampleCol = 96;
  1159. static const unsigned int FuncNameCol = 111;
  1160. /// Return a similarity of two line/block sample counters in the same
  1161. /// function in base and test profiles. The line/block-similarity BS(i) is
  1162. /// computed as follows:
  1163. /// For an offsets i, given the sample count at i in base profile BB(i),
  1164. /// the sample count at i in test profile BT(i), the sum of sample counts
  1165. /// in this function in base profile SB, and the sum of sample counts in
  1166. /// this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
  1167. /// BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
  1168. double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
  1169. const SampleOverlapStats &FuncOverlap) const;
  1170. void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
  1171. uint64_t HotBlockCount);
  1172. void getHotFunctions(const FuncSampleStatsMap &ProfStats,
  1173. FuncSampleStatsMap &HotFunc,
  1174. uint64_t HotThreshold) const;
  1175. void computeHotFuncOverlap();
  1176. /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
  1177. /// Difference for two sample units in a matched function according to the
  1178. /// given match status.
  1179. void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
  1180. uint64_t HotBlockCount,
  1181. SampleOverlapStats &FuncOverlap,
  1182. double &Difference, MatchStatus Status);
  1183. /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
  1184. /// Difference for unmatched callees that only present in one profile in a
  1185. /// matched caller function.
  1186. void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
  1187. SampleOverlapStats &FuncOverlap,
  1188. double &Difference, MatchStatus Status);
  1189. /// This function updates sample overlap statistics of an overlap function in
  1190. /// base and test profile. It also calculates a function-internal similarity
  1191. /// FIS as follows:
  1192. /// For offsets i that have samples in at least one profile in this
  1193. /// function A, given BS(i) returned by computeBlockSimilarity(), compute
  1194. /// FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
  1195. /// 0.0 meaning no overlap.
  1196. double computeSampleFunctionInternalOverlap(
  1197. const sampleprof::FunctionSamples &BaseFunc,
  1198. const sampleprof::FunctionSamples &TestFunc,
  1199. SampleOverlapStats &FuncOverlap);
  1200. /// Function-level similarity (FS) is a weighted value over function internal
  1201. /// similarity (FIS). This function computes a function's FS from its FIS by
  1202. /// applying the weight.
  1203. double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
  1204. uint64_t TestFuncSample) const;
  1205. /// The function-level similarity FS(A) for a function A is computed as
  1206. /// follows:
  1207. /// Compute a function-internal similarity FIS(A) by
  1208. /// computeSampleFunctionInternalOverlap(). Then, with the weight of
  1209. /// function A in base profile WB(A), and the weight of function A in test
  1210. /// profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
  1211. /// ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
  1212. double
  1213. computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
  1214. const sampleprof::FunctionSamples *TestFunc,
  1215. SampleOverlapStats *FuncOverlap,
  1216. uint64_t BaseFuncSample,
  1217. uint64_t TestFuncSample);
  1218. /// Profile-level similarity (PS) is a weighted aggregate over function-level
  1219. /// similarities (FS). This method weights the FS value by the function
  1220. /// weights in the base and test profiles for the aggregation.
  1221. double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
  1222. uint64_t TestFuncSample) const;
  1223. };
  1224. } // end anonymous namespace
  1225. bool SampleOverlapAggregator::detectZeroSampleProfile(
  1226. raw_fd_ostream &OS) const {
  1227. bool HaveZeroSample = false;
  1228. if (ProfOverlap.BaseSample == 0) {
  1229. OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
  1230. HaveZeroSample = true;
  1231. }
  1232. if (ProfOverlap.TestSample == 0) {
  1233. OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
  1234. HaveZeroSample = true;
  1235. }
  1236. return HaveZeroSample;
  1237. }
  1238. double SampleOverlapAggregator::computeBlockSimilarity(
  1239. uint64_t BaseSample, uint64_t TestSample,
  1240. const SampleOverlapStats &FuncOverlap) const {
  1241. double BaseFrac = 0.0;
  1242. double TestFrac = 0.0;
  1243. if (FuncOverlap.BaseSample > 0)
  1244. BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
  1245. if (FuncOverlap.TestSample > 0)
  1246. TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
  1247. return 1.0 - std::fabs(BaseFrac - TestFrac);
  1248. }
  1249. void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
  1250. uint64_t TestSample,
  1251. uint64_t HotBlockCount) {
  1252. bool IsBaseHot = (BaseSample >= BaseHotThreshold);
  1253. bool IsTestHot = (TestSample >= TestHotThreshold);
  1254. if (!IsBaseHot && !IsTestHot)
  1255. return;
  1256. HotBlockOverlap.UnionCount += HotBlockCount;
  1257. if (IsBaseHot)
  1258. HotBlockOverlap.BaseCount += HotBlockCount;
  1259. if (IsTestHot)
  1260. HotBlockOverlap.TestCount += HotBlockCount;
  1261. if (IsBaseHot && IsTestHot)
  1262. HotBlockOverlap.OverlapCount += HotBlockCount;
  1263. }
  1264. void SampleOverlapAggregator::getHotFunctions(
  1265. const FuncSampleStatsMap &ProfStats, FuncSampleStatsMap &HotFunc,
  1266. uint64_t HotThreshold) const {
  1267. for (const auto &F : ProfStats) {
  1268. if (isFunctionHot(F.second, HotThreshold))
  1269. HotFunc.emplace(F.first, F.second);
  1270. }
  1271. }
  1272. void SampleOverlapAggregator::computeHotFuncOverlap() {
  1273. FuncSampleStatsMap BaseHotFunc;
  1274. getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
  1275. HotFuncOverlap.BaseCount = BaseHotFunc.size();
  1276. FuncSampleStatsMap TestHotFunc;
  1277. getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
  1278. HotFuncOverlap.TestCount = TestHotFunc.size();
  1279. HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
  1280. for (const auto &F : BaseHotFunc) {
  1281. if (TestHotFunc.count(F.first))
  1282. ++HotFuncOverlap.OverlapCount;
  1283. else
  1284. ++HotFuncOverlap.UnionCount;
  1285. }
  1286. }
  1287. void SampleOverlapAggregator::updateOverlapStatsForFunction(
  1288. uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
  1289. SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
  1290. assert(Status != MS_None &&
  1291. "Match status should be updated before updating overlap statistics");
  1292. if (Status == MS_FirstUnique) {
  1293. TestSample = 0;
  1294. FuncOverlap.BaseUniqueSample += BaseSample;
  1295. } else if (Status == MS_SecondUnique) {
  1296. BaseSample = 0;
  1297. FuncOverlap.TestUniqueSample += TestSample;
  1298. } else {
  1299. ++FuncOverlap.OverlapCount;
  1300. }
  1301. FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
  1302. FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
  1303. Difference +=
  1304. 1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
  1305. updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
  1306. }
  1307. void SampleOverlapAggregator::updateForUnmatchedCallee(
  1308. const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
  1309. double &Difference, MatchStatus Status) {
  1310. assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
  1311. "Status must be either of the two unmatched cases");
  1312. FuncSampleStats FuncStats;
  1313. if (Status == MS_FirstUnique) {
  1314. getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
  1315. updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
  1316. FuncStats.HotBlockCount, FuncOverlap,
  1317. Difference, Status);
  1318. } else {
  1319. getFuncSampleStats(Func, FuncStats, TestHotThreshold);
  1320. updateOverlapStatsForFunction(0, FuncStats.SampleSum,
  1321. FuncStats.HotBlockCount, FuncOverlap,
  1322. Difference, Status);
  1323. }
  1324. }
  1325. double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
  1326. const sampleprof::FunctionSamples &BaseFunc,
  1327. const sampleprof::FunctionSamples &TestFunc,
  1328. SampleOverlapStats &FuncOverlap) {
  1329. using namespace sampleprof;
  1330. double Difference = 0;
  1331. // Accumulate Difference for regular line/block samples in the function.
  1332. // We match them through sort-merge join algorithm because
  1333. // FunctionSamples::getBodySamples() returns a map of sample counters ordered
  1334. // by their offsets.
  1335. MatchStep<BodySampleMap::const_iterator> BlockIterStep(
  1336. BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
  1337. TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
  1338. BlockIterStep.updateOneStep();
  1339. while (!BlockIterStep.areBothFinished()) {
  1340. uint64_t BaseSample =
  1341. BlockIterStep.isFirstFinished()
  1342. ? 0
  1343. : BlockIterStep.getFirstIter()->second.getSamples();
  1344. uint64_t TestSample =
  1345. BlockIterStep.isSecondFinished()
  1346. ? 0
  1347. : BlockIterStep.getSecondIter()->second.getSamples();
  1348. updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
  1349. Difference, BlockIterStep.getMatchStatus());
  1350. BlockIterStep.updateOneStep();
  1351. }
  1352. // Accumulate Difference for callsite lines in the function. We match
  1353. // them through sort-merge algorithm because
  1354. // FunctionSamples::getCallsiteSamples() returns a map of callsite records
  1355. // ordered by their offsets.
  1356. MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
  1357. BaseFunc.getCallsiteSamples().cbegin(),
  1358. BaseFunc.getCallsiteSamples().cend(),
  1359. TestFunc.getCallsiteSamples().cbegin(),
  1360. TestFunc.getCallsiteSamples().cend());
  1361. CallsiteIterStep.updateOneStep();
  1362. while (!CallsiteIterStep.areBothFinished()) {
  1363. MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
  1364. assert(CallsiteStepStatus != MS_None &&
  1365. "Match status should be updated before entering loop body");
  1366. if (CallsiteStepStatus != MS_Match) {
  1367. auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
  1368. ? CallsiteIterStep.getFirstIter()
  1369. : CallsiteIterStep.getSecondIter();
  1370. for (const auto &F : Callsite->second)
  1371. updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
  1372. CallsiteStepStatus);
  1373. } else {
  1374. // There may be multiple inlinees at the same offset, so we need to try
  1375. // matching all of them. This match is implemented through sort-merge
  1376. // algorithm because callsite records at the same offset are ordered by
  1377. // function names.
  1378. MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
  1379. CallsiteIterStep.getFirstIter()->second.cbegin(),
  1380. CallsiteIterStep.getFirstIter()->second.cend(),
  1381. CallsiteIterStep.getSecondIter()->second.cbegin(),
  1382. CallsiteIterStep.getSecondIter()->second.cend());
  1383. CalleeIterStep.updateOneStep();
  1384. while (!CalleeIterStep.areBothFinished()) {
  1385. MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
  1386. if (CalleeStepStatus != MS_Match) {
  1387. auto Callee = (CalleeStepStatus == MS_FirstUnique)
  1388. ? CalleeIterStep.getFirstIter()
  1389. : CalleeIterStep.getSecondIter();
  1390. updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
  1391. CalleeStepStatus);
  1392. } else {
  1393. // An inlined function can contain other inlinees inside, so compute
  1394. // the Difference recursively.
  1395. Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
  1396. CalleeIterStep.getFirstIter()->second,
  1397. CalleeIterStep.getSecondIter()->second,
  1398. FuncOverlap);
  1399. }
  1400. CalleeIterStep.updateOneStep();
  1401. }
  1402. }
  1403. CallsiteIterStep.updateOneStep();
  1404. }
  1405. // Difference reflects the total differences of line/block samples in this
  1406. // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
  1407. // reflect the similarity between function profiles in [0.0f to 1.0f].
  1408. return (2.0 - Difference) / 2;
  1409. }
  1410. double SampleOverlapAggregator::weightForFuncSimilarity(
  1411. double FuncInternalSimilarity, uint64_t BaseFuncSample,
  1412. uint64_t TestFuncSample) const {
  1413. // Compute the weight as the distance between the function weights in two
  1414. // profiles.
  1415. double BaseFrac = 0.0;
  1416. double TestFrac = 0.0;
  1417. assert(ProfOverlap.BaseSample > 0 &&
  1418. "Total samples in base profile should be greater than 0");
  1419. BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
  1420. assert(ProfOverlap.TestSample > 0 &&
  1421. "Total samples in test profile should be greater than 0");
  1422. TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
  1423. double WeightDistance = std::fabs(BaseFrac - TestFrac);
  1424. // Take WeightDistance into the similarity.
  1425. return FuncInternalSimilarity * (1 - WeightDistance);
  1426. }
  1427. double
  1428. SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
  1429. uint64_t BaseFuncSample,
  1430. uint64_t TestFuncSample) const {
  1431. double BaseFrac = 0.0;
  1432. double TestFrac = 0.0;
  1433. assert(ProfOverlap.BaseSample > 0 &&
  1434. "Total samples in base profile should be greater than 0");
  1435. BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
  1436. assert(ProfOverlap.TestSample > 0 &&
  1437. "Total samples in test profile should be greater than 0");
  1438. TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
  1439. return FuncSimilarity * (BaseFrac + TestFrac);
  1440. }
  1441. double SampleOverlapAggregator::computeSampleFunctionOverlap(
  1442. const sampleprof::FunctionSamples *BaseFunc,
  1443. const sampleprof::FunctionSamples *TestFunc,
  1444. SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
  1445. uint64_t TestFuncSample) {
  1446. // Default function internal similarity before weighted, meaning two functions
  1447. // has no overlap.
  1448. const double DefaultFuncInternalSimilarity = 0;
  1449. double FuncSimilarity;
  1450. double FuncInternalSimilarity;
  1451. // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
  1452. // In this case, we use DefaultFuncInternalSimilarity as the function internal
  1453. // similarity.
  1454. if (!BaseFunc || !TestFunc) {
  1455. FuncInternalSimilarity = DefaultFuncInternalSimilarity;
  1456. } else {
  1457. assert(FuncOverlap != nullptr &&
  1458. "FuncOverlap should be provided in this case");
  1459. FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
  1460. *BaseFunc, *TestFunc, *FuncOverlap);
  1461. // Now, FuncInternalSimilarity may be a little less than 0 due to
  1462. // imprecision of floating point accumulations. Make it zero if the
  1463. // difference is below Epsilon.
  1464. FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
  1465. ? 0
  1466. : FuncInternalSimilarity;
  1467. }
  1468. FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
  1469. BaseFuncSample, TestFuncSample);
  1470. return FuncSimilarity;
  1471. }
  1472. void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
  1473. using namespace sampleprof;
  1474. std::unordered_map<SampleContext, const FunctionSamples *,
  1475. SampleContext::Hash>
  1476. BaseFuncProf;
  1477. const auto &BaseProfiles = BaseReader->getProfiles();
  1478. for (const auto &BaseFunc : BaseProfiles) {
  1479. BaseFuncProf.emplace(BaseFunc.second.getContext(), &(BaseFunc.second));
  1480. }
  1481. ProfOverlap.UnionCount = BaseFuncProf.size();
  1482. const auto &TestProfiles = TestReader->getProfiles();
  1483. for (const auto &TestFunc : TestProfiles) {
  1484. SampleOverlapStats FuncOverlap;
  1485. FuncOverlap.TestName = TestFunc.second.getContext();
  1486. assert(TestStats.count(FuncOverlap.TestName) &&
  1487. "TestStats should have records for all functions in test profile "
  1488. "except inlinees");
  1489. FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
  1490. bool Matched = false;
  1491. const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
  1492. if (Match == BaseFuncProf.end()) {
  1493. const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
  1494. ++ProfOverlap.TestUniqueCount;
  1495. ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
  1496. FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
  1497. updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
  1498. double FuncSimilarity = computeSampleFunctionOverlap(
  1499. nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
  1500. ProfOverlap.Similarity +=
  1501. weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
  1502. ++ProfOverlap.UnionCount;
  1503. ProfOverlap.UnionSample += FuncStats.SampleSum;
  1504. } else {
  1505. ++ProfOverlap.OverlapCount;
  1506. // Two functions match with each other. Compute function-level overlap and
  1507. // aggregate them into profile-level overlap.
  1508. FuncOverlap.BaseName = Match->second->getContext();
  1509. assert(BaseStats.count(FuncOverlap.BaseName) &&
  1510. "BaseStats should have records for all functions in base profile "
  1511. "except inlinees");
  1512. FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
  1513. FuncOverlap.Similarity = computeSampleFunctionOverlap(
  1514. Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
  1515. FuncOverlap.TestSample);
  1516. ProfOverlap.Similarity +=
  1517. weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
  1518. FuncOverlap.TestSample);
  1519. ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
  1520. ProfOverlap.UnionSample += FuncOverlap.UnionSample;
  1521. // Accumulate the percentage of base unique and test unique samples into
  1522. // ProfOverlap.
  1523. ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
  1524. ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
  1525. // Remove matched base functions for later reporting functions not found
  1526. // in test profile.
  1527. BaseFuncProf.erase(Match);
  1528. Matched = true;
  1529. }
  1530. // Print function-level similarity information if specified by options.
  1531. assert(TestStats.count(FuncOverlap.TestName) &&
  1532. "TestStats should have records for all functions in test profile "
  1533. "except inlinees");
  1534. if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
  1535. (Matched && FuncOverlap.Similarity < LowSimilarityThreshold) ||
  1536. (Matched && !FuncFilter.NameFilter.empty() &&
  1537. FuncOverlap.BaseName.toString().find(FuncFilter.NameFilter) !=
  1538. std::string::npos)) {
  1539. assert(ProfOverlap.BaseSample > 0 &&
  1540. "Total samples in base profile should be greater than 0");
  1541. FuncOverlap.BaseWeight =
  1542. static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
  1543. assert(ProfOverlap.TestSample > 0 &&
  1544. "Total samples in test profile should be greater than 0");
  1545. FuncOverlap.TestWeight =
  1546. static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
  1547. FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
  1548. }
  1549. }
  1550. // Traverse through functions in base profile but not in test profile.
  1551. for (const auto &F : BaseFuncProf) {
  1552. assert(BaseStats.count(F.second->getContext()) &&
  1553. "BaseStats should have records for all functions in base profile "
  1554. "except inlinees");
  1555. const FuncSampleStats &FuncStats = BaseStats[F.second->getContext()];
  1556. ++ProfOverlap.BaseUniqueCount;
  1557. ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
  1558. updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
  1559. double FuncSimilarity = computeSampleFunctionOverlap(
  1560. nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
  1561. ProfOverlap.Similarity +=
  1562. weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
  1563. ProfOverlap.UnionSample += FuncStats.SampleSum;
  1564. }
  1565. // Now, ProfSimilarity may be a little greater than 1 due to imprecision
  1566. // of floating point accumulations. Make it 1.0 if the difference is below
  1567. // Epsilon.
  1568. ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
  1569. ? 1
  1570. : ProfOverlap.Similarity;
  1571. computeHotFuncOverlap();
  1572. }
  1573. void SampleOverlapAggregator::initializeSampleProfileOverlap() {
  1574. const auto &BaseProf = BaseReader->getProfiles();
  1575. for (const auto &I : BaseProf) {
  1576. ++ProfOverlap.BaseCount;
  1577. FuncSampleStats FuncStats;
  1578. getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
  1579. ProfOverlap.BaseSample += FuncStats.SampleSum;
  1580. BaseStats.emplace(I.second.getContext(), FuncStats);
  1581. }
  1582. const auto &TestProf = TestReader->getProfiles();
  1583. for (const auto &I : TestProf) {
  1584. ++ProfOverlap.TestCount;
  1585. FuncSampleStats FuncStats;
  1586. getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
  1587. ProfOverlap.TestSample += FuncStats.SampleSum;
  1588. TestStats.emplace(I.second.getContext(), FuncStats);
  1589. }
  1590. ProfOverlap.BaseName = StringRef(BaseFilename);
  1591. ProfOverlap.TestName = StringRef(TestFilename);
  1592. }
  1593. void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
  1594. using namespace sampleprof;
  1595. if (FuncSimilarityDump.empty())
  1596. return;
  1597. formatted_raw_ostream FOS(OS);
  1598. FOS << "Function-level details:\n";
  1599. FOS << "Base weight";
  1600. FOS.PadToColumn(TestWeightCol);
  1601. FOS << "Test weight";
  1602. FOS.PadToColumn(SimilarityCol);
  1603. FOS << "Similarity";
  1604. FOS.PadToColumn(OverlapCol);
  1605. FOS << "Overlap";
  1606. FOS.PadToColumn(BaseUniqueCol);
  1607. FOS << "Base unique";
  1608. FOS.PadToColumn(TestUniqueCol);
  1609. FOS << "Test unique";
  1610. FOS.PadToColumn(BaseSampleCol);
  1611. FOS << "Base samples";
  1612. FOS.PadToColumn(TestSampleCol);
  1613. FOS << "Test samples";
  1614. FOS.PadToColumn(FuncNameCol);
  1615. FOS << "Function name\n";
  1616. for (const auto &F : FuncSimilarityDump) {
  1617. double OverlapPercent =
  1618. F.second.UnionSample > 0
  1619. ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
  1620. : 0;
  1621. double BaseUniquePercent =
  1622. F.second.BaseSample > 0
  1623. ? static_cast<double>(F.second.BaseUniqueSample) /
  1624. F.second.BaseSample
  1625. : 0;
  1626. double TestUniquePercent =
  1627. F.second.TestSample > 0
  1628. ? static_cast<double>(F.second.TestUniqueSample) /
  1629. F.second.TestSample
  1630. : 0;
  1631. FOS << format("%.2f%%", F.second.BaseWeight * 100);
  1632. FOS.PadToColumn(TestWeightCol);
  1633. FOS << format("%.2f%%", F.second.TestWeight * 100);
  1634. FOS.PadToColumn(SimilarityCol);
  1635. FOS << format("%.2f%%", F.second.Similarity * 100);
  1636. FOS.PadToColumn(OverlapCol);
  1637. FOS << format("%.2f%%", OverlapPercent * 100);
  1638. FOS.PadToColumn(BaseUniqueCol);
  1639. FOS << format("%.2f%%", BaseUniquePercent * 100);
  1640. FOS.PadToColumn(TestUniqueCol);
  1641. FOS << format("%.2f%%", TestUniquePercent * 100);
  1642. FOS.PadToColumn(BaseSampleCol);
  1643. FOS << F.second.BaseSample;
  1644. FOS.PadToColumn(TestSampleCol);
  1645. FOS << F.second.TestSample;
  1646. FOS.PadToColumn(FuncNameCol);
  1647. FOS << F.second.TestName.toString() << "\n";
  1648. }
  1649. }
  1650. void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
  1651. OS << "Profile overlap infomation for base_profile: "
  1652. << ProfOverlap.BaseName.toString()
  1653. << " and test_profile: " << ProfOverlap.TestName.toString()
  1654. << "\nProgram level:\n";
  1655. OS << " Whole program profile similarity: "
  1656. << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
  1657. assert(ProfOverlap.UnionSample > 0 &&
  1658. "Total samples in two profile should be greater than 0");
  1659. double OverlapPercent =
  1660. static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
  1661. assert(ProfOverlap.BaseSample > 0 &&
  1662. "Total samples in base profile should be greater than 0");
  1663. double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
  1664. ProfOverlap.BaseSample;
  1665. assert(ProfOverlap.TestSample > 0 &&
  1666. "Total samples in test profile should be greater than 0");
  1667. double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
  1668. ProfOverlap.TestSample;
  1669. OS << " Whole program sample overlap: "
  1670. << format("%.3f%%", OverlapPercent * 100) << "\n";
  1671. OS << " percentage of samples unique in base profile: "
  1672. << format("%.3f%%", BaseUniquePercent * 100) << "\n";
  1673. OS << " percentage of samples unique in test profile: "
  1674. << format("%.3f%%", TestUniquePercent * 100) << "\n";
  1675. OS << " total samples in base profile: " << ProfOverlap.BaseSample << "\n"
  1676. << " total samples in test profile: " << ProfOverlap.TestSample << "\n";
  1677. assert(ProfOverlap.UnionCount > 0 &&
  1678. "There should be at least one function in two input profiles");
  1679. double FuncOverlapPercent =
  1680. static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
  1681. OS << " Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
  1682. << "\n";
  1683. OS << " overlap functions: " << ProfOverlap.OverlapCount << "\n";
  1684. OS << " functions unique in base profile: " << ProfOverlap.BaseUniqueCount
  1685. << "\n";
  1686. OS << " functions unique in test profile: " << ProfOverlap.TestUniqueCount
  1687. << "\n";
  1688. }
  1689. void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
  1690. raw_fd_ostream &OS) const {
  1691. assert(HotFuncOverlap.UnionCount > 0 &&
  1692. "There should be at least one hot function in two input profiles");
  1693. OS << " Hot-function overlap: "
  1694. << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
  1695. HotFuncOverlap.UnionCount * 100)
  1696. << "\n";
  1697. OS << " overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
  1698. OS << " hot functions unique in base profile: "
  1699. << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
  1700. OS << " hot functions unique in test profile: "
  1701. << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
  1702. assert(HotBlockOverlap.UnionCount > 0 &&
  1703. "There should be at least one hot block in two input profiles");
  1704. OS << " Hot-block overlap: "
  1705. << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
  1706. HotBlockOverlap.UnionCount * 100)
  1707. << "\n";
  1708. OS << " overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
  1709. OS << " hot blocks unique in base profile: "
  1710. << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
  1711. OS << " hot blocks unique in test profile: "
  1712. << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
  1713. }
  1714. std::error_code SampleOverlapAggregator::loadProfiles() {
  1715. using namespace sampleprof;
  1716. LLVMContext Context;
  1717. auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context,
  1718. FSDiscriminatorPassOption);
  1719. if (std::error_code EC = BaseReaderOrErr.getError())
  1720. exitWithErrorCode(EC, BaseFilename);
  1721. auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context,
  1722. FSDiscriminatorPassOption);
  1723. if (std::error_code EC = TestReaderOrErr.getError())
  1724. exitWithErrorCode(EC, TestFilename);
  1725. BaseReader = std::move(BaseReaderOrErr.get());
  1726. TestReader = std::move(TestReaderOrErr.get());
  1727. if (std::error_code EC = BaseReader->read())
  1728. exitWithErrorCode(EC, BaseFilename);
  1729. if (std::error_code EC = TestReader->read())
  1730. exitWithErrorCode(EC, TestFilename);
  1731. if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
  1732. exitWithError(
  1733. "cannot compare probe-based profile with non-probe-based profile");
  1734. if (BaseReader->profileIsCSFlat() != TestReader->profileIsCSFlat())
  1735. exitWithError("cannot compare CS profile with non-CS profile");
  1736. // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
  1737. // profile summary.
  1738. ProfileSummary &BasePS = BaseReader->getSummary();
  1739. ProfileSummary &TestPS = TestReader->getSummary();
  1740. BaseHotThreshold =
  1741. ProfileSummaryBuilder::getHotCountThreshold(BasePS.getDetailedSummary());
  1742. TestHotThreshold =
  1743. ProfileSummaryBuilder::getHotCountThreshold(TestPS.getDetailedSummary());
  1744. return std::error_code();
  1745. }
  1746. void overlapSampleProfile(const std::string &BaseFilename,
  1747. const std::string &TestFilename,
  1748. const OverlapFuncFilters &FuncFilter,
  1749. uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
  1750. using namespace sampleprof;
  1751. // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
  1752. // report 2--3 places after decimal point in percentage numbers.
  1753. SampleOverlapAggregator OverlapAggr(
  1754. BaseFilename, TestFilename,
  1755. static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
  1756. if (std::error_code EC = OverlapAggr.loadProfiles())
  1757. exitWithErrorCode(EC);
  1758. OverlapAggr.initializeSampleProfileOverlap();
  1759. if (OverlapAggr.detectZeroSampleProfile(OS))
  1760. return;
  1761. OverlapAggr.computeSampleProfileOverlap(OS);
  1762. OverlapAggr.dumpProgramSummary(OS);
  1763. OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
  1764. OverlapAggr.dumpFuncSimilarity(OS);
  1765. }
  1766. static int overlap_main(int argc, const char *argv[]) {
  1767. cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
  1768. cl::desc("<base profile file>"));
  1769. cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
  1770. cl::desc("<test profile file>"));
  1771. cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
  1772. cl::desc("Output file"));
  1773. cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
  1774. cl::opt<bool> IsCS(
  1775. "cs", cl::init(false),
  1776. cl::desc("For context sensitive PGO counts. Does not work with CSSPGO."));
  1777. cl::opt<unsigned long long> ValueCutoff(
  1778. "value-cutoff", cl::init(-1),
  1779. cl::desc(
  1780. "Function level overlap information for every function (with calling "
  1781. "context for csspgo) in test "
  1782. "profile with max count value greater then the parameter value"));
  1783. cl::opt<std::string> FuncNameFilter(
  1784. "function",
  1785. cl::desc("Function level overlap information for matching functions. For "
  1786. "CSSPGO this takes a a function name with calling context"));
  1787. cl::opt<unsigned long long> SimilarityCutoff(
  1788. "similarity-cutoff", cl::init(0),
  1789. cl::desc("For sample profiles, list function names (with calling context "
  1790. "for csspgo) for overlapped functions "
  1791. "with similarities below the cutoff (percentage times 10000)."));
  1792. cl::opt<ProfileKinds> ProfileKind(
  1793. cl::desc("Profile kind:"), cl::init(instr),
  1794. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  1795. clEnumVal(sample, "Sample profile")));
  1796. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
  1797. std::error_code EC;
  1798. raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_TextWithCRLF);
  1799. if (EC)
  1800. exitWithErrorCode(EC, Output);
  1801. if (ProfileKind == instr)
  1802. overlapInstrProfile(BaseFilename, TestFilename,
  1803. OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
  1804. IsCS);
  1805. else
  1806. overlapSampleProfile(BaseFilename, TestFilename,
  1807. OverlapFuncFilters{ValueCutoff, FuncNameFilter},
  1808. SimilarityCutoff, OS);
  1809. return 0;
  1810. }
  1811. namespace {
  1812. struct ValueSitesStats {
  1813. ValueSitesStats()
  1814. : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
  1815. TotalNumValues(0) {}
  1816. uint64_t TotalNumValueSites;
  1817. uint64_t TotalNumValueSitesWithValueProfile;
  1818. uint64_t TotalNumValues;
  1819. std::vector<unsigned> ValueSitesHistogram;
  1820. };
  1821. } // namespace
  1822. static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
  1823. ValueSitesStats &Stats, raw_fd_ostream &OS,
  1824. InstrProfSymtab *Symtab) {
  1825. uint32_t NS = Func.getNumValueSites(VK);
  1826. Stats.TotalNumValueSites += NS;
  1827. for (size_t I = 0; I < NS; ++I) {
  1828. uint32_t NV = Func.getNumValueDataForSite(VK, I);
  1829. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
  1830. Stats.TotalNumValues += NV;
  1831. if (NV) {
  1832. Stats.TotalNumValueSitesWithValueProfile++;
  1833. if (NV > Stats.ValueSitesHistogram.size())
  1834. Stats.ValueSitesHistogram.resize(NV, 0);
  1835. Stats.ValueSitesHistogram[NV - 1]++;
  1836. }
  1837. uint64_t SiteSum = 0;
  1838. for (uint32_t V = 0; V < NV; V++)
  1839. SiteSum += VD[V].Count;
  1840. if (SiteSum == 0)
  1841. SiteSum = 1;
  1842. for (uint32_t V = 0; V < NV; V++) {
  1843. OS << "\t[ " << format("%2u", I) << ", ";
  1844. if (Symtab == nullptr)
  1845. OS << format("%4" PRIu64, VD[V].Value);
  1846. else
  1847. OS << Symtab->getFuncName(VD[V].Value);
  1848. OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
  1849. << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
  1850. }
  1851. }
  1852. }
  1853. static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
  1854. ValueSitesStats &Stats) {
  1855. OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
  1856. OS << " Total number of sites with values: "
  1857. << Stats.TotalNumValueSitesWithValueProfile << "\n";
  1858. OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
  1859. OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
  1860. for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
  1861. if (Stats.ValueSitesHistogram[I] > 0)
  1862. OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
  1863. }
  1864. }
  1865. static int showInstrProfile(const std::string &Filename, bool ShowCounts,
  1866. uint32_t TopN, bool ShowIndirectCallTargets,
  1867. bool ShowMemOPSizes, bool ShowDetailedSummary,
  1868. std::vector<uint32_t> DetailedSummaryCutoffs,
  1869. bool ShowAllFunctions, bool ShowCS,
  1870. uint64_t ValueCutoff, bool OnlyListBelow,
  1871. const std::string &ShowFunction, bool TextFormat,
  1872. bool ShowBinaryIds, bool ShowCovered,
  1873. raw_fd_ostream &OS) {
  1874. auto ReaderOrErr = InstrProfReader::create(Filename);
  1875. std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
  1876. if (ShowDetailedSummary && Cutoffs.empty()) {
  1877. Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
  1878. }
  1879. InstrProfSummaryBuilder Builder(std::move(Cutoffs));
  1880. if (Error E = ReaderOrErr.takeError())
  1881. exitWithError(std::move(E), Filename);
  1882. auto Reader = std::move(ReaderOrErr.get());
  1883. bool IsIRInstr = Reader->isIRLevelProfile();
  1884. size_t ShownFunctions = 0;
  1885. size_t BelowCutoffFunctions = 0;
  1886. int NumVPKind = IPVK_Last - IPVK_First + 1;
  1887. std::vector<ValueSitesStats> VPStats(NumVPKind);
  1888. auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
  1889. const std::pair<std::string, uint64_t> &v2) {
  1890. return v1.second > v2.second;
  1891. };
  1892. std::priority_queue<std::pair<std::string, uint64_t>,
  1893. std::vector<std::pair<std::string, uint64_t>>,
  1894. decltype(MinCmp)>
  1895. HottestFuncs(MinCmp);
  1896. if (!TextFormat && OnlyListBelow) {
  1897. OS << "The list of functions with the maximum counter less than "
  1898. << ValueCutoff << ":\n";
  1899. }
  1900. // Add marker so that IR-level instrumentation round-trips properly.
  1901. if (TextFormat && IsIRInstr)
  1902. OS << ":ir\n";
  1903. for (const auto &Func : *Reader) {
  1904. if (Reader->isIRLevelProfile()) {
  1905. bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
  1906. if (FuncIsCS != ShowCS)
  1907. continue;
  1908. }
  1909. bool Show = ShowAllFunctions ||
  1910. (!ShowFunction.empty() && Func.Name.contains(ShowFunction));
  1911. bool doTextFormatDump = (Show && TextFormat);
  1912. if (doTextFormatDump) {
  1913. InstrProfSymtab &Symtab = Reader->getSymtab();
  1914. InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
  1915. OS);
  1916. continue;
  1917. }
  1918. assert(Func.Counts.size() > 0 && "function missing entry counter");
  1919. Builder.addRecord(Func);
  1920. if (ShowCovered) {
  1921. if (std::any_of(Func.Counts.begin(), Func.Counts.end(),
  1922. [](uint64_t C) { return C; }))
  1923. OS << Func.Name << "\n";
  1924. continue;
  1925. }
  1926. uint64_t FuncMax = 0;
  1927. uint64_t FuncSum = 0;
  1928. for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
  1929. if (Func.Counts[I] == (uint64_t)-1)
  1930. continue;
  1931. FuncMax = std::max(FuncMax, Func.Counts[I]);
  1932. FuncSum += Func.Counts[I];
  1933. }
  1934. if (FuncMax < ValueCutoff) {
  1935. ++BelowCutoffFunctions;
  1936. if (OnlyListBelow) {
  1937. OS << " " << Func.Name << ": (Max = " << FuncMax
  1938. << " Sum = " << FuncSum << ")\n";
  1939. }
  1940. continue;
  1941. } else if (OnlyListBelow)
  1942. continue;
  1943. if (TopN) {
  1944. if (HottestFuncs.size() == TopN) {
  1945. if (HottestFuncs.top().second < FuncMax) {
  1946. HottestFuncs.pop();
  1947. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  1948. }
  1949. } else
  1950. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  1951. }
  1952. if (Show) {
  1953. if (!ShownFunctions)
  1954. OS << "Counters:\n";
  1955. ++ShownFunctions;
  1956. OS << " " << Func.Name << ":\n"
  1957. << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
  1958. << " Counters: " << Func.Counts.size() << "\n";
  1959. if (!IsIRInstr)
  1960. OS << " Function count: " << Func.Counts[0] << "\n";
  1961. if (ShowIndirectCallTargets)
  1962. OS << " Indirect Call Site Count: "
  1963. << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
  1964. uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
  1965. if (ShowMemOPSizes && NumMemOPCalls > 0)
  1966. OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
  1967. << "\n";
  1968. if (ShowCounts) {
  1969. OS << " Block counts: [";
  1970. size_t Start = (IsIRInstr ? 0 : 1);
  1971. for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
  1972. OS << (I == Start ? "" : ", ") << Func.Counts[I];
  1973. }
  1974. OS << "]\n";
  1975. }
  1976. if (ShowIndirectCallTargets) {
  1977. OS << " Indirect Target Results:\n";
  1978. traverseAllValueSites(Func, IPVK_IndirectCallTarget,
  1979. VPStats[IPVK_IndirectCallTarget], OS,
  1980. &(Reader->getSymtab()));
  1981. }
  1982. if (ShowMemOPSizes && NumMemOPCalls > 0) {
  1983. OS << " Memory Intrinsic Size Results:\n";
  1984. traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
  1985. nullptr);
  1986. }
  1987. }
  1988. }
  1989. if (Reader->hasError())
  1990. exitWithError(Reader->getError(), Filename);
  1991. if (TextFormat || ShowCovered)
  1992. return 0;
  1993. std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
  1994. bool IsIR = Reader->isIRLevelProfile();
  1995. OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
  1996. if (IsIR)
  1997. OS << " entry_first = " << Reader->instrEntryBBEnabled();
  1998. OS << "\n";
  1999. if (ShowAllFunctions || !ShowFunction.empty())
  2000. OS << "Functions shown: " << ShownFunctions << "\n";
  2001. OS << "Total functions: " << PS->getNumFunctions() << "\n";
  2002. if (ValueCutoff > 0) {
  2003. OS << "Number of functions with maximum count (< " << ValueCutoff
  2004. << "): " << BelowCutoffFunctions << "\n";
  2005. OS << "Number of functions with maximum count (>= " << ValueCutoff
  2006. << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
  2007. }
  2008. OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
  2009. OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
  2010. if (TopN) {
  2011. std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
  2012. while (!HottestFuncs.empty()) {
  2013. SortedHottestFuncs.emplace_back(HottestFuncs.top());
  2014. HottestFuncs.pop();
  2015. }
  2016. OS << "Top " << TopN
  2017. << " functions with the largest internal block counts: \n";
  2018. for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
  2019. OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
  2020. }
  2021. if (ShownFunctions && ShowIndirectCallTargets) {
  2022. OS << "Statistics for indirect call sites profile:\n";
  2023. showValueSitesStats(OS, IPVK_IndirectCallTarget,
  2024. VPStats[IPVK_IndirectCallTarget]);
  2025. }
  2026. if (ShownFunctions && ShowMemOPSizes) {
  2027. OS << "Statistics for memory intrinsic calls sizes profile:\n";
  2028. showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
  2029. }
  2030. if (ShowDetailedSummary) {
  2031. OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
  2032. OS << "Total count: " << PS->getTotalCount() << "\n";
  2033. PS->printDetailedSummary(OS);
  2034. }
  2035. if (ShowBinaryIds)
  2036. if (Error E = Reader->printBinaryIds(OS))
  2037. exitWithError(std::move(E), Filename);
  2038. return 0;
  2039. }
  2040. static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
  2041. raw_fd_ostream &OS) {
  2042. if (!Reader->dumpSectionInfo(OS)) {
  2043. WithColor::warning() << "-show-sec-info-only is only supported for "
  2044. << "sample profile in extbinary format and is "
  2045. << "ignored for other formats.\n";
  2046. return;
  2047. }
  2048. }
  2049. namespace {
  2050. struct HotFuncInfo {
  2051. std::string FuncName;
  2052. uint64_t TotalCount;
  2053. double TotalCountPercent;
  2054. uint64_t MaxCount;
  2055. uint64_t EntryCount;
  2056. HotFuncInfo()
  2057. : TotalCount(0), TotalCountPercent(0.0f), MaxCount(0), EntryCount(0) {}
  2058. HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
  2059. : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP),
  2060. MaxCount(MS), EntryCount(ES) {}
  2061. };
  2062. } // namespace
  2063. // Print out detailed information about hot functions in PrintValues vector.
  2064. // Users specify titles and offset of every columns through ColumnTitle and
  2065. // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
  2066. // and at least 4. Besides, users can optionally give a HotFuncMetric string to
  2067. // print out or let it be an empty string.
  2068. static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
  2069. const std::vector<int> &ColumnOffset,
  2070. const std::vector<HotFuncInfo> &PrintValues,
  2071. uint64_t HotFuncCount, uint64_t TotalFuncCount,
  2072. uint64_t HotProfCount, uint64_t TotalProfCount,
  2073. const std::string &HotFuncMetric,
  2074. uint32_t TopNFunctions, raw_fd_ostream &OS) {
  2075. assert(ColumnOffset.size() == ColumnTitle.size() &&
  2076. "ColumnOffset and ColumnTitle should have the same size");
  2077. assert(ColumnTitle.size() >= 4 &&
  2078. "ColumnTitle should have at least 4 elements");
  2079. assert(TotalFuncCount > 0 &&
  2080. "There should be at least one function in the profile");
  2081. double TotalProfPercent = 0;
  2082. if (TotalProfCount > 0)
  2083. TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
  2084. formatted_raw_ostream FOS(OS);
  2085. FOS << HotFuncCount << " out of " << TotalFuncCount
  2086. << " functions with profile ("
  2087. << format("%.2f%%",
  2088. (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
  2089. << ") are considered hot functions";
  2090. if (!HotFuncMetric.empty())
  2091. FOS << " (" << HotFuncMetric << ")";
  2092. FOS << ".\n";
  2093. FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
  2094. << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
  2095. for (size_t I = 0; I < ColumnTitle.size(); ++I) {
  2096. FOS.PadToColumn(ColumnOffset[I]);
  2097. FOS << ColumnTitle[I];
  2098. }
  2099. FOS << "\n";
  2100. uint32_t Count = 0;
  2101. for (const auto &R : PrintValues) {
  2102. if (TopNFunctions && (Count++ == TopNFunctions))
  2103. break;
  2104. FOS.PadToColumn(ColumnOffset[0]);
  2105. FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
  2106. FOS.PadToColumn(ColumnOffset[1]);
  2107. FOS << R.MaxCount;
  2108. FOS.PadToColumn(ColumnOffset[2]);
  2109. FOS << R.EntryCount;
  2110. FOS.PadToColumn(ColumnOffset[3]);
  2111. FOS << R.FuncName << "\n";
  2112. }
  2113. }
  2114. static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles,
  2115. ProfileSummary &PS, uint32_t TopN,
  2116. raw_fd_ostream &OS) {
  2117. using namespace sampleprof;
  2118. const uint32_t HotFuncCutoff = 990000;
  2119. auto &SummaryVector = PS.getDetailedSummary();
  2120. uint64_t MinCountThreshold = 0;
  2121. for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
  2122. if (SummaryEntry.Cutoff == HotFuncCutoff) {
  2123. MinCountThreshold = SummaryEntry.MinCount;
  2124. break;
  2125. }
  2126. }
  2127. // Traverse all functions in the profile and keep only hot functions.
  2128. // The following loop also calculates the sum of total samples of all
  2129. // functions.
  2130. std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
  2131. std::greater<uint64_t>>
  2132. HotFunc;
  2133. uint64_t ProfileTotalSample = 0;
  2134. uint64_t HotFuncSample = 0;
  2135. uint64_t HotFuncCount = 0;
  2136. for (const auto &I : Profiles) {
  2137. FuncSampleStats FuncStats;
  2138. const FunctionSamples &FuncProf = I.second;
  2139. ProfileTotalSample += FuncProf.getTotalSamples();
  2140. getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
  2141. if (isFunctionHot(FuncStats, MinCountThreshold)) {
  2142. HotFunc.emplace(FuncProf.getTotalSamples(),
  2143. std::make_pair(&(I.second), FuncStats.MaxSample));
  2144. HotFuncSample += FuncProf.getTotalSamples();
  2145. ++HotFuncCount;
  2146. }
  2147. }
  2148. std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
  2149. "Entry sample", "Function name"};
  2150. std::vector<int> ColumnOffset{0, 24, 42, 58};
  2151. std::string Metric =
  2152. std::string("max sample >= ") + std::to_string(MinCountThreshold);
  2153. std::vector<HotFuncInfo> PrintValues;
  2154. for (const auto &FuncPair : HotFunc) {
  2155. const FunctionSamples &Func = *FuncPair.second.first;
  2156. double TotalSamplePercent =
  2157. (ProfileTotalSample > 0)
  2158. ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
  2159. : 0;
  2160. PrintValues.emplace_back(HotFuncInfo(
  2161. Func.getContext().toString(), Func.getTotalSamples(),
  2162. TotalSamplePercent, FuncPair.second.second, Func.getEntrySamples()));
  2163. }
  2164. dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
  2165. Profiles.size(), HotFuncSample, ProfileTotalSample,
  2166. Metric, TopN, OS);
  2167. return 0;
  2168. }
  2169. static int showSampleProfile(const std::string &Filename, bool ShowCounts,
  2170. uint32_t TopN, bool ShowAllFunctions,
  2171. bool ShowDetailedSummary,
  2172. const std::string &ShowFunction,
  2173. bool ShowProfileSymbolList,
  2174. bool ShowSectionInfoOnly, bool ShowHotFuncList,
  2175. raw_fd_ostream &OS) {
  2176. using namespace sampleprof;
  2177. LLVMContext Context;
  2178. auto ReaderOrErr =
  2179. SampleProfileReader::create(Filename, Context, FSDiscriminatorPassOption);
  2180. if (std::error_code EC = ReaderOrErr.getError())
  2181. exitWithErrorCode(EC, Filename);
  2182. auto Reader = std::move(ReaderOrErr.get());
  2183. if (ShowSectionInfoOnly) {
  2184. showSectionInfo(Reader.get(), OS);
  2185. return 0;
  2186. }
  2187. if (std::error_code EC = Reader->read())
  2188. exitWithErrorCode(EC, Filename);
  2189. if (ShowAllFunctions || ShowFunction.empty())
  2190. Reader->dump(OS);
  2191. else
  2192. // TODO: parse context string to support filtering by contexts.
  2193. Reader->dumpFunctionProfile(StringRef(ShowFunction), OS);
  2194. if (ShowProfileSymbolList) {
  2195. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  2196. Reader->getProfileSymbolList();
  2197. ReaderList->dump(OS);
  2198. }
  2199. if (ShowDetailedSummary) {
  2200. auto &PS = Reader->getSummary();
  2201. PS.printSummary(OS);
  2202. PS.printDetailedSummary(OS);
  2203. }
  2204. if (ShowHotFuncList || TopN)
  2205. showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), TopN, OS);
  2206. return 0;
  2207. }
  2208. static int showMemProfProfile(const std::string &Filename, raw_fd_ostream &OS) {
  2209. auto ReaderOr = llvm::memprof::RawMemProfReader::create(Filename);
  2210. if (Error E = ReaderOr.takeError())
  2211. exitWithError(std::move(E), Filename);
  2212. std::unique_ptr<llvm::memprof::RawMemProfReader> Reader(
  2213. ReaderOr.get().release());
  2214. Reader->printSummaries(OS);
  2215. return 0;
  2216. }
  2217. static int showDebugInfoCorrelation(const std::string &Filename,
  2218. bool ShowDetailedSummary,
  2219. bool ShowProfileSymbolList,
  2220. raw_fd_ostream &OS) {
  2221. std::unique_ptr<InstrProfCorrelator> Correlator;
  2222. if (auto Err = InstrProfCorrelator::get(Filename).moveInto(Correlator))
  2223. exitWithError(std::move(Err), Filename);
  2224. if (auto Err = Correlator->correlateProfileData())
  2225. exitWithError(std::move(Err), Filename);
  2226. InstrProfSymtab Symtab;
  2227. if (auto Err = Symtab.create(
  2228. StringRef(Correlator->getNamesPointer(), Correlator->getNamesSize())))
  2229. exitWithError(std::move(Err), Filename);
  2230. if (ShowProfileSymbolList)
  2231. Symtab.dumpNames(OS);
  2232. // TODO: Read "Profile Data Type" from debug info to compute and show how many
  2233. // counters the section holds.
  2234. if (ShowDetailedSummary)
  2235. OS << "Counters section size: 0x"
  2236. << Twine::utohexstr(Correlator->getCountersSectionSize()) << " bytes\n";
  2237. OS << "Found " << Correlator->getDataSize() << " functions\n";
  2238. return 0;
  2239. }
  2240. static int show_main(int argc, const char *argv[]) {
  2241. cl::opt<std::string> Filename(cl::Positional, cl::desc("<profdata-file>"));
  2242. cl::opt<bool> ShowCounts("counts", cl::init(false),
  2243. cl::desc("Show counter values for shown functions"));
  2244. cl::opt<bool> TextFormat(
  2245. "text", cl::init(false),
  2246. cl::desc("Show instr profile data in text dump format"));
  2247. cl::opt<bool> ShowIndirectCallTargets(
  2248. "ic-targets", cl::init(false),
  2249. cl::desc("Show indirect call site target values for shown functions"));
  2250. cl::opt<bool> ShowMemOPSizes(
  2251. "memop-sizes", cl::init(false),
  2252. cl::desc("Show the profiled sizes of the memory intrinsic calls "
  2253. "for shown functions"));
  2254. cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
  2255. cl::desc("Show detailed profile summary"));
  2256. cl::list<uint32_t> DetailedSummaryCutoffs(
  2257. cl::CommaSeparated, "detailed-summary-cutoffs",
  2258. cl::desc(
  2259. "Cutoff percentages (times 10000) for generating detailed summary"),
  2260. cl::value_desc("800000,901000,999999"));
  2261. cl::opt<bool> ShowHotFuncList(
  2262. "hot-func-list", cl::init(false),
  2263. cl::desc("Show profile summary of a list of hot functions"));
  2264. cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
  2265. cl::desc("Details for every function"));
  2266. cl::opt<bool> ShowCS("showcs", cl::init(false),
  2267. cl::desc("Show context sensitive counts"));
  2268. cl::opt<std::string> ShowFunction("function",
  2269. cl::desc("Details for matching functions"));
  2270. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  2271. cl::init("-"), cl::desc("Output file"));
  2272. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  2273. cl::aliasopt(OutputFilename));
  2274. cl::opt<ProfileKinds> ProfileKind(
  2275. cl::desc("Profile kind:"), cl::init(instr),
  2276. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  2277. clEnumVal(sample, "Sample profile"),
  2278. clEnumVal(memory, "MemProf memory access profile")));
  2279. cl::opt<uint32_t> TopNFunctions(
  2280. "topn", cl::init(0),
  2281. cl::desc("Show the list of functions with the largest internal counts"));
  2282. cl::opt<uint32_t> ValueCutoff(
  2283. "value-cutoff", cl::init(0),
  2284. cl::desc("Set the count value cutoff. Functions with the maximum count "
  2285. "less than this value will not be printed out. (Default is 0)"));
  2286. cl::opt<bool> OnlyListBelow(
  2287. "list-below-cutoff", cl::init(false),
  2288. cl::desc("Only output names of functions whose max count values are "
  2289. "below the cutoff value"));
  2290. cl::opt<bool> ShowProfileSymbolList(
  2291. "show-prof-sym-list", cl::init(false),
  2292. cl::desc("Show profile symbol list if it exists in the profile. "));
  2293. cl::opt<bool> ShowSectionInfoOnly(
  2294. "show-sec-info-only", cl::init(false),
  2295. cl::desc("Show the information of each section in the sample profile. "
  2296. "The flag is only usable when the sample profile is in "
  2297. "extbinary format"));
  2298. cl::opt<bool> ShowBinaryIds("binary-ids", cl::init(false),
  2299. cl::desc("Show binary ids in the profile. "));
  2300. cl::opt<std::string> DebugInfoFilename(
  2301. "debug-info", cl::init(""),
  2302. cl::desc("Read and extract profile metadata from debug info and show "
  2303. "the functions it found."));
  2304. cl::opt<bool> ShowCovered(
  2305. "covered", cl::init(false),
  2306. cl::desc("Show only the functions that have been executed."));
  2307. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
  2308. if (Filename.empty() && DebugInfoFilename.empty())
  2309. exitWithError(
  2310. "the positional argument '<profdata-file>' is required unless '--" +
  2311. DebugInfoFilename.ArgStr + "' is provided");
  2312. if (Filename == OutputFilename) {
  2313. errs() << sys::path::filename(argv[0])
  2314. << ": Input file name cannot be the same as the output file name!\n";
  2315. return 1;
  2316. }
  2317. std::error_code EC;
  2318. raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
  2319. if (EC)
  2320. exitWithErrorCode(EC, OutputFilename);
  2321. if (ShowAllFunctions && !ShowFunction.empty())
  2322. WithColor::warning() << "-function argument ignored: showing all functions\n";
  2323. if (!DebugInfoFilename.empty())
  2324. return showDebugInfoCorrelation(DebugInfoFilename, ShowDetailedSummary,
  2325. ShowProfileSymbolList, OS);
  2326. if (ProfileKind == instr)
  2327. return showInstrProfile(
  2328. Filename, ShowCounts, TopNFunctions, ShowIndirectCallTargets,
  2329. ShowMemOPSizes, ShowDetailedSummary, DetailedSummaryCutoffs,
  2330. ShowAllFunctions, ShowCS, ValueCutoff, OnlyListBelow, ShowFunction,
  2331. TextFormat, ShowBinaryIds, ShowCovered, OS);
  2332. if (ProfileKind == sample)
  2333. return showSampleProfile(Filename, ShowCounts, TopNFunctions,
  2334. ShowAllFunctions, ShowDetailedSummary,
  2335. ShowFunction, ShowProfileSymbolList,
  2336. ShowSectionInfoOnly, ShowHotFuncList, OS);
  2337. return showMemProfProfile(Filename, OS);
  2338. }
  2339. int main(int argc, const char *argv[]) {
  2340. InitLLVM X(argc, argv);
  2341. StringRef ProgName(sys::path::filename(argv[0]));
  2342. if (argc > 1) {
  2343. int (*func)(int, const char *[]) = nullptr;
  2344. if (strcmp(argv[1], "merge") == 0)
  2345. func = merge_main;
  2346. else if (strcmp(argv[1], "show") == 0)
  2347. func = show_main;
  2348. else if (strcmp(argv[1], "overlap") == 0)
  2349. func = overlap_main;
  2350. if (func) {
  2351. std::string Invocation(ProgName.str() + " " + argv[1]);
  2352. argv[1] = Invocation.c_str();
  2353. return func(argc - 1, argv + 1);
  2354. }
  2355. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
  2356. strcmp(argv[1], "--help") == 0) {
  2357. errs() << "OVERVIEW: LLVM profile data tools\n\n"
  2358. << "USAGE: " << ProgName << " <command> [args...]\n"
  2359. << "USAGE: " << ProgName << " <command> -help\n\n"
  2360. << "See each individual command --help for more details.\n"
  2361. << "Available commands: merge, show, overlap\n";
  2362. return 0;
  2363. }
  2364. }
  2365. if (argc < 2)
  2366. errs() << ProgName << ": No command specified!\n";
  2367. else
  2368. errs() << ProgName << ": Unknown command!\n";
  2369. errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
  2370. return 1;
  2371. }