llvm-mca.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- 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. //
  9. // This utility is a simple driver that allows static performance analysis on
  10. // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
  11. //
  12. // llvm-mca [options] <file-name>
  13. // -march <type>
  14. // -mcpu <cpu>
  15. // -o <file>
  16. //
  17. // The target defaults to the host target.
  18. // The cpu defaults to the 'native' host cpu.
  19. // The output defaults to standard output.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "CodeRegion.h"
  23. #include "CodeRegionGenerator.h"
  24. #include "PipelinePrinter.h"
  25. #include "Views/BottleneckAnalysis.h"
  26. #include "Views/DispatchStatistics.h"
  27. #include "Views/InstructionInfoView.h"
  28. #include "Views/RegisterFileStatistics.h"
  29. #include "Views/ResourcePressureView.h"
  30. #include "Views/RetireControlUnitStatistics.h"
  31. #include "Views/SchedulerStatistics.h"
  32. #include "Views/SummaryView.h"
  33. #include "Views/TimelineView.h"
  34. #include "llvm/MC/MCAsmBackend.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/MCCodeEmitter.h"
  37. #include "llvm/MC/MCContext.h"
  38. #include "llvm/MC/MCObjectFileInfo.h"
  39. #include "llvm/MC/MCRegisterInfo.h"
  40. #include "llvm/MC/MCSubtargetInfo.h"
  41. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  42. #include "llvm/MC/TargetRegistry.h"
  43. #include "llvm/MCA/CodeEmitter.h"
  44. #include "llvm/MCA/Context.h"
  45. #include "llvm/MCA/CustomBehaviour.h"
  46. #include "llvm/MCA/InstrBuilder.h"
  47. #include "llvm/MCA/Pipeline.h"
  48. #include "llvm/MCA/Stages/EntryStage.h"
  49. #include "llvm/MCA/Stages/InstructionTables.h"
  50. #include "llvm/MCA/Support.h"
  51. #include "llvm/Support/CommandLine.h"
  52. #include "llvm/Support/ErrorHandling.h"
  53. #include "llvm/Support/ErrorOr.h"
  54. #include "llvm/Support/FileSystem.h"
  55. #include "llvm/Support/Host.h"
  56. #include "llvm/Support/InitLLVM.h"
  57. #include "llvm/Support/MemoryBuffer.h"
  58. #include "llvm/Support/SourceMgr.h"
  59. #include "llvm/Support/TargetSelect.h"
  60. #include "llvm/Support/ToolOutputFile.h"
  61. #include "llvm/Support/WithColor.h"
  62. using namespace llvm;
  63. static mc::RegisterMCTargetOptionsFlags MOF;
  64. static cl::OptionCategory ToolOptions("Tool Options");
  65. static cl::OptionCategory ViewOptions("View Options");
  66. static cl::opt<std::string> InputFilename(cl::Positional,
  67. cl::desc("<input file>"),
  68. cl::cat(ToolOptions), cl::init("-"));
  69. static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
  70. cl::init("-"), cl::cat(ToolOptions),
  71. cl::value_desc("filename"));
  72. static cl::opt<std::string>
  73. ArchName("march",
  74. cl::desc("Target architecture. "
  75. "See -version for available targets"),
  76. cl::cat(ToolOptions));
  77. static cl::opt<std::string>
  78. TripleName("mtriple",
  79. cl::desc("Target triple. See -version for available targets"),
  80. cl::cat(ToolOptions));
  81. static cl::opt<std::string>
  82. MCPU("mcpu",
  83. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  84. cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
  85. static cl::list<std::string>
  86. MATTRS("mattr", cl::CommaSeparated,
  87. cl::desc("Target specific attributes (-mattr=help for details)"),
  88. cl::value_desc("a1,+a2,-a3,..."), cl::cat(ToolOptions));
  89. static cl::opt<bool> PrintJson("json",
  90. cl::desc("Print the output in json format"),
  91. cl::cat(ToolOptions), cl::init(false));
  92. static cl::opt<int>
  93. OutputAsmVariant("output-asm-variant",
  94. cl::desc("Syntax variant to use for output printing"),
  95. cl::cat(ToolOptions), cl::init(-1));
  96. static cl::opt<bool>
  97. PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),
  98. cl::desc("Prefer hex format when printing immediate values"));
  99. static cl::opt<unsigned> Iterations("iterations",
  100. cl::desc("Number of iterations to run"),
  101. cl::cat(ToolOptions), cl::init(0));
  102. static cl::opt<unsigned>
  103. DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
  104. cl::cat(ToolOptions), cl::init(0));
  105. static cl::opt<unsigned>
  106. RegisterFileSize("register-file-size",
  107. cl::desc("Maximum number of physical registers which can "
  108. "be used for register mappings"),
  109. cl::cat(ToolOptions), cl::init(0));
  110. static cl::opt<unsigned>
  111. MicroOpQueue("micro-op-queue-size", cl::Hidden,
  112. cl::desc("Number of entries in the micro-op queue"),
  113. cl::cat(ToolOptions), cl::init(0));
  114. static cl::opt<unsigned>
  115. DecoderThroughput("decoder-throughput", cl::Hidden,
  116. cl::desc("Maximum throughput from the decoders "
  117. "(instructions per cycle)"),
  118. cl::cat(ToolOptions), cl::init(0));
  119. static cl::opt<bool>
  120. PrintRegisterFileStats("register-file-stats",
  121. cl::desc("Print register file statistics"),
  122. cl::cat(ViewOptions), cl::init(false));
  123. static cl::opt<bool> PrintDispatchStats("dispatch-stats",
  124. cl::desc("Print dispatch statistics"),
  125. cl::cat(ViewOptions), cl::init(false));
  126. static cl::opt<bool>
  127. PrintSummaryView("summary-view", cl::Hidden,
  128. cl::desc("Print summary view (enabled by default)"),
  129. cl::cat(ViewOptions), cl::init(true));
  130. static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
  131. cl::desc("Print scheduler statistics"),
  132. cl::cat(ViewOptions), cl::init(false));
  133. static cl::opt<bool>
  134. PrintRetireStats("retire-stats",
  135. cl::desc("Print retire control unit statistics"),
  136. cl::cat(ViewOptions), cl::init(false));
  137. static cl::opt<bool> PrintResourcePressureView(
  138. "resource-pressure",
  139. cl::desc("Print the resource pressure view (enabled by default)"),
  140. cl::cat(ViewOptions), cl::init(true));
  141. static cl::opt<bool> PrintTimelineView("timeline",
  142. cl::desc("Print the timeline view"),
  143. cl::cat(ViewOptions), cl::init(false));
  144. static cl::opt<unsigned> TimelineMaxIterations(
  145. "timeline-max-iterations",
  146. cl::desc("Maximum number of iterations to print in timeline view"),
  147. cl::cat(ViewOptions), cl::init(0));
  148. static cl::opt<unsigned>
  149. TimelineMaxCycles("timeline-max-cycles",
  150. cl::desc("Maximum number of cycles in the timeline view, "
  151. "or 0 for unlimited. Defaults to 80 cycles"),
  152. cl::cat(ViewOptions), cl::init(80));
  153. static cl::opt<bool>
  154. AssumeNoAlias("noalias",
  155. cl::desc("If set, assume that loads and stores do not alias"),
  156. cl::cat(ToolOptions), cl::init(true));
  157. static cl::opt<unsigned> LoadQueueSize("lqueue",
  158. cl::desc("Size of the load queue"),
  159. cl::cat(ToolOptions), cl::init(0));
  160. static cl::opt<unsigned> StoreQueueSize("squeue",
  161. cl::desc("Size of the store queue"),
  162. cl::cat(ToolOptions), cl::init(0));
  163. static cl::opt<bool>
  164. PrintInstructionTables("instruction-tables",
  165. cl::desc("Print instruction tables"),
  166. cl::cat(ToolOptions), cl::init(false));
  167. static cl::opt<bool> PrintInstructionInfoView(
  168. "instruction-info",
  169. cl::desc("Print the instruction info view (enabled by default)"),
  170. cl::cat(ViewOptions), cl::init(true));
  171. static cl::opt<bool> EnableAllStats("all-stats",
  172. cl::desc("Print all hardware statistics"),
  173. cl::cat(ViewOptions), cl::init(false));
  174. static cl::opt<bool>
  175. EnableAllViews("all-views",
  176. cl::desc("Print all views including hardware statistics"),
  177. cl::cat(ViewOptions), cl::init(false));
  178. static cl::opt<bool> EnableBottleneckAnalysis(
  179. "bottleneck-analysis",
  180. cl::desc("Enable bottleneck analysis (disabled by default)"),
  181. cl::cat(ViewOptions), cl::init(false));
  182. static cl::opt<bool> ShowEncoding(
  183. "show-encoding",
  184. cl::desc("Print encoding information in the instruction info view"),
  185. cl::cat(ViewOptions), cl::init(false));
  186. static cl::opt<bool> ShowBarriers(
  187. "show-barriers",
  188. cl::desc("Print memory barrier information in the instruction info view"),
  189. cl::cat(ViewOptions), cl::init(false));
  190. static cl::opt<bool> DisableCustomBehaviour(
  191. "disable-cb",
  192. cl::desc(
  193. "Disable custom behaviour (use the default class which does nothing)."),
  194. cl::cat(ViewOptions), cl::init(false));
  195. static cl::opt<bool> DisableInstrumentManager(
  196. "disable-im",
  197. cl::desc("Disable instrumentation manager (use the default class which "
  198. "ignores instruments.)."),
  199. cl::cat(ViewOptions), cl::init(false));
  200. namespace {
  201. const Target *getTarget(const char *ProgName) {
  202. if (TripleName.empty())
  203. TripleName = Triple::normalize(sys::getDefaultTargetTriple());
  204. Triple TheTriple(TripleName);
  205. // Get the target specific parser.
  206. std::string Error;
  207. const Target *TheTarget =
  208. TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
  209. if (!TheTarget) {
  210. errs() << ProgName << ": " << Error;
  211. return nullptr;
  212. }
  213. // Update TripleName with the updated triple from the target lookup.
  214. TripleName = TheTriple.str();
  215. // Return the found target.
  216. return TheTarget;
  217. }
  218. ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
  219. if (OutputFilename == "")
  220. OutputFilename = "-";
  221. std::error_code EC;
  222. auto Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
  223. sys::fs::OF_TextWithCRLF);
  224. if (!EC)
  225. return std::move(Out);
  226. return EC;
  227. }
  228. } // end of anonymous namespace
  229. static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
  230. if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
  231. O = Default.getValue();
  232. }
  233. static void processViewOptions(bool IsOutOfOrder) {
  234. if (!EnableAllViews.getNumOccurrences() &&
  235. !EnableAllStats.getNumOccurrences())
  236. return;
  237. if (EnableAllViews.getNumOccurrences()) {
  238. processOptionImpl(PrintSummaryView, EnableAllViews);
  239. if (IsOutOfOrder)
  240. processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
  241. processOptionImpl(PrintResourcePressureView, EnableAllViews);
  242. processOptionImpl(PrintTimelineView, EnableAllViews);
  243. processOptionImpl(PrintInstructionInfoView, EnableAllViews);
  244. }
  245. const cl::opt<bool> &Default =
  246. EnableAllViews.getPosition() < EnableAllStats.getPosition()
  247. ? EnableAllStats
  248. : EnableAllViews;
  249. processOptionImpl(PrintRegisterFileStats, Default);
  250. processOptionImpl(PrintDispatchStats, Default);
  251. processOptionImpl(PrintSchedulerStats, Default);
  252. if (IsOutOfOrder)
  253. processOptionImpl(PrintRetireStats, Default);
  254. }
  255. // Returns true on success.
  256. static bool runPipeline(mca::Pipeline &P) {
  257. // Handle pipeline errors here.
  258. Expected<unsigned> Cycles = P.run();
  259. if (!Cycles) {
  260. WithColor::error() << toString(Cycles.takeError());
  261. return false;
  262. }
  263. return true;
  264. }
  265. int main(int argc, char **argv) {
  266. InitLLVM X(argc, argv);
  267. // Initialize targets and assembly parsers.
  268. InitializeAllTargetInfos();
  269. InitializeAllTargetMCs();
  270. InitializeAllAsmParsers();
  271. InitializeAllTargetMCAs();
  272. // Register the Target and CPU printer for --version.
  273. cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
  274. // Enable printing of available targets when flag --version is specified.
  275. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  276. cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
  277. // Parse flags and initialize target options.
  278. cl::ParseCommandLineOptions(argc, argv,
  279. "llvm machine code performance analyzer.\n");
  280. // Get the target from the triple. If a triple is not specified, then select
  281. // the default triple for the host. If the triple doesn't correspond to any
  282. // registered target, then exit with an error message.
  283. const char *ProgName = argv[0];
  284. const Target *TheTarget = getTarget(ProgName);
  285. if (!TheTarget)
  286. return 1;
  287. // GetTarget() may replaced TripleName with a default triple.
  288. // For safety, reconstruct the Triple object.
  289. Triple TheTriple(TripleName);
  290. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  291. MemoryBuffer::getFileOrSTDIN(InputFilename);
  292. if (std::error_code EC = BufferPtr.getError()) {
  293. WithColor::error() << InputFilename << ": " << EC.message() << '\n';
  294. return 1;
  295. }
  296. if (MCPU == "native")
  297. MCPU = std::string(llvm::sys::getHostCPUName());
  298. // Package up features to be passed to target/subtarget
  299. std::string FeaturesStr;
  300. if (MATTRS.size()) {
  301. SubtargetFeatures Features;
  302. for (std::string &MAttr : MATTRS)
  303. Features.AddFeature(MAttr);
  304. FeaturesStr = Features.getString();
  305. }
  306. std::unique_ptr<MCSubtargetInfo> STI(
  307. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  308. assert(STI && "Unable to create subtarget info!");
  309. if (!STI->isCPUStringValid(MCPU))
  310. return 1;
  311. if (!STI->getSchedModel().hasInstrSchedModel()) {
  312. WithColor::error()
  313. << "unable to find instruction-level scheduling information for"
  314. << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
  315. << "'.\n";
  316. if (STI->getSchedModel().InstrItineraries)
  317. WithColor::note()
  318. << "cpu '" << MCPU << "' provides itineraries. However, "
  319. << "instruction itineraries are currently unsupported.\n";
  320. return 1;
  321. }
  322. // Apply overrides to llvm-mca specific options.
  323. bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
  324. processViewOptions(IsOutOfOrder);
  325. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  326. assert(MRI && "Unable to create target register info!");
  327. MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
  328. std::unique_ptr<MCAsmInfo> MAI(
  329. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  330. assert(MAI && "Unable to create target asm info!");
  331. SourceMgr SrcMgr;
  332. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  333. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  334. MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr);
  335. std::unique_ptr<MCObjectFileInfo> MOFI(
  336. TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
  337. Ctx.setObjectFileInfo(MOFI.get());
  338. std::unique_ptr<buffer_ostream> BOS;
  339. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  340. assert(MCII && "Unable to create instruction info!");
  341. std::unique_ptr<MCInstrAnalysis> MCIA(
  342. TheTarget->createMCInstrAnalysis(MCII.get()));
  343. // Need to initialize an MCInstPrinter as it is
  344. // required for initializing the MCTargetStreamer
  345. // which needs to happen within the CRG.parseAnalysisRegions() call below.
  346. // Without an MCTargetStreamer, certain assembly directives can trigger a
  347. // segfault. (For example, the .cv_fpo_proc directive on x86 will segfault if
  348. // we don't initialize the MCTargetStreamer.)
  349. unsigned IPtempOutputAsmVariant =
  350. OutputAsmVariant == -1 ? 0 : OutputAsmVariant;
  351. std::unique_ptr<MCInstPrinter> IPtemp(TheTarget->createMCInstPrinter(
  352. Triple(TripleName), IPtempOutputAsmVariant, *MAI, *MCII, *MRI));
  353. if (!IPtemp) {
  354. WithColor::error()
  355. << "unable to create instruction printer for target triple '"
  356. << TheTriple.normalize() << "' with assembly variant "
  357. << IPtempOutputAsmVariant << ".\n";
  358. return 1;
  359. }
  360. // Parse the input and create CodeRegions that llvm-mca can analyze.
  361. mca::AsmAnalysisRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI,
  362. *MCII);
  363. Expected<const mca::AnalysisRegions &> RegionsOrErr =
  364. CRG.parseAnalysisRegions(std::move(IPtemp));
  365. if (!RegionsOrErr) {
  366. if (auto Err =
  367. handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
  368. WithColor::error() << E.getMessage() << '\n';
  369. })) {
  370. // Default case.
  371. WithColor::error() << toString(std::move(Err)) << '\n';
  372. }
  373. return 1;
  374. }
  375. const mca::AnalysisRegions &Regions = *RegionsOrErr;
  376. // Early exit if errors were found by the code region parsing logic.
  377. if (!Regions.isValid())
  378. return 1;
  379. if (Regions.empty()) {
  380. WithColor::error() << "no assembly instructions found.\n";
  381. return 1;
  382. }
  383. std::unique_ptr<mca::InstrumentManager> IM;
  384. if (!DisableInstrumentManager) {
  385. IM = std::unique_ptr<mca::InstrumentManager>(
  386. TheTarget->createInstrumentManager(*STI, *MCII));
  387. }
  388. if (!IM) {
  389. // If the target doesn't have its own IM implemented (or the -disable-cb
  390. // flag is set) then we use the base class (which does nothing).
  391. IM = std::make_unique<mca::InstrumentManager>(*STI, *MCII);
  392. }
  393. // Parse the input and create InstrumentRegion that llvm-mca
  394. // can use to improve analysis.
  395. mca::AsmInstrumentRegionGenerator IRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI,
  396. *MCII, *IM);
  397. Expected<const mca::InstrumentRegions &> InstrumentRegionsOrErr =
  398. IRG.parseInstrumentRegions(std::move(IPtemp));
  399. if (!InstrumentRegionsOrErr) {
  400. if (auto Err = handleErrors(InstrumentRegionsOrErr.takeError(),
  401. [](const StringError &E) {
  402. WithColor::error() << E.getMessage() << '\n';
  403. })) {
  404. // Default case.
  405. WithColor::error() << toString(std::move(Err)) << '\n';
  406. }
  407. return 1;
  408. }
  409. const mca::InstrumentRegions &InstrumentRegions = *InstrumentRegionsOrErr;
  410. // Early exit if errors were found by the instrumentation parsing logic.
  411. if (!InstrumentRegions.isValid())
  412. return 1;
  413. // Now initialize the output file.
  414. auto OF = getOutputStream();
  415. if (std::error_code EC = OF.getError()) {
  416. WithColor::error() << EC.message() << '\n';
  417. return 1;
  418. }
  419. unsigned AssemblerDialect = CRG.getAssemblerDialect();
  420. if (OutputAsmVariant >= 0)
  421. AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
  422. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  423. Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
  424. if (!IP) {
  425. WithColor::error()
  426. << "unable to create instruction printer for target triple '"
  427. << TheTriple.normalize() << "' with assembly variant "
  428. << AssemblerDialect << ".\n";
  429. return 1;
  430. }
  431. // Set the display preference for hex vs. decimal immediates.
  432. IP->setPrintImmHex(PrintImmHex);
  433. std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
  434. const MCSchedModel &SM = STI->getSchedModel();
  435. std::unique_ptr<mca::InstrPostProcess> IPP;
  436. if (!DisableCustomBehaviour) {
  437. // TODO: It may be a good idea to separate CB and IPP so that they can
  438. // be used independently of each other. What I mean by this is to add
  439. // an extra command-line arg --disable-ipp so that CB and IPP can be
  440. // toggled without needing to toggle both of them together.
  441. IPP = std::unique_ptr<mca::InstrPostProcess>(
  442. TheTarget->createInstrPostProcess(*STI, *MCII));
  443. }
  444. if (!IPP) {
  445. // If the target doesn't have its own IPP implemented (or the -disable-cb
  446. // flag is set) then we use the base class (which does nothing).
  447. IPP = std::make_unique<mca::InstrPostProcess>(*STI, *MCII);
  448. }
  449. // Create an instruction builder.
  450. mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get(), *IM);
  451. // Create a context to control ownership of the pipeline hardware.
  452. mca::Context MCA(*MRI, *STI);
  453. mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
  454. RegisterFileSize, LoadQueueSize, StoreQueueSize,
  455. AssumeNoAlias, EnableBottleneckAnalysis);
  456. // Number each region in the sequence.
  457. unsigned RegionIdx = 0;
  458. std::unique_ptr<MCCodeEmitter> MCE(
  459. TheTarget->createMCCodeEmitter(*MCII, Ctx));
  460. assert(MCE && "Unable to create code emitter!");
  461. std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
  462. *STI, *MRI, mc::InitMCTargetOptionsFromFlags()));
  463. assert(MAB && "Unable to create asm backend!");
  464. json::Object JSONOutput;
  465. for (const std::unique_ptr<mca::AnalysisRegion> &Region : Regions) {
  466. // Skip empty code regions.
  467. if (Region->empty())
  468. continue;
  469. IB.clear();
  470. // Lower the MCInst sequence into an mca::Instruction sequence.
  471. ArrayRef<MCInst> Insts = Region->getInstructions();
  472. mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
  473. IPP->resetState();
  474. SmallVector<std::unique_ptr<mca::Instruction>> LoweredSequence;
  475. for (const MCInst &MCI : Insts) {
  476. SMLoc Loc = MCI.getLoc();
  477. const SmallVector<mca::SharedInstrument> Instruments =
  478. InstrumentRegions.getActiveInstruments(Loc);
  479. Expected<std::unique_ptr<mca::Instruction>> Inst =
  480. IB.createInstruction(MCI, Instruments);
  481. if (!Inst) {
  482. if (auto NewE = handleErrors(
  483. Inst.takeError(),
  484. [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
  485. std::string InstructionStr;
  486. raw_string_ostream SS(InstructionStr);
  487. WithColor::error() << IE.Message << '\n';
  488. IP->printInst(&IE.Inst, 0, "", *STI, SS);
  489. SS.flush();
  490. WithColor::note()
  491. << "instruction: " << InstructionStr << '\n';
  492. })) {
  493. // Default case.
  494. WithColor::error() << toString(std::move(NewE));
  495. }
  496. return 1;
  497. }
  498. IPP->postProcessInstruction(Inst.get(), MCI);
  499. LoweredSequence.emplace_back(std::move(Inst.get()));
  500. }
  501. mca::CircularSourceMgr S(LoweredSequence,
  502. PrintInstructionTables ? 1 : Iterations);
  503. if (PrintInstructionTables) {
  504. // Create a pipeline, stages, and a printer.
  505. auto P = std::make_unique<mca::Pipeline>();
  506. P->appendStage(std::make_unique<mca::EntryStage>(S));
  507. P->appendStage(std::make_unique<mca::InstructionTables>(SM));
  508. mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
  509. if (PrintJson) {
  510. Printer.addView(
  511. std::make_unique<mca::InstructionView>(*STI, *IP, Insts));
  512. }
  513. // Create the views for this pipeline, execute, and emit a report.
  514. if (PrintInstructionInfoView) {
  515. Printer.addView(std::make_unique<mca::InstructionInfoView>(
  516. *STI, *MCII, CE, ShowEncoding, Insts, *IP, LoweredSequence,
  517. ShowBarriers));
  518. }
  519. Printer.addView(
  520. std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
  521. if (!runPipeline(*P))
  522. return 1;
  523. if (PrintJson) {
  524. Printer.printReport(JSONOutput);
  525. } else {
  526. Printer.printReport(TOF->os());
  527. }
  528. ++RegionIdx;
  529. continue;
  530. }
  531. // Create the CustomBehaviour object for enforcing Target Specific
  532. // behaviours and dependencies that aren't expressed well enough
  533. // in the tablegen. CB cannot depend on the list of MCInst or
  534. // the source code (but it can depend on the list of
  535. // mca::Instruction or any objects that can be reconstructed
  536. // from the target information).
  537. std::unique_ptr<mca::CustomBehaviour> CB;
  538. if (!DisableCustomBehaviour)
  539. CB = std::unique_ptr<mca::CustomBehaviour>(
  540. TheTarget->createCustomBehaviour(*STI, S, *MCII));
  541. if (!CB)
  542. // If the target doesn't have its own CB implemented (or the -disable-cb
  543. // flag is set) then we use the base class (which does nothing).
  544. CB = std::make_unique<mca::CustomBehaviour>(*STI, S, *MCII);
  545. // Create a basic pipeline simulating an out-of-order backend.
  546. auto P = MCA.createDefaultPipeline(PO, S, *CB);
  547. mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
  548. // Targets can define their own custom Views that exist within their
  549. // /lib/Target/ directory so that the View can utilize their CustomBehaviour
  550. // or other backend symbols / functionality that are not already exposed
  551. // through one of the MC-layer classes. These Views will be initialized
  552. // using the CustomBehaviour::getViews() variants.
  553. // If a target makes a custom View that does not depend on their target
  554. // CB or their backend, they should put the View within
  555. // /tools/llvm-mca/Views/ instead.
  556. if (!DisableCustomBehaviour) {
  557. std::vector<std::unique_ptr<mca::View>> CBViews =
  558. CB->getStartViews(*IP, Insts);
  559. for (auto &CBView : CBViews)
  560. Printer.addView(std::move(CBView));
  561. }
  562. // When we output JSON, we add a view that contains the instructions
  563. // and CPU resource information.
  564. if (PrintJson) {
  565. auto IV = std::make_unique<mca::InstructionView>(*STI, *IP, Insts);
  566. Printer.addView(std::move(IV));
  567. }
  568. if (PrintSummaryView)
  569. Printer.addView(
  570. std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
  571. if (EnableBottleneckAnalysis) {
  572. if (!IsOutOfOrder) {
  573. WithColor::warning()
  574. << "bottleneck analysis is not supported for in-order CPU '" << MCPU
  575. << "'.\n";
  576. }
  577. Printer.addView(std::make_unique<mca::BottleneckAnalysis>(
  578. *STI, *IP, Insts, S.getNumIterations()));
  579. }
  580. if (PrintInstructionInfoView)
  581. Printer.addView(std::make_unique<mca::InstructionInfoView>(
  582. *STI, *MCII, CE, ShowEncoding, Insts, *IP, LoweredSequence,
  583. ShowBarriers));
  584. // Fetch custom Views that are to be placed after the InstructionInfoView.
  585. // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
  586. // for more info.
  587. if (!DisableCustomBehaviour) {
  588. std::vector<std::unique_ptr<mca::View>> CBViews =
  589. CB->getPostInstrInfoViews(*IP, Insts);
  590. for (auto &CBView : CBViews)
  591. Printer.addView(std::move(CBView));
  592. }
  593. if (PrintDispatchStats)
  594. Printer.addView(std::make_unique<mca::DispatchStatistics>());
  595. if (PrintSchedulerStats)
  596. Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));
  597. if (PrintRetireStats)
  598. Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));
  599. if (PrintRegisterFileStats)
  600. Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));
  601. if (PrintResourcePressureView)
  602. Printer.addView(
  603. std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
  604. if (PrintTimelineView) {
  605. unsigned TimelineIterations =
  606. TimelineMaxIterations ? TimelineMaxIterations : 10;
  607. Printer.addView(std::make_unique<mca::TimelineView>(
  608. *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
  609. TimelineMaxCycles));
  610. }
  611. // Fetch custom Views that are to be placed after all other Views.
  612. // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
  613. // for more info.
  614. if (!DisableCustomBehaviour) {
  615. std::vector<std::unique_ptr<mca::View>> CBViews =
  616. CB->getEndViews(*IP, Insts);
  617. for (auto &CBView : CBViews)
  618. Printer.addView(std::move(CBView));
  619. }
  620. if (!runPipeline(*P))
  621. return 1;
  622. if (PrintJson) {
  623. Printer.printReport(JSONOutput);
  624. } else {
  625. Printer.printReport(TOF->os());
  626. }
  627. ++RegionIdx;
  628. }
  629. if (PrintJson)
  630. TOF->os() << formatv("{0:2}", json::Value(std::move(JSONOutput))) << "\n";
  631. TOF->keep();
  632. return 0;
  633. }