1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
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
7 //===----------------------------------------------------------------------===//
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.
12 // llvm-mca [options] <file-name>
17 // The target defaults to the host target.
18 // The cpu defaults to the 'native' host cpu.
19 // The output defaults to standard output.
21 //===----------------------------------------------------------------------===//
23 #include "CodeRegion.h"
24 #include "CodeRegionGenerator.h"
25 #include "PipelinePrinter.h"
26 #include "Views/BottleneckAnalysis.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 "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MCA/Context.h"
40 #include "llvm/MCA/Pipeline.h"
41 #include "llvm/MCA/Stages/EntryStage.h"
42 #include "llvm/MCA/Stages/InstructionTables.h"
43 #include "llvm/MCA/Support.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/InitLLVM.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/ToolOutputFile.h"
55 #include "llvm/Support/WithColor.h"
59 static cl::OptionCategory ToolOptions("Tool Options");
60 static cl::OptionCategory ViewOptions("View Options");
62 static cl::opt<std::string> InputFilename(cl::Positional,
63 cl::desc("<input file>"),
64 cl::cat(ToolOptions), cl::init("-"));
66 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
67 cl::init("-"), cl::cat(ToolOptions),
68 cl::value_desc("filename"));
70 static cl::opt<std::string>
72 cl::desc("Target architecture. "
73 "See -version for available targets"),
74 cl::cat(ToolOptions));
76 static cl::opt<std::string>
78 cl::desc("Target triple. See -version for available targets"),
79 cl::cat(ToolOptions));
81 static cl::opt<std::string>
83 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
84 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
87 OutputAsmVariant("output-asm-variant",
88 cl::desc("Syntax variant to use for output printing"),
89 cl::cat(ToolOptions), cl::init(-1));
91 static cl::opt<unsigned> Iterations("iterations",
92 cl::desc("Number of iterations to run"),
93 cl::cat(ToolOptions), cl::init(0));
95 static cl::opt<unsigned>
96 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
97 cl::cat(ToolOptions), cl::init(0));
99 static cl::opt<unsigned>
100 RegisterFileSize("register-file-size",
101 cl::desc("Maximum number of physical registers which can "
102 "be used for register mappings"),
103 cl::cat(ToolOptions), cl::init(0));
105 static cl::opt<unsigned>
106 MicroOpQueue("micro-op-queue-size", cl::Hidden,
107 cl::desc("Number of entries in the micro-op queue"),
108 cl::cat(ToolOptions), cl::init(0));
110 static cl::opt<unsigned>
111 DecoderThroughput("decoder-throughput", cl::Hidden,
112 cl::desc("Maximum throughput from the decoders "
113 "(instructions per cycle)"),
114 cl::cat(ToolOptions), cl::init(0));
117 PrintRegisterFileStats("register-file-stats",
118 cl::desc("Print register file statistics"),
119 cl::cat(ViewOptions), cl::init(false));
121 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
122 cl::desc("Print dispatch statistics"),
123 cl::cat(ViewOptions), cl::init(false));
126 PrintSummaryView("summary-view", cl::Hidden,
127 cl::desc("Print summary view (enabled by default)"),
128 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));
135 PrintRetireStats("retire-stats",
136 cl::desc("Print retire control unit statistics"),
137 cl::cat(ViewOptions), cl::init(false));
139 static cl::opt<bool> PrintResourcePressureView(
141 cl::desc("Print the resource pressure view (enabled by default)"),
142 cl::cat(ViewOptions), cl::init(true));
144 static cl::opt<bool> PrintTimelineView("timeline",
145 cl::desc("Print the timeline view"),
146 cl::cat(ViewOptions), cl::init(false));
148 static cl::opt<unsigned> TimelineMaxIterations(
149 "timeline-max-iterations",
150 cl::desc("Maximum number of iterations to print in timeline view"),
151 cl::cat(ViewOptions), cl::init(0));
153 static cl::opt<unsigned> TimelineMaxCycles(
154 "timeline-max-cycles",
156 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
157 cl::cat(ViewOptions), cl::init(80));
160 AssumeNoAlias("noalias",
161 cl::desc("If set, assume that loads and stores do not alias"),
162 cl::cat(ToolOptions), cl::init(true));
164 static cl::opt<unsigned> LoadQueueSize("lqueue",
165 cl::desc("Size of the load queue"),
166 cl::cat(ToolOptions), cl::init(0));
168 static cl::opt<unsigned> StoreQueueSize("squeue",
169 cl::desc("Size of the store queue"),
170 cl::cat(ToolOptions), cl::init(0));
173 PrintInstructionTables("instruction-tables",
174 cl::desc("Print instruction tables"),
175 cl::cat(ToolOptions), cl::init(false));
177 static cl::opt<bool> PrintInstructionInfoView(
179 cl::desc("Print the instruction info view (enabled by default)"),
180 cl::cat(ViewOptions), cl::init(true));
182 static cl::opt<bool> EnableAllStats("all-stats",
183 cl::desc("Print all hardware statistics"),
184 cl::cat(ViewOptions), cl::init(false));
187 EnableAllViews("all-views",
188 cl::desc("Print all views including hardware statistics"),
189 cl::cat(ViewOptions), cl::init(false));
191 static cl::opt<bool> EnableBottleneckAnalysis(
192 "bottleneck-analysis",
193 cl::desc("Enable bottleneck analysis (disabled by default)"),
194 cl::cat(ViewOptions), cl::init(false));
198 const Target *getTarget(const char *ProgName) {
199 if (TripleName.empty())
200 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
201 Triple TheTriple(TripleName);
203 // Get the target specific parser.
205 const Target *TheTarget =
206 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
208 errs() << ProgName << ": " << Error;
212 // Return the found target.
216 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
217 if (OutputFilename == "")
218 OutputFilename = "-";
221 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
223 return std::move(Out);
226 } // end of anonymous namespace
228 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
229 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
230 O = Default.getValue();
233 static void processViewOptions() {
234 if (!EnableAllViews.getNumOccurrences() &&
235 !EnableAllStats.getNumOccurrences())
238 if (EnableAllViews.getNumOccurrences()) {
239 processOptionImpl(PrintSummaryView, EnableAllViews);
240 processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
241 processOptionImpl(PrintResourcePressureView, EnableAllViews);
242 processOptionImpl(PrintTimelineView, EnableAllViews);
243 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
246 const cl::opt<bool> &Default =
247 EnableAllViews.getPosition() < EnableAllStats.getPosition()
250 processOptionImpl(PrintRegisterFileStats, Default);
251 processOptionImpl(PrintDispatchStats, Default);
252 processOptionImpl(PrintSchedulerStats, Default);
253 processOptionImpl(PrintRetireStats, Default);
256 // Returns true on success.
257 static bool runPipeline(mca::Pipeline &P) {
258 // Handle pipeline errors here.
259 Expected<unsigned> Cycles = P.run();
261 WithColor::error() << toString(Cycles.takeError());
267 int main(int argc, char **argv) {
268 InitLLVM X(argc, argv);
270 // Initialize targets and assembly parsers.
271 InitializeAllTargetInfos();
272 InitializeAllTargetMCs();
273 InitializeAllAsmParsers();
275 // Enable printing of available targets when flag --version is specified.
276 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
278 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
280 // Parse flags and initialize target options.
281 cl::ParseCommandLineOptions(argc, argv,
282 "llvm machine code performance analyzer.\n");
284 // Get the target from the triple. If a triple is not specified, then select
285 // the default triple for the host. If the triple doesn't correspond to any
286 // registered target, then exit with an error message.
287 const char *ProgName = argv[0];
288 const Target *TheTarget = getTarget(ProgName);
292 // GetTarget() may replaced TripleName with a default triple.
293 // For safety, reconstruct the Triple object.
294 Triple TheTriple(TripleName);
296 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
297 MemoryBuffer::getFileOrSTDIN(InputFilename);
298 if (std::error_code EC = BufferPtr.getError()) {
299 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
303 // Apply overrides to llvm-mca specific options.
304 processViewOptions();
308 // Tell SrcMgr about this buffer, which is what the parser will pick up.
309 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
311 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
312 assert(MRI && "Unable to create target register info!");
314 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
315 assert(MAI && "Unable to create target asm info!");
317 MCObjectFileInfo MOFI;
318 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
319 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
321 std::unique_ptr<buffer_ostream> BOS;
323 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
325 std::unique_ptr<MCInstrAnalysis> MCIA(
326 TheTarget->createMCInstrAnalysis(MCII.get()));
328 if (!MCPU.compare("native"))
329 MCPU = llvm::sys::getHostCPUName();
331 std::unique_ptr<MCSubtargetInfo> STI(
332 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
333 if (!STI->isCPUStringValid(MCPU))
336 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
337 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
338 << "' is an in-order cpu.\n";
342 if (!STI->getSchedModel().hasInstrSchedModel()) {
344 << "unable to find instruction-level scheduling information for"
345 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
348 if (STI->getSchedModel().InstrItineraries)
350 << "cpu '" << MCPU << "' provides itineraries. However, "
351 << "instruction itineraries are currently unsupported.\n";
355 // Parse the input and create CodeRegions that llvm-mca can analyze.
356 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
357 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
360 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
361 WithColor::error() << E.getMessage() << '\n';
364 WithColor::error() << toString(std::move(Err)) << '\n';
368 const mca::CodeRegions &Regions = *RegionsOrErr;
370 // Early exit if errors were found by the code region parsing logic.
371 if (!Regions.isValid())
374 if (Regions.empty()) {
375 WithColor::error() << "no assembly instructions found.\n";
379 // Now initialize the output file.
380 auto OF = getOutputStream();
381 if (std::error_code EC = OF.getError()) {
382 WithColor::error() << EC.message() << '\n';
386 unsigned AssemblerDialect = CRG.getAssemblerDialect();
387 if (OutputAsmVariant >= 0)
388 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
389 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
390 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
393 << "unable to create instruction printer for target triple '"
394 << TheTriple.normalize() << "' with assembly variant "
395 << AssemblerDialect << ".\n";
399 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
401 const MCSchedModel &SM = STI->getSchedModel();
403 // Create an instruction builder.
404 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
406 // Create a context to control ownership of the pipeline hardware.
407 mca::Context MCA(*MRI, *STI);
409 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
410 RegisterFileSize, LoadQueueSize, StoreQueueSize,
411 AssumeNoAlias, EnableBottleneckAnalysis);
413 // Number each region in the sequence.
414 unsigned RegionIdx = 0;
416 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
417 // Skip empty code regions.
421 // Don't print the header of this region if it is the default region, and
422 // it doesn't have an end location.
423 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
424 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
425 StringRef Desc = Region->getDescription();
427 TOF->os() << " - " << Desc;
431 // Lower the MCInst sequence into an mca::Instruction sequence.
432 ArrayRef<MCInst> Insts = Region->getInstructions();
433 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
434 for (const MCInst &MCI : Insts) {
435 Expected<std::unique_ptr<mca::Instruction>> Inst =
436 IB.createInstruction(MCI);
438 if (auto NewE = handleErrors(
440 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
441 std::string InstructionStr;
442 raw_string_ostream SS(InstructionStr);
443 WithColor::error() << IE.Message << '\n';
444 IP->printInst(&IE.Inst, SS, "", *STI);
447 << "instruction: " << InstructionStr << '\n';
450 WithColor::error() << toString(std::move(NewE));
455 LoweredSequence.emplace_back(std::move(Inst.get()));
458 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
460 if (PrintInstructionTables) {
461 // Create a pipeline, stages, and a printer.
462 auto P = llvm::make_unique<mca::Pipeline>();
463 P->appendStage(llvm::make_unique<mca::EntryStage>(S));
464 P->appendStage(llvm::make_unique<mca::InstructionTables>(SM));
465 mca::PipelinePrinter Printer(*P);
467 // Create the views for this pipeline, execute, and emit a report.
468 if (PrintInstructionInfoView) {
469 Printer.addView(llvm::make_unique<mca::InstructionInfoView>(
470 *STI, *MCII, Insts, *IP));
473 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
475 if (!runPipeline(*P))
478 Printer.printReport(TOF->os());
482 // Create a basic pipeline simulating an out-of-order backend.
483 auto P = MCA.createDefaultPipeline(PO, IB, S);
484 mca::PipelinePrinter Printer(*P);
486 if (PrintSummaryView)
488 llvm::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
490 if (EnableBottleneckAnalysis) {
491 Printer.addView(llvm::make_unique<mca::BottleneckAnalysis>(
492 *STI, *IP, Insts, S.getNumIterations()));
495 if (PrintInstructionInfoView)
497 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP));
499 if (PrintDispatchStats)
500 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
502 if (PrintSchedulerStats)
503 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
505 if (PrintRetireStats)
506 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM));
508 if (PrintRegisterFileStats)
509 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
511 if (PrintResourcePressureView)
513 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
515 if (PrintTimelineView) {
516 unsigned TimelineIterations =
517 TimelineMaxIterations ? TimelineMaxIterations : 10;
518 Printer.addView(llvm::make_unique<mca::TimelineView>(
519 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
523 if (!runPipeline(*P))
526 Printer.printReport(TOF->os());
528 // Clear the InstrBuilder internal state in preparation for another round.