PerfReader.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. //===-- PerfReader.cpp - perfscript reader ---------------------*- C++ -*-===//
  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. #include "PerfReader.h"
  9. #include "ProfileGenerator.h"
  10. #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"
  11. #include "llvm/Support/FileSystem.h"
  12. #include "llvm/Support/Process.h"
  13. #define DEBUG_TYPE "perf-reader"
  14. cl::opt<bool> SkipSymbolization("skip-symbolization",
  15. cl::desc("Dump the unsymbolized profile to the "
  16. "output file. It will show unwinder "
  17. "output for CS profile generation."));
  18. static cl::opt<bool> ShowMmapEvents("show-mmap-events",
  19. cl::desc("Print binary load events."));
  20. static cl::opt<bool>
  21. UseOffset("use-offset", cl::init(true),
  22. cl::desc("Work with `--skip-symbolization` or "
  23. "`--unsymbolized-profile` to write/read the "
  24. "offset instead of virtual address."));
  25. static cl::opt<bool> UseLoadableSegmentAsBase(
  26. "use-first-loadable-segment-as-base",
  27. cl::desc("Use first loadable segment address as base address "
  28. "for offsets in unsymbolized profile. By default "
  29. "first executable segment address is used"));
  30. static cl::opt<bool>
  31. IgnoreStackSamples("ignore-stack-samples",
  32. cl::desc("Ignore call stack samples for hybrid samples "
  33. "and produce context-insensitive profile."));
  34. cl::opt<bool> ShowDetailedWarning("show-detailed-warning",
  35. cl::desc("Show detailed warning message."));
  36. extern cl::opt<std::string> PerfTraceFilename;
  37. extern cl::opt<bool> ShowDisassemblyOnly;
  38. extern cl::opt<bool> ShowSourceLocations;
  39. extern cl::opt<std::string> OutputFilename;
  40. namespace llvm {
  41. namespace sampleprof {
  42. void VirtualUnwinder::unwindCall(UnwindState &State) {
  43. uint64_t Source = State.getCurrentLBRSource();
  44. auto *ParentFrame = State.getParentFrame();
  45. // The 2nd frame after leaf could be missing if stack sample is
  46. // taken when IP is within prolog/epilog, as frame chain isn't
  47. // setup yet. Fill in the missing frame in that case.
  48. // TODO: Currently we just assume all the addr that can't match the
  49. // 2nd frame is in prolog/epilog. In the future, we will switch to
  50. // pro/epi tracker(Dwarf CFI) for the precise check.
  51. if (ParentFrame == State.getDummyRootPtr() ||
  52. ParentFrame->Address != Source) {
  53. State.switchToFrame(Source);
  54. if (ParentFrame != State.getDummyRootPtr()) {
  55. if (Source == ExternalAddr)
  56. NumMismatchedExtCallBranch++;
  57. else
  58. NumMismatchedProEpiBranch++;
  59. }
  60. } else {
  61. State.popFrame();
  62. }
  63. State.InstPtr.update(Source);
  64. }
  65. void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {
  66. InstructionPointer &IP = State.InstPtr;
  67. uint64_t Target = State.getCurrentLBRTarget();
  68. uint64_t End = IP.Address;
  69. if (End == ExternalAddr && Target == ExternalAddr) {
  70. // Filter out the case when leaf external frame matches the external LBR
  71. // target, this is a valid state, it happens that the code run into external
  72. // address then return back. The call frame under the external frame
  73. // remains valid and can be unwound later, just skip recording this range.
  74. NumPairedExtAddr++;
  75. return;
  76. }
  77. if (End == ExternalAddr || Target == ExternalAddr) {
  78. // Range is invalid if only one point is external address. This means LBR
  79. // traces contains a standalone external address failing to pair another
  80. // one, likely due to interrupt jmp or broken perf script. Set the
  81. // state to invalid.
  82. NumUnpairedExtAddr++;
  83. State.setInvalid();
  84. return;
  85. }
  86. if (!isValidFallThroughRange(Target, End, Binary)) {
  87. // Skip unwinding the rest of LBR trace when a bogus range is seen.
  88. State.setInvalid();
  89. return;
  90. }
  91. if (Binary->usePseudoProbes()) {
  92. // We don't need to top frame probe since it should be extracted
  93. // from the range.
  94. // The outcome of the virtual unwinding with pseudo probes is a
  95. // map from a context key to the address range being unwound.
  96. // This means basically linear unwinding is not needed for pseudo
  97. // probes. The range will be simply recorded here and will be
  98. // converted to a list of pseudo probes to report in ProfileGenerator.
  99. State.getParentFrame()->recordRangeCount(Target, End, Repeat);
  100. } else {
  101. // Unwind linear execution part.
  102. // Split and record the range by different inline context. For example:
  103. // [0x01] ... main:1 # Target
  104. // [0x02] ... main:2
  105. // [0x03] ... main:3 @ foo:1
  106. // [0x04] ... main:3 @ foo:2
  107. // [0x05] ... main:3 @ foo:3
  108. // [0x06] ... main:4
  109. // [0x07] ... main:5 # End
  110. // It will be recorded:
  111. // [main:*] : [0x06, 0x07], [0x01, 0x02]
  112. // [main:3 @ foo:*] : [0x03, 0x05]
  113. while (IP.Address > Target) {
  114. uint64_t PrevIP = IP.Address;
  115. IP.backward();
  116. // Break into segments for implicit call/return due to inlining
  117. bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);
  118. if (!SameInlinee) {
  119. State.switchToFrame(PrevIP);
  120. State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);
  121. End = IP.Address;
  122. }
  123. }
  124. assert(IP.Address == Target && "The last one must be the target address.");
  125. // Record the remaining range, [0x01, 0x02] in the example
  126. State.switchToFrame(IP.Address);
  127. State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);
  128. }
  129. }
  130. void VirtualUnwinder::unwindReturn(UnwindState &State) {
  131. // Add extra frame as we unwind through the return
  132. const LBREntry &LBR = State.getCurrentLBR();
  133. uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);
  134. State.switchToFrame(CallAddr);
  135. State.pushFrame(LBR.Source);
  136. State.InstPtr.update(LBR.Source);
  137. }
  138. void VirtualUnwinder::unwindBranch(UnwindState &State) {
  139. // TODO: Tolerate tail call for now, as we may see tail call from libraries.
  140. // This is only for intra function branches, excluding tail calls.
  141. uint64_t Source = State.getCurrentLBRSource();
  142. State.switchToFrame(Source);
  143. State.InstPtr.update(Source);
  144. }
  145. std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
  146. std::shared_ptr<StringBasedCtxKey> KeyStr =
  147. std::make_shared<StringBasedCtxKey>();
  148. KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
  149. return KeyStr;
  150. }
  151. std::shared_ptr<AddrBasedCtxKey> AddressStack::getContextKey() {
  152. std::shared_ptr<AddrBasedCtxKey> KeyStr = std::make_shared<AddrBasedCtxKey>();
  153. KeyStr->Context = Stack;
  154. CSProfileGenerator::compressRecursionContext<uint64_t>(KeyStr->Context);
  155. CSProfileGenerator::trimContext<uint64_t>(KeyStr->Context);
  156. return KeyStr;
  157. }
  158. template <typename T>
  159. void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
  160. T &Stack) {
  161. if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
  162. return;
  163. std::shared_ptr<ContextKey> Key = Stack.getContextKey();
  164. if (Key == nullptr)
  165. return;
  166. auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
  167. SampleCounter &SCounter = Ret.first->second;
  168. for (auto &I : Cur->RangeSamples)
  169. SCounter.recordRangeCount(std::get<0>(I), std::get<1>(I), std::get<2>(I));
  170. for (auto &I : Cur->BranchSamples)
  171. SCounter.recordBranchCount(std::get<0>(I), std::get<1>(I), std::get<2>(I));
  172. }
  173. template <typename T>
  174. void VirtualUnwinder::collectSamplesFromFrameTrie(
  175. UnwindState::ProfiledFrame *Cur, T &Stack) {
  176. if (!Cur->isDummyRoot()) {
  177. // Truncate the context for external frame since this isn't a real call
  178. // context the compiler will see.
  179. if (Cur->isExternalFrame() || !Stack.pushFrame(Cur)) {
  180. // Process truncated context
  181. // Start a new traversal ignoring its bottom context
  182. T EmptyStack(Binary);
  183. collectSamplesFromFrame(Cur, EmptyStack);
  184. for (const auto &Item : Cur->Children) {
  185. collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
  186. }
  187. // Keep note of untracked call site and deduplicate them
  188. // for warning later.
  189. if (!Cur->isLeafFrame())
  190. UntrackedCallsites.insert(Cur->Address);
  191. return;
  192. }
  193. }
  194. collectSamplesFromFrame(Cur, Stack);
  195. // Process children frame
  196. for (const auto &Item : Cur->Children) {
  197. collectSamplesFromFrameTrie(Item.second.get(), Stack);
  198. }
  199. // Recover the call stack
  200. Stack.popFrame();
  201. }
  202. void VirtualUnwinder::collectSamplesFromFrameTrie(
  203. UnwindState::ProfiledFrame *Cur) {
  204. if (Binary->usePseudoProbes()) {
  205. AddressStack Stack(Binary);
  206. collectSamplesFromFrameTrie<AddressStack>(Cur, Stack);
  207. } else {
  208. FrameStack Stack(Binary);
  209. collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
  210. }
  211. }
  212. void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
  213. UnwindState &State, uint64_t Repeat) {
  214. if (Branch.Target == ExternalAddr)
  215. return;
  216. // Record external-to-internal pattern on the trie root, it later can be
  217. // used for generating head samples.
  218. if (Branch.Source == ExternalAddr) {
  219. State.getDummyRootPtr()->recordBranchCount(Branch.Source, Branch.Target,
  220. Repeat);
  221. return;
  222. }
  223. if (Binary->usePseudoProbes()) {
  224. // Same as recordRangeCount, We don't need to top frame probe since we will
  225. // extract it from branch's source address
  226. State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
  227. Repeat);
  228. } else {
  229. State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
  230. Repeat);
  231. }
  232. }
  233. bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
  234. // Capture initial state as starting point for unwinding.
  235. UnwindState State(Sample, Binary);
  236. // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
  237. // Stack sample sometimes can be unreliable, so filter out bogus ones.
  238. if (!State.validateInitialState())
  239. return false;
  240. NumTotalBranches += State.LBRStack.size();
  241. // Now process the LBR samples in parrallel with stack sample
  242. // Note that we do not reverse the LBR entry order so we can
  243. // unwind the sample stack as we walk through LBR entries.
  244. while (State.hasNextLBR()) {
  245. State.checkStateConsistency();
  246. // Do not attempt linear unwind for the leaf range as it's incomplete.
  247. if (!State.IsLastLBR()) {
  248. // Unwind implicit calls/returns from inlining, along the linear path,
  249. // break into smaller sub section each with its own calling context.
  250. unwindLinear(State, Repeat);
  251. }
  252. // Save the LBR branch before it gets unwound.
  253. const LBREntry &Branch = State.getCurrentLBR();
  254. if (isCallState(State)) {
  255. // Unwind calls - we know we encountered call if LBR overlaps with
  256. // transition between leaf the 2nd frame. Note that for calls that
  257. // were not in the original stack sample, we should have added the
  258. // extra frame when processing the return paired with this call.
  259. unwindCall(State);
  260. } else if (isReturnState(State)) {
  261. // Unwind returns - check whether the IP is indeed at a return
  262. // instruction
  263. unwindReturn(State);
  264. } else if (isValidState(State)) {
  265. // Unwind branches
  266. unwindBranch(State);
  267. } else {
  268. // Skip unwinding the rest of LBR trace. Reset the stack and update the
  269. // state so that the rest of the trace can still be processed as if they
  270. // do not have stack samples.
  271. State.clearCallStack();
  272. State.InstPtr.update(State.getCurrentLBRSource());
  273. State.pushFrame(State.InstPtr.Address);
  274. }
  275. State.advanceLBR();
  276. // Record `branch` with calling context after unwinding.
  277. recordBranchCount(Branch, State, Repeat);
  278. }
  279. // As samples are aggregated on trie, record them into counter map
  280. collectSamplesFromFrameTrie(State.getDummyRootPtr());
  281. return true;
  282. }
  283. std::unique_ptr<PerfReaderBase>
  284. PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput,
  285. std::optional<uint32_t> PIDFilter) {
  286. std::unique_ptr<PerfReaderBase> PerfReader;
  287. if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
  288. PerfReader.reset(
  289. new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
  290. return PerfReader;
  291. }
  292. // For perf data input, we need to convert them into perf script first.
  293. if (PerfInput.Format == PerfFormat::PerfData)
  294. PerfInput =
  295. PerfScriptReader::convertPerfDataToTrace(Binary, PerfInput, PIDFilter);
  296. assert((PerfInput.Format == PerfFormat::PerfScript) &&
  297. "Should be a perfscript!");
  298. PerfInput.Content =
  299. PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);
  300. if (PerfInput.Content == PerfContent::LBRStack) {
  301. PerfReader.reset(
  302. new HybridPerfReader(Binary, PerfInput.InputFile, PIDFilter));
  303. } else if (PerfInput.Content == PerfContent::LBR) {
  304. PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile, PIDFilter));
  305. } else {
  306. exitWithError("Unsupported perfscript!");
  307. }
  308. return PerfReader;
  309. }
  310. PerfInputFile
  311. PerfScriptReader::convertPerfDataToTrace(ProfiledBinary *Binary,
  312. PerfInputFile &File,
  313. std::optional<uint32_t> PIDFilter) {
  314. StringRef PerfData = File.InputFile;
  315. // Run perf script to retrieve PIDs matching binary we're interested in.
  316. auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");
  317. if (!PerfExecutable) {
  318. exitWithError("Perf not found.");
  319. }
  320. std::string PerfPath = *PerfExecutable;
  321. std::string PerfTraceFile = PerfData.str() + ".script.tmp";
  322. std::string ErrorFile = PerfData.str() + ".script.err.tmp";
  323. StringRef ScriptMMapArgs[] = {PerfPath, "script", "--show-mmap-events",
  324. "-F", "comm,pid", "-i",
  325. PerfData};
  326. std::optional<StringRef> Redirects[] = {std::nullopt, // Stdin
  327. StringRef(PerfTraceFile), // Stdout
  328. StringRef(ErrorFile)}; // Stderr
  329. sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, std::nullopt, Redirects);
  330. // Collect the PIDs
  331. TraceStream TraceIt(PerfTraceFile);
  332. std::string PIDs;
  333. std::unordered_set<uint32_t> PIDSet;
  334. while (!TraceIt.isAtEoF()) {
  335. MMapEvent MMap;
  336. if (isMMap2Event(TraceIt.getCurrentLine()) &&
  337. extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {
  338. auto It = PIDSet.emplace(MMap.PID);
  339. if (It.second && (!PIDFilter || MMap.PID == *PIDFilter)) {
  340. if (!PIDs.empty()) {
  341. PIDs.append(",");
  342. }
  343. PIDs.append(utostr(MMap.PID));
  344. }
  345. }
  346. TraceIt.advance();
  347. }
  348. if (PIDs.empty()) {
  349. exitWithError("No relevant mmap event is found in perf data.");
  350. }
  351. // Run perf script again to retrieve events for PIDs collected above
  352. StringRef ScriptSampleArgs[] = {PerfPath, "script", "--show-mmap-events",
  353. "-F", "ip,brstack", "--pid",
  354. PIDs, "-i", PerfData};
  355. sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, std::nullopt, Redirects);
  356. return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
  357. }
  358. void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {
  359. // Drop the event which doesn't belong to user-provided binary
  360. StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
  361. if (Binary->getName() != BinaryName)
  362. return;
  363. // Drop the event if process does not match pid filter
  364. if (PIDFilter && Event.PID != *PIDFilter)
  365. return;
  366. // Drop the event if its image is loaded at the same address
  367. if (Event.Address == Binary->getBaseAddress()) {
  368. Binary->setIsLoadedByMMap(true);
  369. return;
  370. }
  371. if (Event.Offset == Binary->getTextSegmentOffset()) {
  372. // A binary image could be unloaded and then reloaded at different
  373. // place, so update binary load address.
  374. // Only update for the first executable segment and assume all other
  375. // segments are loaded at consecutive memory addresses, which is the case on
  376. // X64.
  377. Binary->setBaseAddress(Event.Address);
  378. Binary->setIsLoadedByMMap(true);
  379. } else {
  380. // Verify segments are loaded consecutively.
  381. const auto &Offsets = Binary->getTextSegmentOffsets();
  382. auto It = llvm::lower_bound(Offsets, Event.Offset);
  383. if (It != Offsets.end() && *It == Event.Offset) {
  384. // The event is for loading a separate executable segment.
  385. auto I = std::distance(Offsets.begin(), It);
  386. const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
  387. if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
  388. Event.Address - Binary->getBaseAddress())
  389. exitWithError("Executable segments not loaded consecutively");
  390. } else {
  391. if (It == Offsets.begin())
  392. exitWithError("File offset not found");
  393. else {
  394. // Find the segment the event falls in. A large segment could be loaded
  395. // via multiple mmap calls with consecutive memory addresses.
  396. --It;
  397. assert(*It < Event.Offset);
  398. if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
  399. exitWithError("Segment not loaded by consecutive mmaps");
  400. }
  401. }
  402. }
  403. }
  404. static std::string getContextKeyStr(ContextKey *K,
  405. const ProfiledBinary *Binary) {
  406. if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
  407. return SampleContext::getContextString(CtxKey->Context);
  408. } else if (const auto *CtxKey = dyn_cast<AddrBasedCtxKey>(K)) {
  409. std::ostringstream OContextStr;
  410. for (uint32_t I = 0; I < CtxKey->Context.size(); I++) {
  411. if (OContextStr.str().size())
  412. OContextStr << " @ ";
  413. uint64_t Address = CtxKey->Context[I];
  414. if (UseOffset) {
  415. if (UseLoadableSegmentAsBase)
  416. Address -= Binary->getFirstLoadableAddress();
  417. else
  418. Address -= Binary->getPreferredBaseAddress();
  419. }
  420. OContextStr << "0x"
  421. << utohexstr(Address,
  422. /*LowerCase=*/true);
  423. }
  424. return OContextStr.str();
  425. } else {
  426. llvm_unreachable("unexpected key type");
  427. }
  428. }
  429. void HybridPerfReader::unwindSamples() {
  430. if (Binary->useFSDiscriminator())
  431. exitWithError("FS discriminator is not supported in CS profile.");
  432. VirtualUnwinder Unwinder(&SampleCounters, Binary);
  433. for (const auto &Item : AggregatedSamples) {
  434. const PerfSample *Sample = Item.first.getPtr();
  435. Unwinder.unwind(Sample, Item.second);
  436. }
  437. // Warn about untracked frames due to missing probes.
  438. if (ShowDetailedWarning) {
  439. for (auto Address : Unwinder.getUntrackedCallsites())
  440. WithColor::warning() << "Profile context truncated due to missing probe "
  441. << "for call instruction at "
  442. << format("0x%" PRIx64, Address) << "\n";
  443. }
  444. emitWarningSummary(Unwinder.getUntrackedCallsites().size(),
  445. SampleCounters.size(),
  446. "of profiled contexts are truncated due to missing probe "
  447. "for call instruction.");
  448. emitWarningSummary(
  449. Unwinder.NumMismatchedExtCallBranch, Unwinder.NumTotalBranches,
  450. "of branches'source is a call instruction but doesn't match call frame "
  451. "stack, likely due to unwinding error of external frame.");
  452. emitWarningSummary(Unwinder.NumPairedExtAddr * 2, Unwinder.NumTotalBranches,
  453. "of branches containing paired external address.");
  454. emitWarningSummary(Unwinder.NumUnpairedExtAddr, Unwinder.NumTotalBranches,
  455. "of branches containing external address but doesn't have "
  456. "another external address to pair, likely due to "
  457. "interrupt jmp or broken perf script.");
  458. emitWarningSummary(
  459. Unwinder.NumMismatchedProEpiBranch, Unwinder.NumTotalBranches,
  460. "of branches'source is a call instruction but doesn't match call frame "
  461. "stack, likely due to frame in prolog/epilog.");
  462. emitWarningSummary(Unwinder.NumMissingExternalFrame,
  463. Unwinder.NumExtCallBranch,
  464. "of artificial call branches but doesn't have an external "
  465. "frame to match.");
  466. }
  467. bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
  468. SmallVectorImpl<LBREntry> &LBRStack) {
  469. // The raw format of LBR stack is like:
  470. // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  471. // ... 0x4005c8/0x4005dc/P/-/-/0
  472. // It's in FIFO order and seperated by whitespace.
  473. SmallVector<StringRef, 32> Records;
  474. TraceIt.getCurrentLine().split(Records, " ", -1, false);
  475. auto WarnInvalidLBR = [](TraceStream &TraceIt) {
  476. WithColor::warning() << "Invalid address in LBR record at line "
  477. << TraceIt.getLineNumber() << ": "
  478. << TraceIt.getCurrentLine() << "\n";
  479. };
  480. // Skip the leading instruction pointer.
  481. size_t Index = 0;
  482. uint64_t LeadingAddr;
  483. if (!Records.empty() && !Records[0].contains('/')) {
  484. if (Records[0].getAsInteger(16, LeadingAddr)) {
  485. WarnInvalidLBR(TraceIt);
  486. TraceIt.advance();
  487. return false;
  488. }
  489. Index = 1;
  490. }
  491. // Now extract LBR samples - note that we do not reverse the
  492. // LBR entry order so we can unwind the sample stack as we walk
  493. // through LBR entries.
  494. while (Index < Records.size()) {
  495. auto &Token = Records[Index++];
  496. if (Token.size() == 0)
  497. continue;
  498. SmallVector<StringRef, 8> Addresses;
  499. Token.split(Addresses, "/");
  500. uint64_t Src;
  501. uint64_t Dst;
  502. // Stop at broken LBR records.
  503. if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
  504. Addresses[1].substr(2).getAsInteger(16, Dst)) {
  505. WarnInvalidLBR(TraceIt);
  506. break;
  507. }
  508. // Canonicalize to use preferred load address as base address.
  509. Src = Binary->canonicalizeVirtualAddress(Src);
  510. Dst = Binary->canonicalizeVirtualAddress(Dst);
  511. bool SrcIsInternal = Binary->addressIsCode(Src);
  512. bool DstIsInternal = Binary->addressIsCode(Dst);
  513. if (!SrcIsInternal)
  514. Src = ExternalAddr;
  515. if (!DstIsInternal)
  516. Dst = ExternalAddr;
  517. // Filter external-to-external case to reduce LBR trace size.
  518. if (!SrcIsInternal && !DstIsInternal)
  519. continue;
  520. LBRStack.emplace_back(LBREntry(Src, Dst));
  521. }
  522. TraceIt.advance();
  523. return !LBRStack.empty();
  524. }
  525. bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,
  526. SmallVectorImpl<uint64_t> &CallStack) {
  527. // The raw format of call stack is like:
  528. // 4005dc # leaf frame
  529. // 400634
  530. // 400684 # root frame
  531. // It's in bottom-up order with each frame in one line.
  532. // Extract stack frames from sample
  533. while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
  534. StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
  535. uint64_t FrameAddr = 0;
  536. if (FrameStr.getAsInteger(16, FrameAddr)) {
  537. // We might parse a non-perf sample line like empty line and comments,
  538. // skip it
  539. TraceIt.advance();
  540. return false;
  541. }
  542. TraceIt.advance();
  543. FrameAddr = Binary->canonicalizeVirtualAddress(FrameAddr);
  544. // Currently intermixed frame from different binaries is not supported.
  545. if (!Binary->addressIsCode(FrameAddr)) {
  546. if (CallStack.empty())
  547. NumLeafExternalFrame++;
  548. // Push a special value(ExternalAddr) for the external frames so that
  549. // unwinder can still work on this with artificial Call/Return branch.
  550. // After unwinding, the context will be truncated for external frame.
  551. // Also deduplicate the consecutive external addresses.
  552. if (CallStack.empty() || CallStack.back() != ExternalAddr)
  553. CallStack.emplace_back(ExternalAddr);
  554. continue;
  555. }
  556. // We need to translate return address to call address for non-leaf frames.
  557. if (!CallStack.empty()) {
  558. auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
  559. if (!CallAddr) {
  560. // Stop at an invalid return address caused by bad unwinding. This could
  561. // happen to frame-pointer-based unwinding and the callee functions that
  562. // do not have the frame pointer chain set up.
  563. InvalidReturnAddresses.insert(FrameAddr);
  564. break;
  565. }
  566. FrameAddr = CallAddr;
  567. }
  568. CallStack.emplace_back(FrameAddr);
  569. }
  570. // Strip out the bottom external addr.
  571. if (CallStack.size() > 1 && CallStack.back() == ExternalAddr)
  572. CallStack.pop_back();
  573. // Skip other unrelated line, find the next valid LBR line
  574. // Note that even for empty call stack, we should skip the address at the
  575. // bottom, otherwise the following pass may generate a truncated callstack
  576. while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
  577. TraceIt.advance();
  578. }
  579. // Filter out broken stack sample. We may not have complete frame info
  580. // if sample end up in prolog/epilog, the result is dangling context not
  581. // connected to entry point. This should be relatively rare thus not much
  582. // impact on overall profile quality. However we do want to filter them
  583. // out to reduce the number of different calling contexts. One instance
  584. // of such case - when sample landed in prolog/epilog, somehow stack
  585. // walking will be broken in an unexpected way that higher frames will be
  586. // missing.
  587. return !CallStack.empty() &&
  588. !Binary->addressInPrologEpilog(CallStack.front());
  589. }
  590. void PerfScriptReader::warnIfMissingMMap() {
  591. if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
  592. WithColor::warning() << "No relevant mmap event is matched for "
  593. << Binary->getName()
  594. << ", will use preferred address ("
  595. << format("0x%" PRIx64,
  596. Binary->getPreferredBaseAddress())
  597. << ") as the base loading address!\n";
  598. // Avoid redundant warning, only warn at the first unmatched sample.
  599. Binary->setMissingMMapWarned(true);
  600. }
  601. }
  602. void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
  603. // The raw hybird sample started with call stack in FILO order and followed
  604. // intermediately by LBR sample
  605. // e.g.
  606. // 4005dc # call stack leaf
  607. // 400634
  608. // 400684 # call stack root
  609. // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  610. // ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
  611. //
  612. std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
  613. #ifndef NDEBUG
  614. Sample->Linenum = TraceIt.getLineNumber();
  615. #endif
  616. // Parsing call stack and populate into PerfSample.CallStack
  617. if (!extractCallstack(TraceIt, Sample->CallStack)) {
  618. // Skip the next LBR line matched current call stack
  619. if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
  620. TraceIt.advance();
  621. return;
  622. }
  623. warnIfMissingMMap();
  624. if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
  625. // Parsing LBR stack and populate into PerfSample.LBRStack
  626. if (extractLBRStack(TraceIt, Sample->LBRStack)) {
  627. if (IgnoreStackSamples) {
  628. Sample->CallStack.clear();
  629. } else {
  630. // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
  631. // ranges
  632. Sample->CallStack.front() = Sample->LBRStack[0].Target;
  633. }
  634. // Record samples by aggregation
  635. AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
  636. }
  637. } else {
  638. // LBR sample is encoded in single line after stack sample
  639. exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
  640. }
  641. }
  642. void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {
  643. std::error_code EC;
  644. raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
  645. if (EC)
  646. exitWithError(EC, Filename);
  647. writeUnsymbolizedProfile(OS);
  648. }
  649. // Use ordered map to make the output deterministic
  650. using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;
  651. void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {
  652. OrderedCounterForPrint OrderedCounters;
  653. for (auto &CI : SampleCounters) {
  654. OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;
  655. }
  656. auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,
  657. uint32_t Indent) {
  658. OS.indent(Indent);
  659. OS << Counter.size() << "\n";
  660. for (auto &I : Counter) {
  661. uint64_t Start = I.first.first;
  662. uint64_t End = I.first.second;
  663. if (UseOffset) {
  664. if (UseLoadableSegmentAsBase) {
  665. Start -= Binary->getFirstLoadableAddress();
  666. End -= Binary->getFirstLoadableAddress();
  667. } else {
  668. Start -= Binary->getPreferredBaseAddress();
  669. End -= Binary->getPreferredBaseAddress();
  670. }
  671. }
  672. OS.indent(Indent);
  673. OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"
  674. << I.second << "\n";
  675. }
  676. };
  677. for (auto &CI : OrderedCounters) {
  678. uint32_t Indent = 0;
  679. if (ProfileIsCS) {
  680. // Context string key
  681. OS << "[" << CI.first << "]\n";
  682. Indent = 2;
  683. }
  684. SampleCounter &Counter = *CI.second;
  685. SCounterPrinter(Counter.RangeCounter, "-", Indent);
  686. SCounterPrinter(Counter.BranchCounter, "->", Indent);
  687. }
  688. }
  689. // Format of input:
  690. // number of entries in RangeCounter
  691. // from_1-to_1:count_1
  692. // from_2-to_2:count_2
  693. // ......
  694. // from_n-to_n:count_n
  695. // number of entries in BranchCounter
  696. // src_1->dst_1:count_1
  697. // src_2->dst_2:count_2
  698. // ......
  699. // src_n->dst_n:count_n
  700. void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,
  701. SampleCounter &SCounters) {
  702. auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {
  703. std::string Msg = TraceIt.isAtEoF()
  704. ? "Invalid raw profile!"
  705. : "Invalid raw profile at line " +
  706. Twine(TraceIt.getLineNumber()).str() + ": " +
  707. TraceIt.getCurrentLine().str();
  708. exitWithError(Msg);
  709. };
  710. auto ReadNumber = [&](uint64_t &Num) {
  711. if (TraceIt.isAtEoF())
  712. exitWithErrorForTraceLine(TraceIt);
  713. if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))
  714. exitWithErrorForTraceLine(TraceIt);
  715. TraceIt.advance();
  716. };
  717. auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {
  718. uint64_t Num = 0;
  719. ReadNumber(Num);
  720. while (Num--) {
  721. if (TraceIt.isAtEoF())
  722. exitWithErrorForTraceLine(TraceIt);
  723. StringRef Line = TraceIt.getCurrentLine().ltrim();
  724. uint64_t Count = 0;
  725. auto LineSplit = Line.split(":");
  726. if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))
  727. exitWithErrorForTraceLine(TraceIt);
  728. uint64_t Source = 0;
  729. uint64_t Target = 0;
  730. auto Range = LineSplit.first.split(Separator);
  731. if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||
  732. Range.second.getAsInteger(16, Target))
  733. exitWithErrorForTraceLine(TraceIt);
  734. if (UseOffset) {
  735. if (UseLoadableSegmentAsBase) {
  736. Source += Binary->getFirstLoadableAddress();
  737. Target += Binary->getFirstLoadableAddress();
  738. } else {
  739. Source += Binary->getPreferredBaseAddress();
  740. Target += Binary->getPreferredBaseAddress();
  741. }
  742. }
  743. Counter[{Source, Target}] += Count;
  744. TraceIt.advance();
  745. }
  746. };
  747. ReadCounter(SCounters.RangeCounter, "-");
  748. ReadCounter(SCounters.BranchCounter, "->");
  749. }
  750. void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {
  751. TraceStream TraceIt(FileName);
  752. while (!TraceIt.isAtEoF()) {
  753. std::shared_ptr<StringBasedCtxKey> Key =
  754. std::make_shared<StringBasedCtxKey>();
  755. StringRef Line = TraceIt.getCurrentLine();
  756. // Read context stack for CS profile.
  757. if (Line.startswith("[")) {
  758. ProfileIsCS = true;
  759. auto I = ContextStrSet.insert(Line.str());
  760. SampleContext::createCtxVectorFromStr(*I.first, Key->Context);
  761. TraceIt.advance();
  762. }
  763. auto Ret =
  764. SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
  765. readSampleCounters(TraceIt, Ret.first->second);
  766. }
  767. }
  768. void UnsymbolizedProfileReader::parsePerfTraces() {
  769. readUnsymbolizedProfile(PerfTraceFile);
  770. }
  771. void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,
  772. uint64_t Repeat) {
  773. SampleCounter &Counter = SampleCounters.begin()->second;
  774. uint64_t EndAddress = 0;
  775. for (const LBREntry &LBR : Sample->LBRStack) {
  776. uint64_t SourceAddress = LBR.Source;
  777. uint64_t TargetAddress = LBR.Target;
  778. // Record the branch if its SourceAddress is external. It can be the case an
  779. // external source call an internal function, later this branch will be used
  780. // to generate the function's head sample.
  781. if (Binary->addressIsCode(TargetAddress)) {
  782. Counter.recordBranchCount(SourceAddress, TargetAddress, Repeat);
  783. }
  784. // If this not the first LBR, update the range count between TO of current
  785. // LBR and FROM of next LBR.
  786. uint64_t StartAddress = TargetAddress;
  787. if (Binary->addressIsCode(StartAddress) &&
  788. Binary->addressIsCode(EndAddress) &&
  789. isValidFallThroughRange(StartAddress, EndAddress, Binary))
  790. Counter.recordRangeCount(StartAddress, EndAddress, Repeat);
  791. EndAddress = SourceAddress;
  792. }
  793. }
  794. void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
  795. std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
  796. // Parsing LBR stack and populate into PerfSample.LBRStack
  797. if (extractLBRStack(TraceIt, Sample->LBRStack)) {
  798. warnIfMissingMMap();
  799. // Record LBR only samples by aggregation
  800. AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
  801. }
  802. }
  803. void PerfScriptReader::generateUnsymbolizedProfile() {
  804. // There is no context for LBR only sample, so initialize one entry with
  805. // fake "empty" context key.
  806. assert(SampleCounters.empty() &&
  807. "Sample counter map should be empty before raw profile generation");
  808. std::shared_ptr<StringBasedCtxKey> Key =
  809. std::make_shared<StringBasedCtxKey>();
  810. SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
  811. for (const auto &Item : AggregatedSamples) {
  812. const PerfSample *Sample = Item.first.getPtr();
  813. computeCounterFromLBR(Sample, Item.second);
  814. }
  815. }
  816. uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {
  817. // The aggregated count is optional, so do not skip the line and return 1 if
  818. // it's unmatched
  819. uint64_t Count = 1;
  820. if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
  821. TraceIt.advance();
  822. return Count;
  823. }
  824. void PerfScriptReader::parseSample(TraceStream &TraceIt) {
  825. NumTotalSample++;
  826. uint64_t Count = parseAggregatedCount(TraceIt);
  827. assert(Count >= 1 && "Aggregated count should be >= 1!");
  828. parseSample(TraceIt, Count);
  829. }
  830. bool PerfScriptReader::extractMMap2EventForBinary(ProfiledBinary *Binary,
  831. StringRef Line,
  832. MMapEvent &MMap) {
  833. // Parse a line like:
  834. // PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
  835. // 08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
  836. constexpr static const char *const Pattern =
  837. "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
  838. "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
  839. "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
  840. // Field 0 - whole line
  841. // Field 1 - PID
  842. // Field 2 - base address
  843. // Field 3 - mmapped size
  844. // Field 4 - page offset
  845. // Field 5 - binary path
  846. enum EventIndex {
  847. WHOLE_LINE = 0,
  848. PID = 1,
  849. MMAPPED_ADDRESS = 2,
  850. MMAPPED_SIZE = 3,
  851. PAGE_OFFSET = 4,
  852. BINARY_PATH = 5
  853. };
  854. Regex RegMmap2(Pattern);
  855. SmallVector<StringRef, 6> Fields;
  856. bool R = RegMmap2.match(Line, &Fields);
  857. if (!R) {
  858. std::string WarningMsg = "Cannot parse mmap event: " + Line.str() + " \n";
  859. WithColor::warning() << WarningMsg;
  860. }
  861. Fields[PID].getAsInteger(10, MMap.PID);
  862. Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);
  863. Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);
  864. Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);
  865. MMap.BinaryPath = Fields[BINARY_PATH];
  866. if (ShowMmapEvents) {
  867. outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "
  868. << format("0x%" PRIx64 ":", MMap.Address) << " \n";
  869. }
  870. StringRef BinaryName = llvm::sys::path::filename(MMap.BinaryPath);
  871. return Binary->getName() == BinaryName;
  872. }
  873. void PerfScriptReader::parseMMap2Event(TraceStream &TraceIt) {
  874. MMapEvent MMap;
  875. if (extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap))
  876. updateBinaryAddress(MMap);
  877. TraceIt.advance();
  878. }
  879. void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {
  880. if (isMMap2Event(TraceIt.getCurrentLine()))
  881. parseMMap2Event(TraceIt);
  882. else
  883. parseSample(TraceIt);
  884. }
  885. void PerfScriptReader::parseAndAggregateTrace() {
  886. // Trace line iterator
  887. TraceStream TraceIt(PerfTraceFile);
  888. while (!TraceIt.isAtEoF())
  889. parseEventOrSample(TraceIt);
  890. }
  891. // A LBR sample is like:
  892. // 40062f 0x5c6313f/0x5c63170/P/-/-/0 0x5c630e7/0x5c63130/P/-/-/0 ...
  893. // A heuristic for fast detection by checking whether a
  894. // leading " 0x" and the '/' exist.
  895. bool PerfScriptReader::isLBRSample(StringRef Line) {
  896. // Skip the leading instruction pointer
  897. SmallVector<StringRef, 32> Records;
  898. Line.trim().split(Records, " ", 2, false);
  899. if (Records.size() < 2)
  900. return false;
  901. if (Records[1].startswith("0x") && Records[1].contains('/'))
  902. return true;
  903. return false;
  904. }
  905. bool PerfScriptReader::isMMap2Event(StringRef Line) {
  906. // Short cut to avoid string find is possible.
  907. if (Line.empty() || Line.size() < 50)
  908. return false;
  909. if (std::isdigit(Line[0]))
  910. return false;
  911. // PERF_RECORD_MMAP2 does not appear at the beginning of the line
  912. // for ` perf script --show-mmap-events -i ...`
  913. return Line.contains("PERF_RECORD_MMAP2");
  914. }
  915. // The raw hybird sample is like
  916. // e.g.
  917. // 4005dc # call stack leaf
  918. // 400634
  919. // 400684 # call stack root
  920. // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  921. // ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
  922. // Determine the perfscript contains hybrid samples(call stack + LBRs) by
  923. // checking whether there is a non-empty call stack immediately followed by
  924. // a LBR sample
  925. PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {
  926. TraceStream TraceIt(FileName);
  927. uint64_t FrameAddr = 0;
  928. while (!TraceIt.isAtEoF()) {
  929. // Skip the aggregated count
  930. if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))
  931. TraceIt.advance();
  932. // Detect sample with call stack
  933. int32_t Count = 0;
  934. while (!TraceIt.isAtEoF() &&
  935. !TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {
  936. Count++;
  937. TraceIt.advance();
  938. }
  939. if (!TraceIt.isAtEoF()) {
  940. if (isLBRSample(TraceIt.getCurrentLine())) {
  941. if (Count > 0)
  942. return PerfContent::LBRStack;
  943. else
  944. return PerfContent::LBR;
  945. }
  946. TraceIt.advance();
  947. }
  948. }
  949. exitWithError("Invalid perf script input!");
  950. return PerfContent::UnknownContent;
  951. }
  952. void HybridPerfReader::generateUnsymbolizedProfile() {
  953. ProfileIsCS = !IgnoreStackSamples;
  954. if (ProfileIsCS)
  955. unwindSamples();
  956. else
  957. PerfScriptReader::generateUnsymbolizedProfile();
  958. }
  959. void PerfScriptReader::warnTruncatedStack() {
  960. if (ShowDetailedWarning) {
  961. for (auto Address : InvalidReturnAddresses) {
  962. WithColor::warning()
  963. << "Truncated stack sample due to invalid return address at "
  964. << format("0x%" PRIx64, Address)
  965. << ", likely caused by frame pointer omission\n";
  966. }
  967. }
  968. emitWarningSummary(
  969. InvalidReturnAddresses.size(), AggregatedSamples.size(),
  970. "of truncated stack samples due to invalid return address, "
  971. "likely caused by frame pointer omission.");
  972. }
  973. void PerfScriptReader::warnInvalidRange() {
  974. std::unordered_map<std::pair<uint64_t, uint64_t>, uint64_t,
  975. pair_hash<uint64_t, uint64_t>>
  976. Ranges;
  977. for (const auto &Item : AggregatedSamples) {
  978. const PerfSample *Sample = Item.first.getPtr();
  979. uint64_t Count = Item.second;
  980. uint64_t EndAddress = 0;
  981. for (const LBREntry &LBR : Sample->LBRStack) {
  982. uint64_t SourceAddress = LBR.Source;
  983. uint64_t StartAddress = LBR.Target;
  984. if (EndAddress != 0)
  985. Ranges[{StartAddress, EndAddress}] += Count;
  986. EndAddress = SourceAddress;
  987. }
  988. }
  989. if (Ranges.empty()) {
  990. WithColor::warning() << "No samples in perf script!\n";
  991. return;
  992. }
  993. auto WarnInvalidRange = [&](uint64_t StartAddress, uint64_t EndAddress,
  994. StringRef Msg) {
  995. if (!ShowDetailedWarning)
  996. return;
  997. WithColor::warning() << "[" << format("%8" PRIx64, StartAddress) << ","
  998. << format("%8" PRIx64, EndAddress) << "]: " << Msg
  999. << "\n";
  1000. };
  1001. const char *EndNotBoundaryMsg = "Range is not on instruction boundary, "
  1002. "likely due to profile and binary mismatch.";
  1003. const char *DanglingRangeMsg = "Range does not belong to any functions, "
  1004. "likely from PLT, .init or .fini section.";
  1005. const char *RangeCrossFuncMsg =
  1006. "Fall through range should not cross function boundaries, likely due to "
  1007. "profile and binary mismatch.";
  1008. const char *BogusRangeMsg = "Range start is after or too far from range end.";
  1009. uint64_t TotalRangeNum = 0;
  1010. uint64_t InstNotBoundary = 0;
  1011. uint64_t UnmatchedRange = 0;
  1012. uint64_t RangeCrossFunc = 0;
  1013. uint64_t BogusRange = 0;
  1014. for (auto &I : Ranges) {
  1015. uint64_t StartAddress = I.first.first;
  1016. uint64_t EndAddress = I.first.second;
  1017. TotalRangeNum += I.second;
  1018. if (!Binary->addressIsCode(StartAddress) &&
  1019. !Binary->addressIsCode(EndAddress))
  1020. continue;
  1021. if (!Binary->addressIsCode(StartAddress) ||
  1022. !Binary->addressIsTransfer(EndAddress)) {
  1023. InstNotBoundary += I.second;
  1024. WarnInvalidRange(StartAddress, EndAddress, EndNotBoundaryMsg);
  1025. }
  1026. auto *FRange = Binary->findFuncRange(StartAddress);
  1027. if (!FRange) {
  1028. UnmatchedRange += I.second;
  1029. WarnInvalidRange(StartAddress, EndAddress, DanglingRangeMsg);
  1030. continue;
  1031. }
  1032. if (EndAddress >= FRange->EndAddress) {
  1033. RangeCrossFunc += I.second;
  1034. WarnInvalidRange(StartAddress, EndAddress, RangeCrossFuncMsg);
  1035. }
  1036. if (Binary->addressIsCode(StartAddress) &&
  1037. Binary->addressIsCode(EndAddress) &&
  1038. !isValidFallThroughRange(StartAddress, EndAddress, Binary)) {
  1039. BogusRange += I.second;
  1040. WarnInvalidRange(StartAddress, EndAddress, BogusRangeMsg);
  1041. }
  1042. }
  1043. emitWarningSummary(
  1044. InstNotBoundary, TotalRangeNum,
  1045. "of samples are from ranges that are not on instruction boundary.");
  1046. emitWarningSummary(
  1047. UnmatchedRange, TotalRangeNum,
  1048. "of samples are from ranges that do not belong to any functions.");
  1049. emitWarningSummary(
  1050. RangeCrossFunc, TotalRangeNum,
  1051. "of samples are from ranges that do cross function boundaries.");
  1052. emitWarningSummary(
  1053. BogusRange, TotalRangeNum,
  1054. "of samples are from ranges that have range start after or too far from "
  1055. "range end acrossing the unconditinal jmp.");
  1056. }
  1057. void PerfScriptReader::parsePerfTraces() {
  1058. // Parse perf traces and do aggregation.
  1059. parseAndAggregateTrace();
  1060. emitWarningSummary(NumLeafExternalFrame, NumTotalSample,
  1061. "of samples have leaf external frame in call stack.");
  1062. emitWarningSummary(NumLeadingOutgoingLBR, NumTotalSample,
  1063. "of samples have leading external LBR.");
  1064. // Generate unsymbolized profile.
  1065. warnTruncatedStack();
  1066. warnInvalidRange();
  1067. generateUnsymbolizedProfile();
  1068. AggregatedSamples.clear();
  1069. if (SkipSymbolization)
  1070. writeUnsymbolizedProfile(OutputFilename);
  1071. }
  1072. } // end namespace sampleprof
  1073. } // end namespace llvm