llvm-mca.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This utility is a simple driver that allows static performance analysis on
  11. // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
  12. //
  13. // llvm-mca [options] <file-name>
  14. // -march <type>
  15. // -mcpu <cpu>
  16. // -o <file>
  17. //
  18. // The target defaults to the host target.
  19. // The cpu defaults to the 'native' host cpu.
  20. // The output defaults to standard output.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "CodeRegion.h"
  24. #include "PipelinePrinter.h"
  25. #include "Stages/FetchStage.h"
  26. #include "Stages/InstructionTables.h"
  27. #include "Views/DispatchStatistics.h"
  28. #include "Views/InstructionInfoView.h"
  29. #include "Views/RegisterFileStatistics.h"
  30. #include "Views/ResourcePressureView.h"
  31. #include "Views/RetireControlUnitStatistics.h"
  32. #include "Views/SchedulerStatistics.h"
  33. #include "Views/SummaryView.h"
  34. #include "Views/TimelineView.h"
  35. #include "include/Context.h"
  36. #include "include/Pipeline.h"
  37. #include "llvm/MC/MCAsmInfo.h"
  38. #include "llvm/MC/MCContext.h"
  39. #include "llvm/MC/MCObjectFileInfo.h"
  40. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  41. #include "llvm/MC/MCRegisterInfo.h"
  42. #include "llvm/MC/MCStreamer.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", cl::desc("Target arch to assemble for, "
  66. "see -version for available targets"),
  67. cl::cat(ToolOptions));
  68. static cl::opt<std::string>
  69. TripleName("mtriple", cl::desc("Target triple to assemble for, "
  70. "see -version for available targets"),
  71. cl::cat(ToolOptions));
  72. static cl::opt<std::string>
  73. MCPU("mcpu",
  74. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  75. cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
  76. static cl::opt<int>
  77. OutputAsmVariant("output-asm-variant",
  78. cl::desc("Syntax variant to use for output printing"),
  79. cl::cat(ToolOptions), cl::init(-1));
  80. static cl::opt<unsigned> Iterations("iterations",
  81. cl::desc("Number of iterations to run"),
  82. cl::cat(ToolOptions), cl::init(0));
  83. static cl::opt<unsigned>
  84. DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
  85. cl::cat(ToolOptions), cl::init(0));
  86. static cl::opt<unsigned>
  87. RegisterFileSize("register-file-size",
  88. cl::desc("Maximum number of physical registers which can "
  89. "be used for register mappings"),
  90. cl::cat(ToolOptions), cl::init(0));
  91. static cl::opt<bool>
  92. PrintRegisterFileStats("register-file-stats",
  93. cl::desc("Print register file statistics"),
  94. cl::cat(ViewOptions), cl::init(false));
  95. static cl::opt<bool> PrintDispatchStats("dispatch-stats",
  96. cl::desc("Print dispatch statistics"),
  97. cl::cat(ViewOptions), cl::init(false));
  98. static cl::opt<bool>
  99. PrintSummaryView("summary-view", cl::Hidden,
  100. cl::desc("Print summary view (enabled by default)"),
  101. cl::cat(ViewOptions), cl::init(true));
  102. static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
  103. cl::desc("Print scheduler statistics"),
  104. cl::cat(ViewOptions), cl::init(false));
  105. static cl::opt<bool>
  106. PrintRetireStats("retire-stats",
  107. cl::desc("Print retire control unit statistics"),
  108. cl::cat(ViewOptions), cl::init(false));
  109. static cl::opt<bool> PrintResourcePressureView(
  110. "resource-pressure",
  111. cl::desc("Print the resource pressure view (enabled by default)"),
  112. cl::cat(ViewOptions), cl::init(true));
  113. static cl::opt<bool> PrintTimelineView("timeline",
  114. cl::desc("Print the timeline view"),
  115. cl::cat(ViewOptions), cl::init(false));
  116. static cl::opt<unsigned> TimelineMaxIterations(
  117. "timeline-max-iterations",
  118. cl::desc("Maximum number of iterations to print in timeline view"),
  119. cl::cat(ViewOptions), cl::init(0));
  120. static cl::opt<unsigned> TimelineMaxCycles(
  121. "timeline-max-cycles",
  122. cl::desc(
  123. "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
  124. cl::cat(ViewOptions), cl::init(80));
  125. static cl::opt<bool>
  126. AssumeNoAlias("noalias",
  127. cl::desc("If set, assume that loads and stores do not alias"),
  128. cl::cat(ToolOptions), cl::init(true));
  129. static cl::opt<unsigned>
  130. LoadQueueSize("lqueue",
  131. cl::desc("Size of the load queue (unbound by default)"),
  132. cl::cat(ToolOptions), cl::init(0));
  133. static cl::opt<unsigned>
  134. StoreQueueSize("squeue",
  135. cl::desc("Size of the store queue (unbound by default)"),
  136. cl::cat(ToolOptions), cl::init(0));
  137. static cl::opt<bool>
  138. PrintInstructionTables("instruction-tables",
  139. cl::desc("Print instruction tables"),
  140. cl::cat(ToolOptions), cl::init(false));
  141. static cl::opt<bool> PrintInstructionInfoView(
  142. "instruction-info",
  143. cl::desc("Print the instruction info view (enabled by default)"),
  144. cl::cat(ViewOptions), cl::init(true));
  145. static cl::opt<bool> EnableAllStats("all-stats",
  146. cl::desc("Print all hardware statistics"),
  147. cl::cat(ViewOptions), cl::init(false));
  148. static cl::opt<bool>
  149. EnableAllViews("all-views",
  150. cl::desc("Print all views including hardware statistics"),
  151. cl::cat(ViewOptions), cl::init(false));
  152. namespace {
  153. const Target *getTarget(const char *ProgName) {
  154. if (TripleName.empty())
  155. TripleName = Triple::normalize(sys::getDefaultTargetTriple());
  156. Triple TheTriple(TripleName);
  157. // Get the target specific parser.
  158. std::string Error;
  159. const Target *TheTarget =
  160. TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
  161. if (!TheTarget) {
  162. errs() << ProgName << ": " << Error;
  163. return nullptr;
  164. }
  165. // Return the found target.
  166. return TheTarget;
  167. }
  168. // A comment consumer that parses strings.
  169. // The only valid tokens are strings.
  170. class MCACommentConsumer : public AsmCommentConsumer {
  171. public:
  172. mca::CodeRegions &Regions;
  173. MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
  174. void HandleComment(SMLoc Loc, StringRef CommentText) override {
  175. // Skip empty comments.
  176. StringRef Comment(CommentText);
  177. if (Comment.empty())
  178. return;
  179. // Skip spaces and tabs
  180. unsigned Position = Comment.find_first_not_of(" \t");
  181. if (Position >= Comment.size())
  182. // We reached the end of the comment. Bail out.
  183. return;
  184. Comment = Comment.drop_front(Position);
  185. if (Comment.consume_front("LLVM-MCA-END")) {
  186. Regions.endRegion(Loc);
  187. return;
  188. }
  189. // Now try to parse string LLVM-MCA-BEGIN
  190. if (!Comment.consume_front("LLVM-MCA-BEGIN"))
  191. return;
  192. // Skip spaces and tabs
  193. Position = Comment.find_first_not_of(" \t");
  194. if (Position < Comment.size())
  195. Comment = Comment.drop_front(Position);
  196. // Use the rest of the string as a descriptor for this code snippet.
  197. Regions.beginRegion(Comment, Loc);
  198. }
  199. };
  200. int AssembleInput(MCAsmParser &Parser, const Target *TheTarget,
  201. MCSubtargetInfo &STI, MCInstrInfo &MCII,
  202. MCTargetOptions &MCOptions) {
  203. std::unique_ptr<MCTargetAsmParser> TAP(
  204. TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
  205. if (!TAP) {
  206. WithColor::error() << "this target does not support assembly parsing.\n";
  207. return 1;
  208. }
  209. Parser.setTargetParser(*TAP);
  210. return Parser.Run(false);
  211. }
  212. ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
  213. if (OutputFilename == "")
  214. OutputFilename = "-";
  215. std::error_code EC;
  216. auto Out =
  217. llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
  218. if (!EC)
  219. return std::move(Out);
  220. return EC;
  221. }
  222. class MCStreamerWrapper final : public MCStreamer {
  223. mca::CodeRegions &Regions;
  224. public:
  225. MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
  226. : MCStreamer(Context), Regions(R) {}
  227. // We only want to intercept the emission of new instructions.
  228. virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
  229. bool /* unused */) override {
  230. Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
  231. }
  232. bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
  233. return true;
  234. }
  235. void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  236. unsigned ByteAlignment) override {}
  237. void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
  238. uint64_t Size = 0, unsigned ByteAlignment = 0,
  239. SMLoc Loc = SMLoc()) override {}
  240. void EmitGPRel32Value(const MCExpr *Value) override {}
  241. void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
  242. void EmitCOFFSymbolStorageClass(int StorageClass) override {}
  243. void EmitCOFFSymbolType(int Type) override {}
  244. void EndCOFFSymbolDef() override {}
  245. const std::vector<std::unique_ptr<const MCInst>> &
  246. GetInstructionSequence(unsigned Index) const {
  247. return Regions.getInstructionSequence(Index);
  248. }
  249. };
  250. } // end of anonymous namespace
  251. static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
  252. if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
  253. O = Default.getValue();
  254. }
  255. static void processViewOptions() {
  256. if (!EnableAllViews.getNumOccurrences() &&
  257. !EnableAllStats.getNumOccurrences())
  258. return;
  259. if (EnableAllViews.getNumOccurrences()) {
  260. processOptionImpl(PrintSummaryView, EnableAllViews);
  261. processOptionImpl(PrintResourcePressureView, EnableAllViews);
  262. processOptionImpl(PrintTimelineView, EnableAllViews);
  263. processOptionImpl(PrintInstructionInfoView, EnableAllViews);
  264. }
  265. const cl::opt<bool> &Default =
  266. EnableAllViews.getPosition() < EnableAllStats.getPosition()
  267. ? EnableAllStats
  268. : EnableAllViews;
  269. processOptionImpl(PrintRegisterFileStats, Default);
  270. processOptionImpl(PrintDispatchStats, Default);
  271. processOptionImpl(PrintSchedulerStats, Default);
  272. processOptionImpl(PrintRetireStats, Default);
  273. }
  274. int main(int argc, char **argv) {
  275. InitLLVM X(argc, argv);
  276. // Initialize targets and assembly parsers.
  277. llvm::InitializeAllTargetInfos();
  278. llvm::InitializeAllTargetMCs();
  279. llvm::InitializeAllAsmParsers();
  280. // Enable printing of available targets when flag --version is specified.
  281. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  282. cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
  283. // Parse flags and initialize target options.
  284. cl::ParseCommandLineOptions(argc, argv,
  285. "llvm machine code performance analyzer.\n");
  286. MCTargetOptions MCOptions;
  287. MCOptions.PreserveAsmComments = false;
  288. // Get the target from the triple. If a triple is not specified, then select
  289. // the default triple for the host. If the triple doesn't correspond to any
  290. // registered target, then exit with an error message.
  291. const char *ProgName = argv[0];
  292. const Target *TheTarget = getTarget(ProgName);
  293. if (!TheTarget)
  294. return 1;
  295. // GetTarget() may replaced TripleName with a default triple.
  296. // For safety, reconstruct the Triple object.
  297. Triple TheTriple(TripleName);
  298. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  299. MemoryBuffer::getFileOrSTDIN(InputFilename);
  300. if (std::error_code EC = BufferPtr.getError()) {
  301. WithColor::error() << InputFilename << ": " << EC.message() << '\n';
  302. return 1;
  303. }
  304. // Apply overrides to llvm-mca specific options.
  305. processViewOptions();
  306. SourceMgr SrcMgr;
  307. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  308. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  309. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  310. assert(MRI && "Unable to create target register info!");
  311. std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
  312. assert(MAI && "Unable to create target asm info!");
  313. MCObjectFileInfo MOFI;
  314. MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
  315. MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
  316. std::unique_ptr<buffer_ostream> BOS;
  317. mca::CodeRegions Regions(SrcMgr);
  318. MCStreamerWrapper Str(Ctx, Regions);
  319. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  320. std::unique_ptr<MCInstrAnalysis> MCIA(
  321. TheTarget->createMCInstrAnalysis(MCII.get()));
  322. if (!MCPU.compare("native"))
  323. MCPU = llvm::sys::getHostCPUName();
  324. std::unique_ptr<MCSubtargetInfo> STI(
  325. TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
  326. if (!STI->isCPUStringValid(MCPU))
  327. return 1;
  328. if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
  329. WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
  330. << "' is an in-order cpu.\n";
  331. return 1;
  332. }
  333. if (!STI->getSchedModel().hasInstrSchedModel()) {
  334. WithColor::error()
  335. << "unable to find instruction-level scheduling information for"
  336. << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
  337. << "'.\n";
  338. if (STI->getSchedModel().InstrItineraries)
  339. WithColor::note()
  340. << "cpu '" << MCPU << "' provides itineraries. However, "
  341. << "instruction itineraries are currently unsupported.\n";
  342. return 1;
  343. }
  344. std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
  345. MCAsmLexer &Lexer = P->getLexer();
  346. MCACommentConsumer CC(Regions);
  347. Lexer.setCommentConsumer(&CC);
  348. if (AssembleInput(*P, TheTarget, *STI, *MCII, MCOptions))
  349. return 1;
  350. if (Regions.empty()) {
  351. WithColor::error() << "no assembly instructions found.\n";
  352. return 1;
  353. }
  354. // Now initialize the output file.
  355. auto OF = getOutputStream();
  356. if (std::error_code EC = OF.getError()) {
  357. WithColor::error() << EC.message() << '\n';
  358. return 1;
  359. }
  360. unsigned AssemblerDialect = P->getAssemblerDialect();
  361. if (OutputAsmVariant >= 0)
  362. AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
  363. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  364. Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
  365. if (!IP) {
  366. WithColor::error()
  367. << "unable to create instruction printer for target triple '"
  368. << TheTriple.normalize() << "' with assembly variant "
  369. << AssemblerDialect << ".\n";
  370. return 1;
  371. }
  372. std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
  373. const MCSchedModel &SM = STI->getSchedModel();
  374. unsigned Width = SM.IssueWidth;
  375. if (DispatchWidth)
  376. Width = DispatchWidth;
  377. // Create an instruction builder.
  378. mca::InstrBuilder IB(*STI, *MCII, *MRI, *MCIA, *IP);
  379. // Create a context to control ownership of the pipeline hardware.
  380. mca::Context MCA(*MRI, *STI);
  381. mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
  382. StoreQueueSize, AssumeNoAlias);
  383. // Number each region in the sequence.
  384. unsigned RegionIdx = 0;
  385. for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
  386. // Skip empty code regions.
  387. if (Region->empty())
  388. continue;
  389. // Don't print the header of this region if it is the default region, and
  390. // it doesn't have an end location.
  391. if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
  392. TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
  393. StringRef Desc = Region->getDescription();
  394. if (!Desc.empty())
  395. TOF->os() << " - " << Desc;
  396. TOF->os() << "\n\n";
  397. }
  398. mca::SourceMgr S(Region->getInstructions(),
  399. PrintInstructionTables ? 1 : Iterations);
  400. if (PrintInstructionTables) {
  401. // Create a pipeline, stages, and a printer.
  402. auto P = llvm::make_unique<mca::Pipeline>();
  403. P->appendStage(llvm::make_unique<mca::FetchStage>(IB, S));
  404. P->appendStage(llvm::make_unique<mca::InstructionTables>(SM, IB));
  405. mca::PipelinePrinter Printer(*P);
  406. // Create the views for this pipeline, execute, and emit a report.
  407. if (PrintInstructionInfoView) {
  408. Printer.addView(
  409. llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
  410. }
  411. Printer.addView(
  412. llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
  413. auto Err = P->run();
  414. if (Err)
  415. report_fatal_error(toString(std::move(Err)));
  416. Printer.printReport(TOF->os());
  417. continue;
  418. }
  419. // Create a basic pipeline simulating an out-of-order backend.
  420. auto P = MCA.createDefaultPipeline(PO, IB, S);
  421. mca::PipelinePrinter Printer(*P);
  422. if (PrintSummaryView)
  423. Printer.addView(llvm::make_unique<mca::SummaryView>(SM, S, Width));
  424. if (PrintInstructionInfoView)
  425. Printer.addView(
  426. llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
  427. if (PrintDispatchStats)
  428. Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
  429. if (PrintSchedulerStats)
  430. Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
  431. if (PrintRetireStats)
  432. Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
  433. if (PrintRegisterFileStats)
  434. Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
  435. if (PrintResourcePressureView)
  436. Printer.addView(
  437. llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
  438. if (PrintTimelineView) {
  439. Printer.addView(llvm::make_unique<mca::TimelineView>(
  440. *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
  441. }
  442. auto Err = P->run();
  443. if (Err)
  444. report_fatal_error(toString(std::move(Err)));
  445. Printer.printReport(TOF->os());
  446. // Clear the InstrBuilder internal state in preparation for another round.
  447. IB.clear();
  448. }
  449. TOF->keep();
  450. return 0;
  451. }