PerfReader.cpp 45 KB

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