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/MCCodeEmitter.h"
38 #include "llvm/MC/MCObjectFileInfo.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/MCA/Context.h"
42 #include "llvm/MCA/InstrBuilder.h"
43 #include "llvm/MCA/Pipeline.h"
44 #include "llvm/MCA/Stages/EntryStage.h"
45 #include "llvm/MCA/Stages/InstructionTables.h"
46 #include "llvm/MCA/Support.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/ErrorOr.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/InitLLVM.h"
53 #include "llvm/Support/MemoryBuffer.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/ToolOutputFile.h"
58 #include "llvm/Support/WithColor.h"
62 static cl::OptionCategory
ToolOptions("Tool Options");
63 static cl::OptionCategory
ViewOptions("View Options");
65 static cl::opt
<std::string
> InputFilename(cl::Positional
,
66 cl::desc("<input file>"),
67 cl::cat(ToolOptions
), cl::init("-"));
69 static cl::opt
<std::string
> OutputFilename("o", cl::desc("Output filename"),
70 cl::init("-"), cl::cat(ToolOptions
),
71 cl::value_desc("filename"));
73 static cl::opt
<std::string
>
75 cl::desc("Target architecture. "
76 "See -version for available targets"),
77 cl::cat(ToolOptions
));
79 static cl::opt
<std::string
>
81 cl::desc("Target triple. See -version for available targets"),
82 cl::cat(ToolOptions
));
84 static cl::opt
<std::string
>
86 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
87 cl::value_desc("cpu-name"), cl::cat(ToolOptions
), cl::init("native"));
90 OutputAsmVariant("output-asm-variant",
91 cl::desc("Syntax variant to use for output printing"),
92 cl::cat(ToolOptions
), cl::init(-1));
95 PrintImmHex("print-imm-hex", cl::cat(ToolOptions
), cl::init(false),
96 cl::desc("Prefer hex format when printing immediate values"));
98 static cl::opt
<unsigned> Iterations("iterations",
99 cl::desc("Number of iterations to run"),
100 cl::cat(ToolOptions
), cl::init(0));
102 static cl::opt
<unsigned>
103 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
104 cl::cat(ToolOptions
), cl::init(0));
106 static cl::opt
<unsigned>
107 RegisterFileSize("register-file-size",
108 cl::desc("Maximum number of physical registers which can "
109 "be used for register mappings"),
110 cl::cat(ToolOptions
), cl::init(0));
112 static cl::opt
<unsigned>
113 MicroOpQueue("micro-op-queue-size", cl::Hidden
,
114 cl::desc("Number of entries in the micro-op queue"),
115 cl::cat(ToolOptions
), cl::init(0));
117 static cl::opt
<unsigned>
118 DecoderThroughput("decoder-throughput", cl::Hidden
,
119 cl::desc("Maximum throughput from the decoders "
120 "(instructions per cycle)"),
121 cl::cat(ToolOptions
), cl::init(0));
124 PrintRegisterFileStats("register-file-stats",
125 cl::desc("Print register file statistics"),
126 cl::cat(ViewOptions
), cl::init(false));
128 static cl::opt
<bool> PrintDispatchStats("dispatch-stats",
129 cl::desc("Print dispatch statistics"),
130 cl::cat(ViewOptions
), cl::init(false));
133 PrintSummaryView("summary-view", cl::Hidden
,
134 cl::desc("Print summary view (enabled by default)"),
135 cl::cat(ViewOptions
), cl::init(true));
137 static cl::opt
<bool> PrintSchedulerStats("scheduler-stats",
138 cl::desc("Print scheduler statistics"),
139 cl::cat(ViewOptions
), cl::init(false));
142 PrintRetireStats("retire-stats",
143 cl::desc("Print retire control unit statistics"),
144 cl::cat(ViewOptions
), cl::init(false));
146 static cl::opt
<bool> PrintResourcePressureView(
148 cl::desc("Print the resource pressure view (enabled by default)"),
149 cl::cat(ViewOptions
), cl::init(true));
151 static cl::opt
<bool> PrintTimelineView("timeline",
152 cl::desc("Print the timeline view"),
153 cl::cat(ViewOptions
), cl::init(false));
155 static cl::opt
<unsigned> TimelineMaxIterations(
156 "timeline-max-iterations",
157 cl::desc("Maximum number of iterations to print in timeline view"),
158 cl::cat(ViewOptions
), cl::init(0));
160 static cl::opt
<unsigned> TimelineMaxCycles(
161 "timeline-max-cycles",
163 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
164 cl::cat(ViewOptions
), cl::init(80));
167 AssumeNoAlias("noalias",
168 cl::desc("If set, assume that loads and stores do not alias"),
169 cl::cat(ToolOptions
), cl::init(true));
171 static cl::opt
<unsigned> LoadQueueSize("lqueue",
172 cl::desc("Size of the load queue"),
173 cl::cat(ToolOptions
), cl::init(0));
175 static cl::opt
<unsigned> StoreQueueSize("squeue",
176 cl::desc("Size of the store queue"),
177 cl::cat(ToolOptions
), cl::init(0));
180 PrintInstructionTables("instruction-tables",
181 cl::desc("Print instruction tables"),
182 cl::cat(ToolOptions
), cl::init(false));
184 static cl::opt
<bool> PrintInstructionInfoView(
186 cl::desc("Print the instruction info view (enabled by default)"),
187 cl::cat(ViewOptions
), cl::init(true));
189 static cl::opt
<bool> EnableAllStats("all-stats",
190 cl::desc("Print all hardware statistics"),
191 cl::cat(ViewOptions
), cl::init(false));
194 EnableAllViews("all-views",
195 cl::desc("Print all views including hardware statistics"),
196 cl::cat(ViewOptions
), cl::init(false));
198 static cl::opt
<bool> EnableBottleneckAnalysis(
199 "bottleneck-analysis",
200 cl::desc("Enable bottleneck analysis (disabled by default)"),
201 cl::cat(ViewOptions
), cl::init(false));
205 const Target
*getTarget(const char *ProgName
) {
206 if (TripleName
.empty())
207 TripleName
= Triple::normalize(sys::getDefaultTargetTriple());
208 Triple
TheTriple(TripleName
);
210 // Get the target specific parser.
212 const Target
*TheTarget
=
213 TargetRegistry::lookupTarget(ArchName
, TheTriple
, Error
);
215 errs() << ProgName
<< ": " << Error
;
219 // Return the found target.
223 ErrorOr
<std::unique_ptr
<ToolOutputFile
>> getOutputStream() {
224 if (OutputFilename
== "")
225 OutputFilename
= "-";
228 llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, sys::fs::OF_None
);
230 return std::move(Out
);
233 } // end of anonymous namespace
235 static void processOptionImpl(cl::opt
<bool> &O
, const cl::opt
<bool> &Default
) {
236 if (!O
.getNumOccurrences() || O
.getPosition() < Default
.getPosition())
237 O
= Default
.getValue();
240 static void processViewOptions() {
241 if (!EnableAllViews
.getNumOccurrences() &&
242 !EnableAllStats
.getNumOccurrences())
245 if (EnableAllViews
.getNumOccurrences()) {
246 processOptionImpl(PrintSummaryView
, EnableAllViews
);
247 processOptionImpl(EnableBottleneckAnalysis
, EnableAllViews
);
248 processOptionImpl(PrintResourcePressureView
, EnableAllViews
);
249 processOptionImpl(PrintTimelineView
, EnableAllViews
);
250 processOptionImpl(PrintInstructionInfoView
, EnableAllViews
);
253 const cl::opt
<bool> &Default
=
254 EnableAllViews
.getPosition() < EnableAllStats
.getPosition()
257 processOptionImpl(PrintRegisterFileStats
, Default
);
258 processOptionImpl(PrintDispatchStats
, Default
);
259 processOptionImpl(PrintSchedulerStats
, Default
);
260 processOptionImpl(PrintRetireStats
, Default
);
263 // Returns true on success.
264 static bool runPipeline(mca::Pipeline
&P
) {
265 // Handle pipeline errors here.
266 Expected
<unsigned> Cycles
= P
.run();
268 WithColor::error() << toString(Cycles
.takeError());
274 int main(int argc
, char **argv
) {
275 InitLLVM
X(argc
, argv
);
277 // Initialize targets and assembly parsers.
278 InitializeAllTargetInfos();
279 InitializeAllTargetMCs();
280 InitializeAllAsmParsers();
282 // Enable printing of available targets when flag --version is specified.
283 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
285 cl::HideUnrelatedOptions({&ToolOptions
, &ViewOptions
});
287 // Parse flags and initialize target options.
288 cl::ParseCommandLineOptions(argc
, argv
,
289 "llvm machine code performance analyzer.\n");
291 // Get the target from the triple. If a triple is not specified, then select
292 // the default triple for the host. If the triple doesn't correspond to any
293 // registered target, then exit with an error message.
294 const char *ProgName
= argv
[0];
295 const Target
*TheTarget
= getTarget(ProgName
);
299 // GetTarget() may replaced TripleName with a default triple.
300 // For safety, reconstruct the Triple object.
301 Triple
TheTriple(TripleName
);
303 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
304 MemoryBuffer::getFileOrSTDIN(InputFilename
);
305 if (std::error_code EC
= BufferPtr
.getError()) {
306 WithColor::error() << InputFilename
<< ": " << EC
.message() << '\n';
310 // Apply overrides to llvm-mca specific options.
311 processViewOptions();
313 if (!MCPU
.compare("native"))
314 MCPU
= llvm::sys::getHostCPUName();
316 std::unique_ptr
<MCSubtargetInfo
> STI(
317 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, /* FeaturesStr */ ""));
318 if (!STI
->isCPUStringValid(MCPU
))
321 if (!PrintInstructionTables
&& !STI
->getSchedModel().isOutOfOrder()) {
322 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
323 << "' is an in-order cpu.\n";
327 if (!STI
->getSchedModel().hasInstrSchedModel()) {
329 << "unable to find instruction-level scheduling information for"
330 << " target triple '" << TheTriple
.normalize() << "' and cpu '" << MCPU
333 if (STI
->getSchedModel().InstrItineraries
)
335 << "cpu '" << MCPU
<< "' provides itineraries. However, "
336 << "instruction itineraries are currently unsupported.\n";
340 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
341 assert(MRI
&& "Unable to create target register info!");
343 std::unique_ptr
<MCAsmInfo
> MAI(TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
344 assert(MAI
&& "Unable to create target asm info!");
346 MCObjectFileInfo MOFI
;
349 // Tell SrcMgr about this buffer, which is what the parser will pick up.
350 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
352 MCContext
Ctx(MAI
.get(), MRI
.get(), &MOFI
, &SrcMgr
);
354 MOFI
.InitMCObjectFileInfo(TheTriple
, /* PIC= */ false, Ctx
);
356 std::unique_ptr
<buffer_ostream
> BOS
;
358 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
360 std::unique_ptr
<MCInstrAnalysis
> MCIA(
361 TheTarget
->createMCInstrAnalysis(MCII
.get()));
363 // Parse the input and create CodeRegions that llvm-mca can analyze.
364 mca::AsmCodeRegionGenerator
CRG(*TheTarget
, SrcMgr
, Ctx
, *MAI
, *STI
, *MCII
);
365 Expected
<const mca::CodeRegions
&> RegionsOrErr
= CRG
.parseCodeRegions();
368 handleErrors(RegionsOrErr
.takeError(), [](const StringError
&E
) {
369 WithColor::error() << E
.getMessage() << '\n';
372 WithColor::error() << toString(std::move(Err
)) << '\n';
376 const mca::CodeRegions
&Regions
= *RegionsOrErr
;
378 // Early exit if errors were found by the code region parsing logic.
379 if (!Regions
.isValid())
382 if (Regions
.empty()) {
383 WithColor::error() << "no assembly instructions found.\n";
387 // Now initialize the output file.
388 auto OF
= getOutputStream();
389 if (std::error_code EC
= OF
.getError()) {
390 WithColor::error() << EC
.message() << '\n';
394 unsigned AssemblerDialect
= CRG
.getAssemblerDialect();
395 if (OutputAsmVariant
>= 0)
396 AssemblerDialect
= static_cast<unsigned>(OutputAsmVariant
);
397 std::unique_ptr
<MCInstPrinter
> IP(TheTarget
->createMCInstPrinter(
398 Triple(TripleName
), AssemblerDialect
, *MAI
, *MCII
, *MRI
));
401 << "unable to create instruction printer for target triple '"
402 << TheTriple
.normalize() << "' with assembly variant "
403 << AssemblerDialect
<< ".\n";
407 // Set the display preference for hex vs. decimal immediates.
408 IP
->setPrintImmHex(PrintImmHex
);
410 std::unique_ptr
<ToolOutputFile
> TOF
= std::move(*OF
);
412 const MCSchedModel
&SM
= STI
->getSchedModel();
414 // Create an instruction builder.
415 mca::InstrBuilder
IB(*STI
, *MCII
, *MRI
, MCIA
.get());
417 // Create a context to control ownership of the pipeline hardware.
418 mca::Context
MCA(*MRI
, *STI
);
420 mca::PipelineOptions
PO(MicroOpQueue
, DecoderThroughput
, DispatchWidth
,
421 RegisterFileSize
, LoadQueueSize
, StoreQueueSize
,
422 AssumeNoAlias
, EnableBottleneckAnalysis
);
424 // Number each region in the sequence.
425 unsigned RegionIdx
= 0;
427 for (const std::unique_ptr
<mca::CodeRegion
> &Region
: Regions
) {
428 // Skip empty code regions.
432 // Don't print the header of this region if it is the default region, and
433 // it doesn't have an end location.
434 if (Region
->startLoc().isValid() || Region
->endLoc().isValid()) {
435 TOF
->os() << "\n[" << RegionIdx
++ << "] Code Region";
436 StringRef Desc
= Region
->getDescription();
438 TOF
->os() << " - " << Desc
;
442 // Lower the MCInst sequence into an mca::Instruction sequence.
443 ArrayRef
<MCInst
> Insts
= Region
->getInstructions();
444 std::vector
<std::unique_ptr
<mca::Instruction
>> LoweredSequence
;
445 for (const MCInst
&MCI
: Insts
) {
446 Expected
<std::unique_ptr
<mca::Instruction
>> Inst
=
447 IB
.createInstruction(MCI
);
449 if (auto NewE
= handleErrors(
451 [&IP
, &STI
](const mca::InstructionError
<MCInst
> &IE
) {
452 std::string InstructionStr
;
453 raw_string_ostream
SS(InstructionStr
);
454 WithColor::error() << IE
.Message
<< '\n';
455 IP
->printInst(&IE
.Inst
, SS
, "", *STI
);
458 << "instruction: " << InstructionStr
<< '\n';
461 WithColor::error() << toString(std::move(NewE
));
466 LoweredSequence
.emplace_back(std::move(Inst
.get()));
469 mca::SourceMgr
S(LoweredSequence
, PrintInstructionTables
? 1 : Iterations
);
471 if (PrintInstructionTables
) {
472 // Create a pipeline, stages, and a printer.
473 auto P
= llvm::make_unique
<mca::Pipeline
>();
474 P
->appendStage(llvm::make_unique
<mca::EntryStage
>(S
));
475 P
->appendStage(llvm::make_unique
<mca::InstructionTables
>(SM
));
476 mca::PipelinePrinter
Printer(*P
);
478 // Create the views for this pipeline, execute, and emit a report.
479 if (PrintInstructionInfoView
) {
480 Printer
.addView(llvm::make_unique
<mca::InstructionInfoView
>(
481 *STI
, *MCII
, Insts
, *IP
));
484 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
486 if (!runPipeline(*P
))
489 Printer
.printReport(TOF
->os());
493 // Create a basic pipeline simulating an out-of-order backend.
494 auto P
= MCA
.createDefaultPipeline(PO
, S
);
495 mca::PipelinePrinter
Printer(*P
);
497 if (PrintSummaryView
)
499 llvm::make_unique
<mca::SummaryView
>(SM
, Insts
, DispatchWidth
));
501 if (EnableBottleneckAnalysis
) {
502 Printer
.addView(llvm::make_unique
<mca::BottleneckAnalysis
>(
503 *STI
, *IP
, Insts
, S
.getNumIterations()));
506 if (PrintInstructionInfoView
)
508 llvm::make_unique
<mca::InstructionInfoView
>(*STI
, *MCII
, Insts
, *IP
));
510 if (PrintDispatchStats
)
511 Printer
.addView(llvm::make_unique
<mca::DispatchStatistics
>());
513 if (PrintSchedulerStats
)
514 Printer
.addView(llvm::make_unique
<mca::SchedulerStatistics
>(*STI
));
516 if (PrintRetireStats
)
517 Printer
.addView(llvm::make_unique
<mca::RetireControlUnitStatistics
>(SM
));
519 if (PrintRegisterFileStats
)
520 Printer
.addView(llvm::make_unique
<mca::RegisterFileStatistics
>(*STI
));
522 if (PrintResourcePressureView
)
524 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
526 if (PrintTimelineView
) {
527 unsigned TimelineIterations
=
528 TimelineMaxIterations
? TimelineMaxIterations
: 10;
529 Printer
.addView(llvm::make_unique
<mca::TimelineView
>(
530 *STI
, *IP
, Insts
, std::min(TimelineIterations
, S
.getNumIterations()),
534 if (!runPipeline(*P
))
537 Printer
.printReport(TOF
->os());
539 // Clear the InstrBuilder internal state in preparation for another round.