llvm-mca.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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/MCAsmInfo.h"
  35. #include "llvm/MC/MCContext.h"
  36. #include "llvm/MC/MCObjectFileInfo.h"
  37. #include "llvm/MC/MCRegisterInfo.h"
  38. #include "llvm/MCA/Context.h"
  39. #include "llvm/MCA/Pipeline.h"
  40. #include "llvm/MCA/Stages/EntryStage.h"
  41. #include "llvm/MCA/Stages/InstructionTables.h"
  42. #include "llvm/MCA/Support.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/ErrorOr.h"
  46. #include "llvm/Support/FileSystem.h"
  47. #include "llvm/Support/Host.h"
  48. #include "llvm/Support/InitLLVM.h"
  49. #include "llvm/Support/MemoryBuffer.h"
  50. #include "llvm/Support/SourceMgr.h"
  51. #include "llvm/Support/TargetRegistry.h"
  52. #include "llvm/Support/TargetSelect.h"
  53. #include "llvm/Support/ToolOutputFile.h"
  54. #include "llvm/Support/WithColor.h"
  55. using namespace llvm;
  56. static cl::OptionCategory ToolOptions("Tool Options");
  57. static cl::OptionCategory ViewOptions("View Options");
  58. static cl::opt<std::string> InputFilename(cl::Positional,
  59. cl::desc("<input file>"),
  60. cl::cat(ToolOptions), cl::init("-"));
  61. static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
  62. cl::init("-"), cl::cat(ToolOptions),
  63. cl::value_desc("filename"));
  64. static cl::opt<std::string>
  65. ArchName("march",
  66. cl::desc("Target architecture. "
  67. "See -version for available targets"),
  68. cl::cat(ToolOptions));
  69. static cl::opt<std::string>
  70. TripleName("mtriple",
  71. cl::desc("Target triple. See -version for available targets"),
  72. cl::cat(ToolOptions));
  73. static cl::opt<std::string>
  74. MCPU("mcpu",
  75. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  76. cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
  77. static cl::opt<int>
  78. OutputAsmVariant("output-asm-variant",
  79. cl::desc("Syntax variant to use for output printing"),
  80. cl::cat(ToolOptions), cl::init(-1));
  81. static cl::opt<bool>
  82. PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),
  83. cl::desc("Prefer hex format when printing immediate values"));
  84. static cl::opt<unsigned> Iterations("iterations",
  85. cl::desc("Number of iterations to run"),
  86. cl::cat(ToolOptions), cl::init(0));
  87. static cl::opt<unsigned>
  88. DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
  89. cl::cat(ToolOptions), cl::init(0));
  90. static cl::opt<unsigned>
  91. RegisterFileSize("register-file-size",
  92. cl::desc("Maximum number of physical registers which can "
  93. "be used for register mappings"),
  94. cl::cat(ToolOptions), cl::init(0));
  95. static cl::opt<unsigned>
  96. MicroOpQueue("micro-op-queue-size", cl::Hidden,
  97. cl::desc("Number of entries in the micro-op queue"),
  98. cl::cat(ToolOptions), cl::init(0));
  99. static cl::opt<unsigned>
  100. DecoderThroughput("decoder-throughput", cl::Hidden,
  101. cl::desc("Maximum throughput from the decoders "
  102. "(instructions per cycle)"),
  103. cl::cat(ToolOptions), cl::init(0));
  104. static cl::opt<bool>
  105. PrintRegisterFileStats("register-file-stats",
  106. cl::desc("Print register file statistics"),
  107. cl::cat(ViewOptions), cl::init(false));
  108. static cl::opt<bool> PrintDispatchStats("dispatch-stats",
  109. cl::desc("Print dispatch statistics"),
  110. cl::cat(ViewOptions), cl::init(false));
  111. static cl::opt<bool>
  112. PrintSummaryView("summary-view", cl::Hidden,
  113. cl::desc("Print summary view (enabled by default)"),
  114. cl::cat(ViewOptions), cl::init(true));
  115. static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
  116. cl::desc("Print scheduler statistics"),
  117. cl::cat(ViewOptions), cl::init(false));
  118. static cl::opt<bool>
  119. PrintRetireStats("retire-stats",
  120. cl::desc("Print retire control unit statistics"),
  121. cl::cat(ViewOptions), cl::init(false));
  122. static cl::opt<bool> PrintResourcePressureView(
  123. "resource-pressure",
  124. cl::desc("Print the resource pressure view (enabled by default)"),
  125. cl::cat(ViewOptions), cl::init(true));
  126. static cl::opt<bool> PrintTimelineView("timeline",
  127. cl::desc("Print the timeline view"),
  128. cl::cat(ViewOptions), cl::init(false));
  129. static cl::opt<unsigned> TimelineMaxIterations(
  130. "timeline-max-iterations",
  131. cl::desc("Maximum number of iterations to print in timeline view"),
  132. cl::cat(ViewOptions), cl::init(0));
  133. static cl::opt<unsigned> TimelineMaxCycles(
  134. "timeline-max-cycles",
  135. cl::desc(
  136. "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
  137. cl::cat(ViewOptions), cl::init(80));
  138. static cl::opt<bool>
  139. AssumeNoAlias("noalias",
  140. cl::desc("If set, assume that loads and stores do not alias"),
  141. cl::cat(ToolOptions), cl::init(true));
  142. static cl::opt<unsigned> LoadQueueSize("lqueue",
  143. cl::desc("Size of the load queue"),
  144. cl::cat(ToolOptions), cl::init(0));
  145. static cl::opt<unsigned> StoreQueueSize("squeue",
  146. cl::desc("Size of the store queue"),
  147. cl::cat(ToolOptions), cl::init(0));
  148. static cl::opt<bool>
  149. PrintInstructionTables("instruction-tables",
  150. cl::desc("Print instruction tables"),
  151. cl::cat(ToolOptions), cl::init(false));
  152. static cl::opt<bool> PrintInstructionInfoView(
  153. "instruction-info",
  154. cl::desc("Print the instruction info view (enabled by default)"),
  155. cl::cat(ViewOptions), cl::init(true));
  156. static cl::opt<bool> EnableAllStats("all-stats",
  157. cl::desc("Print all hardware statistics"),
  158. cl::cat(ViewOptions), cl::init(false));
  159. static cl::opt<bool>
  160. EnableAllViews("all-views",
  161. cl::desc("Print all views including hardware statistics"),
  162. cl::cat(ViewOptions), cl::init(false));
  163. static cl::opt<bool> EnableBottleneckAnalysis(
  164. "bottleneck-analysis",
  165. cl::desc("Enable bottleneck analysis (disabled by default)"),
  166. cl::cat(ViewOptions), cl::init(false));
  167. namespace {
  168. const Target *getTarget(const char *ProgName) {
  169. if (TripleName.empty())
  170. TripleName = Triple::normalize(sys::getDefaultTargetTriple());
  171. Triple TheTriple(TripleName);
  172. // Get the target specific parser.
  173. std::string Error;
  174. const Target *TheTarget =
  175. TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
  176. if (!TheTarget) {
  177. errs() << ProgName << ": " << Error;
  178. return nullptr;
  179. }
  180. // Return the found target.
  181. return TheTarget;
  182. }
  183. ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
  184. if (OutputFilename == "")
  185. OutputFilename = "-";
  186. std::error_code EC;
  187. auto Out =
  188. llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_None);
  189. if (!EC)
  190. return std::move(Out);
  191. return EC;
  192. }
  193. } // end of anonymous namespace
  194. static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
  195. if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
  196. O = Default.getValue();
  197. }
  198. static void processViewOptions() {
  199. if (!EnableAllViews.getNumOccurrences() &&
  200. !EnableAllStats.getNumOccurrences())
  201. return;
  202. if (EnableAllViews.getNumOccurrences()) {
  203. processOptionImpl(PrintSummaryView, EnableAllViews);
  204. processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
  205. processOptionImpl(PrintResourcePressureView, EnableAllViews);
  206. processOptionImpl(PrintTimelineView, EnableAllViews);
  207. processOptionImpl(PrintInstructionInfoView, EnableAllViews);
  208. }
  209. const cl::opt<bool> &Default =
  210. EnableAllViews.getPosition() < EnableAllStats.getPosition()
  211. ? EnableAllStats
  212. : EnableAllViews;
  213. processOptionImpl(PrintRegisterFileStats, Default);
  214. processOptionImpl(PrintDispatchStats, Default);
  215. processOptionImpl(PrintSchedulerStats, Default);
  216. processOptionImpl(PrintRetireStats, Default);
  217. }
  218. // Returns true on success.
  219. static bool runPipeline(mca::Pipeline &P) {
  220. // Handle pipeline errors here.
  221. Expected<unsigned> Cycles = P.run();
  222. if (!Cycles) {
  223. WithColor::error() << toString(Cycles.takeError());
  224. return false;
  225. }
  226. return true;
  227. }
  228. int main(int argc, char **argv) {
  229. InitLLVM X(argc, argv);
  230. // Initialize targets and assembly parsers.
  231. InitializeAllTargetInfos();
  232. InitializeAllTargetMCs();
  233. InitializeAllAsmParsers();
  234. // Enable printing of available targets when flag --version is specified.
  235. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  236. cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
  237. // Parse flags and initialize target options.
  238. cl::ParseCommandLineOptions(argc, argv,
  239. "llvm machine code performance analyzer.\n");
  240. // Get the target from the triple. If a triple is not specified, then select
  241. // the default triple for the host. If the triple doesn't correspond to any
  242. // registered target, then exit with an error message.
  243. const char *ProgName = argv[0];
  244. const Target *TheTarget = getTarget(ProgName);
  245. if (!TheTarget)
  246. return 1;
  247. // GetTarget() may replaced TripleName with a default triple.
  248. // For safety, reconstruct the Triple object.
  249. Triple TheTriple(TripleName);
  250. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  251. MemoryBuffer::getFileOrSTDIN(InputFilename);
  252. if (std::error_code EC = BufferPtr.getError()) {
  253. WithColor::error() << InputFilename << ": " << EC.message() << '\n';
  254. return 1;
  255. }
  256. // Apply overrides to llvm-mca specific options.
  257. processViewOptions();
  258. SourceMgr SrcMgr;
  259. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  260. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  261. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  262. assert(MRI && "Unable to create target register info!");
  263. std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
  264. assert(MAI && "Unable to create target asm info!");
  265. MCObjectFileInfo MOFI;
  266. MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
  267. MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
  268. std::unique_ptr<buffer_ostream> BOS;
  269. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  270. std::unique_ptr<MCInstrAnalysis> MCIA(
  271. TheTarget->createMCInstrAnalysis(MCII.get()));
  272. if (!MCPU.compare("native"))
  273. MCPU = llvm::sys::getHostCPUName();
  274. std::unique_ptr<MCSubtargetInfo> STI(
  275. TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
  276. if (!STI->isCPUStringValid(MCPU))
  277. return 1;
  278. if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
  279. WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
  280. << "' is an in-order cpu.\n";
  281. return 1;
  282. }
  283. if (!STI->getSchedModel().hasInstrSchedModel()) {
  284. WithColor::error()
  285. << "unable to find instruction-level scheduling information for"
  286. << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
  287. << "'.\n";
  288. if (STI->getSchedModel().InstrItineraries)
  289. WithColor::note()
  290. << "cpu '" << MCPU << "' provides itineraries. However, "
  291. << "instruction itineraries are currently unsupported.\n";
  292. return 1;
  293. }
  294. // Parse the input and create CodeRegions that llvm-mca can analyze.
  295. mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
  296. Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
  297. if (!RegionsOrErr) {
  298. if (auto Err =
  299. handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
  300. WithColor::error() << E.getMessage() << '\n';
  301. })) {
  302. // Default case.
  303. WithColor::error() << toString(std::move(Err)) << '\n';
  304. }
  305. return 1;
  306. }
  307. const mca::CodeRegions &Regions = *RegionsOrErr;
  308. // Early exit if errors were found by the code region parsing logic.
  309. if (!Regions.isValid())
  310. return 1;
  311. if (Regions.empty()) {
  312. WithColor::error() << "no assembly instructions found.\n";
  313. return 1;
  314. }
  315. // Now initialize the output file.
  316. auto OF = getOutputStream();
  317. if (std::error_code EC = OF.getError()) {
  318. WithColor::error() << EC.message() << '\n';
  319. return 1;
  320. }
  321. unsigned AssemblerDialect = CRG.getAssemblerDialect();
  322. if (OutputAsmVariant >= 0)
  323. AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
  324. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  325. Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
  326. if (!IP) {
  327. WithColor::error()
  328. << "unable to create instruction printer for target triple '"
  329. << TheTriple.normalize() << "' with assembly variant "
  330. << AssemblerDialect << ".\n";
  331. return 1;
  332. }
  333. // Set the display preference for hex vs. decimal immediates.
  334. IP->setPrintImmHex(PrintImmHex);
  335. std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
  336. const MCSchedModel &SM = STI->getSchedModel();
  337. // Create an instruction builder.
  338. mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
  339. // Create a context to control ownership of the pipeline hardware.
  340. mca::Context MCA(*MRI, *STI);
  341. mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
  342. RegisterFileSize, LoadQueueSize, StoreQueueSize,
  343. AssumeNoAlias, EnableBottleneckAnalysis);
  344. // Number each region in the sequence.
  345. unsigned RegionIdx = 0;
  346. for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
  347. // Skip empty code regions.
  348. if (Region->empty())
  349. continue;
  350. // Don't print the header of this region if it is the default region, and
  351. // it doesn't have an end location.
  352. if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
  353. TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
  354. StringRef Desc = Region->getDescription();
  355. if (!Desc.empty())
  356. TOF->os() << " - " << Desc;
  357. TOF->os() << "\n\n";
  358. }
  359. // Lower the MCInst sequence into an mca::Instruction sequence.
  360. ArrayRef<MCInst> Insts = Region->getInstructions();
  361. std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
  362. for (const MCInst &MCI : Insts) {
  363. Expected<std::unique_ptr<mca::Instruction>> Inst =
  364. IB.createInstruction(MCI);
  365. if (!Inst) {
  366. if (auto NewE = handleErrors(
  367. Inst.takeError(),
  368. [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
  369. std::string InstructionStr;
  370. raw_string_ostream SS(InstructionStr);
  371. WithColor::error() << IE.Message << '\n';
  372. IP->printInst(&IE.Inst, SS, "", *STI);
  373. SS.flush();
  374. WithColor::note()
  375. << "instruction: " << InstructionStr << '\n';
  376. })) {
  377. // Default case.
  378. WithColor::error() << toString(std::move(NewE));
  379. }
  380. return 1;
  381. }
  382. LoweredSequence.emplace_back(std::move(Inst.get()));
  383. }
  384. mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
  385. if (PrintInstructionTables) {
  386. // Create a pipeline, stages, and a printer.
  387. auto P = llvm::make_unique<mca::Pipeline>();
  388. P->appendStage(llvm::make_unique<mca::EntryStage>(S));
  389. P->appendStage(llvm::make_unique<mca::InstructionTables>(SM));
  390. mca::PipelinePrinter Printer(*P);
  391. // Create the views for this pipeline, execute, and emit a report.
  392. if (PrintInstructionInfoView) {
  393. Printer.addView(llvm::make_unique<mca::InstructionInfoView>(
  394. *STI, *MCII, Insts, *IP));
  395. }
  396. Printer.addView(
  397. llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
  398. if (!runPipeline(*P))
  399. return 1;
  400. Printer.printReport(TOF->os());
  401. continue;
  402. }
  403. // Create a basic pipeline simulating an out-of-order backend.
  404. auto P = MCA.createDefaultPipeline(PO, IB, S);
  405. mca::PipelinePrinter Printer(*P);
  406. if (PrintSummaryView)
  407. Printer.addView(
  408. llvm::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
  409. if (EnableBottleneckAnalysis) {
  410. Printer.addView(llvm::make_unique<mca::BottleneckAnalysis>(
  411. *STI, *IP, Insts, S.getNumIterations()));
  412. }
  413. if (PrintInstructionInfoView)
  414. Printer.addView(
  415. llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP));
  416. if (PrintDispatchStats)
  417. Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
  418. if (PrintSchedulerStats)
  419. Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
  420. if (PrintRetireStats)
  421. Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM));
  422. if (PrintRegisterFileStats)
  423. Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
  424. if (PrintResourcePressureView)
  425. Printer.addView(
  426. llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
  427. if (PrintTimelineView) {
  428. unsigned TimelineIterations =
  429. TimelineMaxIterations ? TimelineMaxIterations : 10;
  430. Printer.addView(llvm::make_unique<mca::TimelineView>(
  431. *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
  432. TimelineMaxCycles));
  433. }
  434. if (!runPipeline(*P))
  435. return 1;
  436. Printer.printReport(TOF->os());
  437. // Clear the InstrBuilder internal state in preparation for another round.
  438. IB.clear();
  439. }
  440. TOF->keep();
  441. return 0;
  442. }