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/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"
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
>
78 cl::desc("Target architecture. "
79 "See -version for available targets"),
80 cl::cat(ToolOptions
));
82 static cl::opt
<std::string
>
84 cl::desc("Target triple. See -version for available targets"),
85 cl::cat(ToolOptions
));
87 static cl::opt
<std::string
>
89 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
90 cl::value_desc("cpu-name"), cl::cat(ToolOptions
), cl::init("native"));
93 OutputAsmVariant("output-asm-variant",
94 cl::desc("Syntax variant to use for output printing"),
95 cl::cat(ToolOptions
), cl::init(-1));
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));
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));
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));
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(
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",
166 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
167 cl::cat(ViewOptions
), cl::init(80));
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));
183 PrintInstructionTables("instruction-tables",
184 cl::desc("Print instruction tables"),
185 cl::cat(ToolOptions
), cl::init(false));
187 static cl::opt
<bool> PrintInstructionInfoView(
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));
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(
208 cl::desc("Print encoding information in the instruction info view"),
209 cl::cat(ViewOptions
), cl::init(false));
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.
220 const Target
*TheTarget
=
221 TargetRegistry::lookupTarget(ArchName
, TheTriple
, Error
);
223 errs() << ProgName
<< ": " << Error
;
227 // Return the found target.
231 ErrorOr
<std::unique_ptr
<ToolOutputFile
>> getOutputStream() {
232 if (OutputFilename
== "")
233 OutputFilename
= "-";
236 llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, sys::fs::OF_None
);
238 return std::move(Out
);
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())
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()
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();
276 WithColor::error() << toString(Cycles
.takeError());
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
);
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';
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
))
329 if (!PrintInstructionTables
&& !STI
->getSchedModel().isOutOfOrder()) {
330 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
331 << "' is an in-order cpu.\n";
335 if (!STI
->getSchedModel().hasInstrSchedModel()) {
337 << "unable to find instruction-level scheduling information for"
338 << " target triple '" << TheTriple
.normalize() << "' and cpu '" << MCPU
341 if (STI
->getSchedModel().InstrItineraries
)
343 << "cpu '" << MCPU
<< "' provides itineraries. However, "
344 << "instruction itineraries are currently unsupported.\n";
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
;
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();
376 handleErrors(RegionsOrErr
.takeError(), [](const StringError
&E
) {
377 WithColor::error() << E
.getMessage() << '\n';
380 WithColor::error() << toString(std::move(Err
)) << '\n';
384 const mca::CodeRegions
&Regions
= *RegionsOrErr
;
386 // Early exit if errors were found by the code region parsing logic.
387 if (!Regions
.isValid())
390 if (Regions
.empty()) {
391 WithColor::error() << "no assembly instructions found.\n";
395 // Now initialize the output file.
396 auto OF
= getOutputStream();
397 if (std::error_code EC
= OF
.getError()) {
398 WithColor::error() << EC
.message() << '\n';
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
));
409 << "unable to create instruction printer for target triple '"
410 << TheTriple
.normalize() << "' with assembly variant "
411 << AssemblerDialect
<< ".\n";
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.
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();
452 TOF
->os() << " - " << Desc
;
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
);
464 if (auto NewE
= handleErrors(
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
);
473 << "instruction: " << InstructionStr
<< '\n';
476 WithColor::error() << toString(std::move(NewE
));
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
= llvm::make_unique
<mca::Pipeline
>();
489 P
->appendStage(llvm::make_unique
<mca::EntryStage
>(S
));
490 P
->appendStage(llvm::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(llvm::make_unique
<mca::InstructionInfoView
>(
496 *STI
, *MCII
, CE
, ShowEncoding
, Insts
, *IP
));
499 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
501 if (!runPipeline(*P
))
504 Printer
.printReport(TOF
->os());
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
)
514 llvm::make_unique
<mca::SummaryView
>(SM
, Insts
, DispatchWidth
));
516 if (EnableBottleneckAnalysis
) {
517 Printer
.addView(llvm::make_unique
<mca::BottleneckAnalysis
>(
518 *STI
, *IP
, Insts
, S
.getNumIterations()));
521 if (PrintInstructionInfoView
)
522 Printer
.addView(llvm::make_unique
<mca::InstructionInfoView
>(
523 *STI
, *MCII
, CE
, ShowEncoding
, Insts
, *IP
));
525 if (PrintDispatchStats
)
526 Printer
.addView(llvm::make_unique
<mca::DispatchStatistics
>());
528 if (PrintSchedulerStats
)
529 Printer
.addView(llvm::make_unique
<mca::SchedulerStatistics
>(*STI
));
531 if (PrintRetireStats
)
532 Printer
.addView(llvm::make_unique
<mca::RetireControlUnitStatistics
>(SM
));
534 if (PrintRegisterFileStats
)
535 Printer
.addView(llvm::make_unique
<mca::RegisterFileStatistics
>(*STI
));
537 if (PrintResourcePressureView
)
539 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
541 if (PrintTimelineView
) {
542 unsigned TimelineIterations
=
543 TimelineMaxIterations
? TimelineMaxIterations
: 10;
544 Printer
.addView(llvm::make_unique
<mca::TimelineView
>(
545 *STI
, *IP
, Insts
, std::min(TimelineIterations
, S
.getNumIterations()),
549 if (!runPipeline(*P
))
552 Printer
.printReport(TOF
->os());
554 // Clear the InstrBuilder internal state in preparation for another round.