[lib/ObjectYAML] - Cleanup the private interface of ELFState<ELFT>. NFCI.
[llvm-complete.git] / tools / llvm-mca / llvm-mca.cpp
blobdde42c117300b7a3c21636bd3d3414b6d9692511
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<int>
93 OutputAsmVariant("output-asm-variant",
94 cl::desc("Syntax variant to use for output printing"),
95 cl::cat(ToolOptions), cl::init(-1));
97 static cl::opt<bool>
98 PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),
99 cl::desc("Prefer hex format when printing immediate values"));
101 static cl::opt<unsigned> Iterations("iterations",
102 cl::desc("Number of iterations to run"),
103 cl::cat(ToolOptions), cl::init(0));
105 static cl::opt<unsigned>
106 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
107 cl::cat(ToolOptions), cl::init(0));
109 static cl::opt<unsigned>
110 RegisterFileSize("register-file-size",
111 cl::desc("Maximum number of physical registers which can "
112 "be used for register mappings"),
113 cl::cat(ToolOptions), cl::init(0));
115 static cl::opt<unsigned>
116 MicroOpQueue("micro-op-queue-size", cl::Hidden,
117 cl::desc("Number of entries in the micro-op queue"),
118 cl::cat(ToolOptions), cl::init(0));
120 static cl::opt<unsigned>
121 DecoderThroughput("decoder-throughput", cl::Hidden,
122 cl::desc("Maximum throughput from the decoders "
123 "(instructions per cycle)"),
124 cl::cat(ToolOptions), cl::init(0));
126 static cl::opt<bool>
127 PrintRegisterFileStats("register-file-stats",
128 cl::desc("Print register file statistics"),
129 cl::cat(ViewOptions), cl::init(false));
131 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
132 cl::desc("Print dispatch statistics"),
133 cl::cat(ViewOptions), cl::init(false));
135 static cl::opt<bool>
136 PrintSummaryView("summary-view", cl::Hidden,
137 cl::desc("Print summary view (enabled by default)"),
138 cl::cat(ViewOptions), cl::init(true));
140 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
141 cl::desc("Print scheduler statistics"),
142 cl::cat(ViewOptions), cl::init(false));
144 static cl::opt<bool>
145 PrintRetireStats("retire-stats",
146 cl::desc("Print retire control unit statistics"),
147 cl::cat(ViewOptions), cl::init(false));
149 static cl::opt<bool> PrintResourcePressureView(
150 "resource-pressure",
151 cl::desc("Print the resource pressure view (enabled by default)"),
152 cl::cat(ViewOptions), cl::init(true));
154 static cl::opt<bool> PrintTimelineView("timeline",
155 cl::desc("Print the timeline view"),
156 cl::cat(ViewOptions), cl::init(false));
158 static cl::opt<unsigned> TimelineMaxIterations(
159 "timeline-max-iterations",
160 cl::desc("Maximum number of iterations to print in timeline view"),
161 cl::cat(ViewOptions), cl::init(0));
163 static cl::opt<unsigned> TimelineMaxCycles(
164 "timeline-max-cycles",
165 cl::desc(
166 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
167 cl::cat(ViewOptions), cl::init(80));
169 static cl::opt<bool>
170 AssumeNoAlias("noalias",
171 cl::desc("If set, assume that loads and stores do not alias"),
172 cl::cat(ToolOptions), cl::init(true));
174 static cl::opt<unsigned> LoadQueueSize("lqueue",
175 cl::desc("Size of the load queue"),
176 cl::cat(ToolOptions), cl::init(0));
178 static cl::opt<unsigned> StoreQueueSize("squeue",
179 cl::desc("Size of the store queue"),
180 cl::cat(ToolOptions), cl::init(0));
182 static cl::opt<bool>
183 PrintInstructionTables("instruction-tables",
184 cl::desc("Print instruction tables"),
185 cl::cat(ToolOptions), cl::init(false));
187 static cl::opt<bool> PrintInstructionInfoView(
188 "instruction-info",
189 cl::desc("Print the instruction info view (enabled by default)"),
190 cl::cat(ViewOptions), cl::init(true));
192 static cl::opt<bool> EnableAllStats("all-stats",
193 cl::desc("Print all hardware statistics"),
194 cl::cat(ViewOptions), cl::init(false));
196 static cl::opt<bool>
197 EnableAllViews("all-views",
198 cl::desc("Print all views including hardware statistics"),
199 cl::cat(ViewOptions), cl::init(false));
201 static cl::opt<bool> EnableBottleneckAnalysis(
202 "bottleneck-analysis",
203 cl::desc("Enable bottleneck analysis (disabled by default)"),
204 cl::cat(ViewOptions), cl::init(false));
206 static cl::opt<bool> ShowEncoding(
207 "show-encoding",
208 cl::desc("Print encoding information in the instruction info view"),
209 cl::cat(ViewOptions), cl::init(false));
211 namespace {
213 const Target *getTarget(const char *ProgName) {
214 if (TripleName.empty())
215 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
216 Triple TheTriple(TripleName);
218 // Get the target specific parser.
219 std::string Error;
220 const Target *TheTarget =
221 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
222 if (!TheTarget) {
223 errs() << ProgName << ": " << Error;
224 return nullptr;
227 // Return the found target.
228 return TheTarget;
231 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
232 if (OutputFilename == "")
233 OutputFilename = "-";
234 std::error_code EC;
235 auto Out =
236 std::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_None);
237 if (!EC)
238 return std::move(Out);
239 return EC;
241 } // end of anonymous namespace
243 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
244 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
245 O = Default.getValue();
248 static void processViewOptions() {
249 if (!EnableAllViews.getNumOccurrences() &&
250 !EnableAllStats.getNumOccurrences())
251 return;
253 if (EnableAllViews.getNumOccurrences()) {
254 processOptionImpl(PrintSummaryView, EnableAllViews);
255 processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
256 processOptionImpl(PrintResourcePressureView, EnableAllViews);
257 processOptionImpl(PrintTimelineView, EnableAllViews);
258 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
261 const cl::opt<bool> &Default =
262 EnableAllViews.getPosition() < EnableAllStats.getPosition()
263 ? EnableAllStats
264 : EnableAllViews;
265 processOptionImpl(PrintRegisterFileStats, Default);
266 processOptionImpl(PrintDispatchStats, Default);
267 processOptionImpl(PrintSchedulerStats, Default);
268 processOptionImpl(PrintRetireStats, Default);
271 // Returns true on success.
272 static bool runPipeline(mca::Pipeline &P) {
273 // Handle pipeline errors here.
274 Expected<unsigned> Cycles = P.run();
275 if (!Cycles) {
276 WithColor::error() << toString(Cycles.takeError());
277 return false;
279 return true;
282 int main(int argc, char **argv) {
283 InitLLVM X(argc, argv);
285 // Initialize targets and assembly parsers.
286 InitializeAllTargetInfos();
287 InitializeAllTargetMCs();
288 InitializeAllAsmParsers();
290 // Enable printing of available targets when flag --version is specified.
291 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
293 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
295 // Parse flags and initialize target options.
296 cl::ParseCommandLineOptions(argc, argv,
297 "llvm machine code performance analyzer.\n");
299 // Get the target from the triple. If a triple is not specified, then select
300 // the default triple for the host. If the triple doesn't correspond to any
301 // registered target, then exit with an error message.
302 const char *ProgName = argv[0];
303 const Target *TheTarget = getTarget(ProgName);
304 if (!TheTarget)
305 return 1;
307 // GetTarget() may replaced TripleName with a default triple.
308 // For safety, reconstruct the Triple object.
309 Triple TheTriple(TripleName);
311 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
312 MemoryBuffer::getFileOrSTDIN(InputFilename);
313 if (std::error_code EC = BufferPtr.getError()) {
314 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
315 return 1;
318 // Apply overrides to llvm-mca specific options.
319 processViewOptions();
321 if (!MCPU.compare("native"))
322 MCPU = llvm::sys::getHostCPUName();
324 std::unique_ptr<MCSubtargetInfo> STI(
325 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
326 if (!STI->isCPUStringValid(MCPU))
327 return 1;
329 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
330 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
331 << "' is an in-order cpu.\n";
332 return 1;
335 if (!STI->getSchedModel().hasInstrSchedModel()) {
336 WithColor::error()
337 << "unable to find instruction-level scheduling information for"
338 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
339 << "'.\n";
341 if (STI->getSchedModel().InstrItineraries)
342 WithColor::note()
343 << "cpu '" << MCPU << "' provides itineraries. However, "
344 << "instruction itineraries are currently unsupported.\n";
345 return 1;
348 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
349 assert(MRI && "Unable to create target register info!");
351 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
352 assert(MAI && "Unable to create target asm info!");
354 MCObjectFileInfo MOFI;
355 SourceMgr SrcMgr;
357 // Tell SrcMgr about this buffer, which is what the parser will pick up.
358 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
360 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
362 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
364 std::unique_ptr<buffer_ostream> BOS;
366 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
368 std::unique_ptr<MCInstrAnalysis> MCIA(
369 TheTarget->createMCInstrAnalysis(MCII.get()));
371 // Parse the input and create CodeRegions that llvm-mca can analyze.
372 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
373 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
374 if (!RegionsOrErr) {
375 if (auto Err =
376 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
377 WithColor::error() << E.getMessage() << '\n';
378 })) {
379 // Default case.
380 WithColor::error() << toString(std::move(Err)) << '\n';
382 return 1;
384 const mca::CodeRegions &Regions = *RegionsOrErr;
386 // Early exit if errors were found by the code region parsing logic.
387 if (!Regions.isValid())
388 return 1;
390 if (Regions.empty()) {
391 WithColor::error() << "no assembly instructions found.\n";
392 return 1;
395 // Now initialize the output file.
396 auto OF = getOutputStream();
397 if (std::error_code EC = OF.getError()) {
398 WithColor::error() << EC.message() << '\n';
399 return 1;
402 unsigned AssemblerDialect = CRG.getAssemblerDialect();
403 if (OutputAsmVariant >= 0)
404 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
405 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
406 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
407 if (!IP) {
408 WithColor::error()
409 << "unable to create instruction printer for target triple '"
410 << TheTriple.normalize() << "' with assembly variant "
411 << AssemblerDialect << ".\n";
412 return 1;
415 // Set the display preference for hex vs. decimal immediates.
416 IP->setPrintImmHex(PrintImmHex);
418 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
420 const MCSchedModel &SM = STI->getSchedModel();
422 // Create an instruction builder.
423 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
425 // Create a context to control ownership of the pipeline hardware.
426 mca::Context MCA(*MRI, *STI);
428 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
429 RegisterFileSize, LoadQueueSize, StoreQueueSize,
430 AssumeNoAlias, EnableBottleneckAnalysis);
432 // Number each region in the sequence.
433 unsigned RegionIdx = 0;
435 std::unique_ptr<MCCodeEmitter> MCE(
436 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
438 std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
439 *STI, *MRI, InitMCTargetOptionsFromFlags()));
441 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
442 // Skip empty code regions.
443 if (Region->empty())
444 continue;
446 // Don't print the header of this region if it is the default region, and
447 // it doesn't have an end location.
448 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
449 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
450 StringRef Desc = Region->getDescription();
451 if (!Desc.empty())
452 TOF->os() << " - " << Desc;
453 TOF->os() << "\n\n";
456 // Lower the MCInst sequence into an mca::Instruction sequence.
457 ArrayRef<MCInst> Insts = Region->getInstructions();
458 mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
459 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
460 for (const MCInst &MCI : Insts) {
461 Expected<std::unique_ptr<mca::Instruction>> Inst =
462 IB.createInstruction(MCI);
463 if (!Inst) {
464 if (auto NewE = handleErrors(
465 Inst.takeError(),
466 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
467 std::string InstructionStr;
468 raw_string_ostream SS(InstructionStr);
469 WithColor::error() << IE.Message << '\n';
470 IP->printInst(&IE.Inst, SS, "", *STI);
471 SS.flush();
472 WithColor::note()
473 << "instruction: " << InstructionStr << '\n';
474 })) {
475 // Default case.
476 WithColor::error() << toString(std::move(NewE));
478 return 1;
481 LoweredSequence.emplace_back(std::move(Inst.get()));
484 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
486 if (PrintInstructionTables) {
487 // Create a pipeline, stages, and a printer.
488 auto P = std::make_unique<mca::Pipeline>();
489 P->appendStage(std::make_unique<mca::EntryStage>(S));
490 P->appendStage(std::make_unique<mca::InstructionTables>(SM));
491 mca::PipelinePrinter Printer(*P);
493 // Create the views for this pipeline, execute, and emit a report.
494 if (PrintInstructionInfoView) {
495 Printer.addView(std::make_unique<mca::InstructionInfoView>(
496 *STI, *MCII, CE, ShowEncoding, Insts, *IP));
498 Printer.addView(
499 std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
501 if (!runPipeline(*P))
502 return 1;
504 Printer.printReport(TOF->os());
505 continue;
508 // Create a basic pipeline simulating an out-of-order backend.
509 auto P = MCA.createDefaultPipeline(PO, S);
510 mca::PipelinePrinter Printer(*P);
512 if (PrintSummaryView)
513 Printer.addView(
514 std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
516 if (EnableBottleneckAnalysis) {
517 Printer.addView(std::make_unique<mca::BottleneckAnalysis>(
518 *STI, *IP, Insts, S.getNumIterations()));
521 if (PrintInstructionInfoView)
522 Printer.addView(std::make_unique<mca::InstructionInfoView>(
523 *STI, *MCII, CE, ShowEncoding, Insts, *IP));
525 if (PrintDispatchStats)
526 Printer.addView(std::make_unique<mca::DispatchStatistics>());
528 if (PrintSchedulerStats)
529 Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));
531 if (PrintRetireStats)
532 Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));
534 if (PrintRegisterFileStats)
535 Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));
537 if (PrintResourcePressureView)
538 Printer.addView(
539 std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
541 if (PrintTimelineView) {
542 unsigned TimelineIterations =
543 TimelineMaxIterations ? TimelineMaxIterations : 10;
544 Printer.addView(std::make_unique<mca::TimelineView>(
545 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
546 TimelineMaxCycles));
549 if (!runPipeline(*P))
550 return 1;
552 Printer.printReport(TOF->os());
554 // Clear the InstrBuilder internal state in preparation for another round.
555 IB.clear();
558 TOF->keep();
559 return 0;