[llvm-readobj] - Refine the LLVM-style output to be consistent.
[llvm-complete.git] / tools / llvm-mca / llvm-mca.cpp
blob99c45eebdd88e30c9f5f058fea5da9a2cfdafb50
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.
12 // llvm-mca [options] <file-name>
13 // -march <type>
14 // -mcpu <cpu>
15 // -o <file>
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/MCAsmBackend.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCCodeEmitter.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCObjectFileInfo.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCTargetOptionsCommandFlags.inc"
43 #include "llvm/MCA/CodeEmitter.h"
44 #include "llvm/MCA/Context.h"
45 #include "llvm/MCA/InstrBuilder.h"
46 #include "llvm/MCA/Pipeline.h"
47 #include "llvm/MCA/Stages/EntryStage.h"
48 #include "llvm/MCA/Stages/InstructionTables.h"
49 #include "llvm/MCA/Support.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/ErrorOr.h"
53 #include "llvm/Support/FileSystem.h"
54 #include "llvm/Support/Host.h"
55 #include "llvm/Support/InitLLVM.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/TargetRegistry.h"
59 #include "llvm/Support/TargetSelect.h"
60 #include "llvm/Support/ToolOutputFile.h"
61 #include "llvm/Support/WithColor.h"
63 using namespace llvm;
65 static cl::OptionCategory ToolOptions("Tool Options");
66 static cl::OptionCategory ViewOptions("View Options");
68 static cl::opt<std::string> InputFilename(cl::Positional,
69 cl::desc("<input file>"),
70 cl::cat(ToolOptions), cl::init("-"));
72 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
73 cl::init("-"), cl::cat(ToolOptions),
74 cl::value_desc("filename"));
76 static cl::opt<std::string>
77 ArchName("march",
78 cl::desc("Target architecture. "
79 "See -version for available targets"),
80 cl::cat(ToolOptions));
82 static cl::opt<std::string>
83 TripleName("mtriple",
84 cl::desc("Target triple. See -version for available targets"),
85 cl::cat(ToolOptions));
87 static cl::opt<std::string>
88 MCPU("mcpu",
89 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
90 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
92 static cl::opt<std::string>
93 MATTR("mattr",
94 cl::desc("Additional target features."),
95 cl::cat(ToolOptions));
97 static cl::opt<int>
98 OutputAsmVariant("output-asm-variant",
99 cl::desc("Syntax variant to use for output printing"),
100 cl::cat(ToolOptions), cl::init(-1));
102 static cl::opt<bool>
103 PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),
104 cl::desc("Prefer hex format when printing immediate values"));
106 static cl::opt<unsigned> Iterations("iterations",
107 cl::desc("Number of iterations to run"),
108 cl::cat(ToolOptions), cl::init(0));
110 static cl::opt<unsigned>
111 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
112 cl::cat(ToolOptions), cl::init(0));
114 static cl::opt<unsigned>
115 RegisterFileSize("register-file-size",
116 cl::desc("Maximum number of physical registers which can "
117 "be used for register mappings"),
118 cl::cat(ToolOptions), cl::init(0));
120 static cl::opt<unsigned>
121 MicroOpQueue("micro-op-queue-size", cl::Hidden,
122 cl::desc("Number of entries in the micro-op queue"),
123 cl::cat(ToolOptions), cl::init(0));
125 static cl::opt<unsigned>
126 DecoderThroughput("decoder-throughput", cl::Hidden,
127 cl::desc("Maximum throughput from the decoders "
128 "(instructions per cycle)"),
129 cl::cat(ToolOptions), cl::init(0));
131 static cl::opt<bool>
132 PrintRegisterFileStats("register-file-stats",
133 cl::desc("Print register file statistics"),
134 cl::cat(ViewOptions), cl::init(false));
136 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
137 cl::desc("Print dispatch statistics"),
138 cl::cat(ViewOptions), cl::init(false));
140 static cl::opt<bool>
141 PrintSummaryView("summary-view", cl::Hidden,
142 cl::desc("Print summary view (enabled by default)"),
143 cl::cat(ViewOptions), cl::init(true));
145 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
146 cl::desc("Print scheduler statistics"),
147 cl::cat(ViewOptions), cl::init(false));
149 static cl::opt<bool>
150 PrintRetireStats("retire-stats",
151 cl::desc("Print retire control unit statistics"),
152 cl::cat(ViewOptions), cl::init(false));
154 static cl::opt<bool> PrintResourcePressureView(
155 "resource-pressure",
156 cl::desc("Print the resource pressure view (enabled by default)"),
157 cl::cat(ViewOptions), cl::init(true));
159 static cl::opt<bool> PrintTimelineView("timeline",
160 cl::desc("Print the timeline view"),
161 cl::cat(ViewOptions), cl::init(false));
163 static cl::opt<unsigned> TimelineMaxIterations(
164 "timeline-max-iterations",
165 cl::desc("Maximum number of iterations to print in timeline view"),
166 cl::cat(ViewOptions), cl::init(0));
168 static cl::opt<unsigned> TimelineMaxCycles(
169 "timeline-max-cycles",
170 cl::desc(
171 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
172 cl::cat(ViewOptions), cl::init(80));
174 static cl::opt<bool>
175 AssumeNoAlias("noalias",
176 cl::desc("If set, assume that loads and stores do not alias"),
177 cl::cat(ToolOptions), cl::init(true));
179 static cl::opt<unsigned> LoadQueueSize("lqueue",
180 cl::desc("Size of the load queue"),
181 cl::cat(ToolOptions), cl::init(0));
183 static cl::opt<unsigned> StoreQueueSize("squeue",
184 cl::desc("Size of the store queue"),
185 cl::cat(ToolOptions), cl::init(0));
187 static cl::opt<bool>
188 PrintInstructionTables("instruction-tables",
189 cl::desc("Print instruction tables"),
190 cl::cat(ToolOptions), cl::init(false));
192 static cl::opt<bool> PrintInstructionInfoView(
193 "instruction-info",
194 cl::desc("Print the instruction info view (enabled by default)"),
195 cl::cat(ViewOptions), cl::init(true));
197 static cl::opt<bool> EnableAllStats("all-stats",
198 cl::desc("Print all hardware statistics"),
199 cl::cat(ViewOptions), cl::init(false));
201 static cl::opt<bool>
202 EnableAllViews("all-views",
203 cl::desc("Print all views including hardware statistics"),
204 cl::cat(ViewOptions), cl::init(false));
206 static cl::opt<bool> EnableBottleneckAnalysis(
207 "bottleneck-analysis",
208 cl::desc("Enable bottleneck analysis (disabled by default)"),
209 cl::cat(ViewOptions), cl::init(false));
211 static cl::opt<bool> ShowEncoding(
212 "show-encoding",
213 cl::desc("Print encoding information in the instruction info view"),
214 cl::cat(ViewOptions), cl::init(false));
216 namespace {
218 const Target *getTarget(const char *ProgName) {
219 if (TripleName.empty())
220 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
221 Triple TheTriple(TripleName);
223 // Get the target specific parser.
224 std::string Error;
225 const Target *TheTarget =
226 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
227 if (!TheTarget) {
228 errs() << ProgName << ": " << Error;
229 return nullptr;
232 // Return the found target.
233 return TheTarget;
236 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
237 if (OutputFilename == "")
238 OutputFilename = "-";
239 std::error_code EC;
240 auto Out =
241 std::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_Text);
242 if (!EC)
243 return std::move(Out);
244 return EC;
246 } // end of anonymous namespace
248 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
249 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
250 O = Default.getValue();
253 static void processViewOptions() {
254 if (!EnableAllViews.getNumOccurrences() &&
255 !EnableAllStats.getNumOccurrences())
256 return;
258 if (EnableAllViews.getNumOccurrences()) {
259 processOptionImpl(PrintSummaryView, EnableAllViews);
260 processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
261 processOptionImpl(PrintResourcePressureView, EnableAllViews);
262 processOptionImpl(PrintTimelineView, EnableAllViews);
263 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
266 const cl::opt<bool> &Default =
267 EnableAllViews.getPosition() < EnableAllStats.getPosition()
268 ? EnableAllStats
269 : EnableAllViews;
270 processOptionImpl(PrintRegisterFileStats, Default);
271 processOptionImpl(PrintDispatchStats, Default);
272 processOptionImpl(PrintSchedulerStats, Default);
273 processOptionImpl(PrintRetireStats, Default);
276 // Returns true on success.
277 static bool runPipeline(mca::Pipeline &P) {
278 // Handle pipeline errors here.
279 Expected<unsigned> Cycles = P.run();
280 if (!Cycles) {
281 WithColor::error() << toString(Cycles.takeError());
282 return false;
284 return true;
287 int main(int argc, char **argv) {
288 InitLLVM X(argc, argv);
290 // Initialize targets and assembly parsers.
291 InitializeAllTargetInfos();
292 InitializeAllTargetMCs();
293 InitializeAllAsmParsers();
295 // Enable printing of available targets when flag --version is specified.
296 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
298 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
300 // Parse flags and initialize target options.
301 cl::ParseCommandLineOptions(argc, argv,
302 "llvm machine code performance analyzer.\n");
304 // Get the target from the triple. If a triple is not specified, then select
305 // the default triple for the host. If the triple doesn't correspond to any
306 // registered target, then exit with an error message.
307 const char *ProgName = argv[0];
308 const Target *TheTarget = getTarget(ProgName);
309 if (!TheTarget)
310 return 1;
312 // GetTarget() may replaced TripleName with a default triple.
313 // For safety, reconstruct the Triple object.
314 Triple TheTriple(TripleName);
316 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
317 MemoryBuffer::getFileOrSTDIN(InputFilename);
318 if (std::error_code EC = BufferPtr.getError()) {
319 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
320 return 1;
323 // Apply overrides to llvm-mca specific options.
324 processViewOptions();
326 if (!MCPU.compare("native"))
327 MCPU = llvm::sys::getHostCPUName();
329 std::unique_ptr<MCSubtargetInfo> STI(
330 TheTarget->createMCSubtargetInfo(TripleName, MCPU, MATTR));
331 if (!STI->isCPUStringValid(MCPU))
332 return 1;
334 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
335 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
336 << "' is an in-order cpu.\n";
337 return 1;
340 if (!STI->getSchedModel().hasInstrSchedModel()) {
341 WithColor::error()
342 << "unable to find instruction-level scheduling information for"
343 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
344 << "'.\n";
346 if (STI->getSchedModel().InstrItineraries)
347 WithColor::note()
348 << "cpu '" << MCPU << "' provides itineraries. However, "
349 << "instruction itineraries are currently unsupported.\n";
350 return 1;
353 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
354 assert(MRI && "Unable to create target register info!");
356 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
357 assert(MAI && "Unable to create target asm info!");
359 MCObjectFileInfo MOFI;
360 SourceMgr SrcMgr;
362 // Tell SrcMgr about this buffer, which is what the parser will pick up.
363 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
365 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
367 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
369 std::unique_ptr<buffer_ostream> BOS;
371 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
373 std::unique_ptr<MCInstrAnalysis> MCIA(
374 TheTarget->createMCInstrAnalysis(MCII.get()));
376 // Parse the input and create CodeRegions that llvm-mca can analyze.
377 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
378 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
379 if (!RegionsOrErr) {
380 if (auto Err =
381 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
382 WithColor::error() << E.getMessage() << '\n';
383 })) {
384 // Default case.
385 WithColor::error() << toString(std::move(Err)) << '\n';
387 return 1;
389 const mca::CodeRegions &Regions = *RegionsOrErr;
391 // Early exit if errors were found by the code region parsing logic.
392 if (!Regions.isValid())
393 return 1;
395 if (Regions.empty()) {
396 WithColor::error() << "no assembly instructions found.\n";
397 return 1;
400 // Now initialize the output file.
401 auto OF = getOutputStream();
402 if (std::error_code EC = OF.getError()) {
403 WithColor::error() << EC.message() << '\n';
404 return 1;
407 unsigned AssemblerDialect = CRG.getAssemblerDialect();
408 if (OutputAsmVariant >= 0)
409 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
410 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
411 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
412 if (!IP) {
413 WithColor::error()
414 << "unable to create instruction printer for target triple '"
415 << TheTriple.normalize() << "' with assembly variant "
416 << AssemblerDialect << ".\n";
417 return 1;
420 // Set the display preference for hex vs. decimal immediates.
421 IP->setPrintImmHex(PrintImmHex);
423 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
425 const MCSchedModel &SM = STI->getSchedModel();
427 // Create an instruction builder.
428 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
430 // Create a context to control ownership of the pipeline hardware.
431 mca::Context MCA(*MRI, *STI);
433 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
434 RegisterFileSize, LoadQueueSize, StoreQueueSize,
435 AssumeNoAlias, EnableBottleneckAnalysis);
437 // Number each region in the sequence.
438 unsigned RegionIdx = 0;
440 std::unique_ptr<MCCodeEmitter> MCE(
441 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
443 std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
444 *STI, *MRI, InitMCTargetOptionsFromFlags()));
446 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
447 // Skip empty code regions.
448 if (Region->empty())
449 continue;
451 // Don't print the header of this region if it is the default region, and
452 // it doesn't have an end location.
453 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
454 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
455 StringRef Desc = Region->getDescription();
456 if (!Desc.empty())
457 TOF->os() << " - " << Desc;
458 TOF->os() << "\n\n";
461 // Lower the MCInst sequence into an mca::Instruction sequence.
462 ArrayRef<MCInst> Insts = Region->getInstructions();
463 mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
464 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
465 for (const MCInst &MCI : Insts) {
466 Expected<std::unique_ptr<mca::Instruction>> Inst =
467 IB.createInstruction(MCI);
468 if (!Inst) {
469 if (auto NewE = handleErrors(
470 Inst.takeError(),
471 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
472 std::string InstructionStr;
473 raw_string_ostream SS(InstructionStr);
474 WithColor::error() << IE.Message << '\n';
475 IP->printInst(&IE.Inst, SS, "", *STI);
476 SS.flush();
477 WithColor::note()
478 << "instruction: " << InstructionStr << '\n';
479 })) {
480 // Default case.
481 WithColor::error() << toString(std::move(NewE));
483 return 1;
486 LoweredSequence.emplace_back(std::move(Inst.get()));
489 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
491 if (PrintInstructionTables) {
492 // Create a pipeline, stages, and a printer.
493 auto P = std::make_unique<mca::Pipeline>();
494 P->appendStage(std::make_unique<mca::EntryStage>(S));
495 P->appendStage(std::make_unique<mca::InstructionTables>(SM));
496 mca::PipelinePrinter Printer(*P);
498 // Create the views for this pipeline, execute, and emit a report.
499 if (PrintInstructionInfoView) {
500 Printer.addView(std::make_unique<mca::InstructionInfoView>(
501 *STI, *MCII, CE, ShowEncoding, Insts, *IP));
503 Printer.addView(
504 std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
506 if (!runPipeline(*P))
507 return 1;
509 Printer.printReport(TOF->os());
510 continue;
513 // Create a basic pipeline simulating an out-of-order backend.
514 auto P = MCA.createDefaultPipeline(PO, S);
515 mca::PipelinePrinter Printer(*P);
517 if (PrintSummaryView)
518 Printer.addView(
519 std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
521 if (EnableBottleneckAnalysis) {
522 Printer.addView(std::make_unique<mca::BottleneckAnalysis>(
523 *STI, *IP, Insts, S.getNumIterations()));
526 if (PrintInstructionInfoView)
527 Printer.addView(std::make_unique<mca::InstructionInfoView>(
528 *STI, *MCII, CE, ShowEncoding, Insts, *IP));
530 if (PrintDispatchStats)
531 Printer.addView(std::make_unique<mca::DispatchStatistics>());
533 if (PrintSchedulerStats)
534 Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));
536 if (PrintRetireStats)
537 Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));
539 if (PrintRegisterFileStats)
540 Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));
542 if (PrintResourcePressureView)
543 Printer.addView(
544 std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
546 if (PrintTimelineView) {
547 unsigned TimelineIterations =
548 TimelineMaxIterations ? TimelineMaxIterations : 10;
549 Printer.addView(std::make_unique<mca::TimelineView>(
550 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
551 TimelineMaxCycles));
554 if (!runPipeline(*P))
555 return 1;
557 Printer.printReport(TOF->os());
559 // Clear the InstrBuilder internal state in preparation for another round.
560 IB.clear();
563 TOF->keep();
564 return 0;