1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows static performance analysis on
11 // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
13 // llvm-mca [options] <file-name>
18 // The target defaults to the host target.
19 // The cpu defaults to the 'native' host cpu.
20 // The output defaults to standard output.
22 //===----------------------------------------------------------------------===//
24 #include "CodeRegion.h"
25 #include "PipelinePrinter.h"
26 #include "Stages/FetchStage.h"
27 #include "Stages/InstructionTables.h"
28 #include "Views/DispatchStatistics.h"
29 #include "Views/InstructionInfoView.h"
30 #include "Views/RegisterFileStatistics.h"
31 #include "Views/ResourcePressureView.h"
32 #include "Views/RetireControlUnitStatistics.h"
33 #include "Views/SchedulerStatistics.h"
34 #include "Views/SummaryView.h"
35 #include "Views/TimelineView.h"
36 #include "include/Context.h"
37 #include "include/Pipeline.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCObjectFileInfo.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCStreamer.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
>
71 ArchName("march", cl::desc("Target arch to assemble for, "
72 "see -version for available targets"),
73 cl::cat(ToolOptions
));
75 static cl::opt
<std::string
>
76 TripleName("mtriple", cl::desc("Target triple to assemble for, "
77 "see -version for available targets"),
78 cl::cat(ToolOptions
));
80 static cl::opt
<std::string
>
82 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
83 cl::value_desc("cpu-name"), cl::cat(ToolOptions
), cl::init("native"));
86 OutputAsmVariant("output-asm-variant",
87 cl::desc("Syntax variant to use for output printing"),
88 cl::cat(ToolOptions
), cl::init(-1));
90 static cl::opt
<unsigned> Iterations("iterations",
91 cl::desc("Number of iterations to run"),
92 cl::cat(ToolOptions
), cl::init(0));
94 static cl::opt
<unsigned>
95 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
96 cl::cat(ToolOptions
), cl::init(0));
98 static cl::opt
<unsigned>
99 RegisterFileSize("register-file-size",
100 cl::desc("Maximum number of physical registers which can "
101 "be used for register mappings"),
102 cl::cat(ToolOptions
), cl::init(0));
105 PrintRegisterFileStats("register-file-stats",
106 cl::desc("Print register file statistics"),
107 cl::cat(ViewOptions
), cl::init(false));
109 static cl::opt
<bool> PrintDispatchStats("dispatch-stats",
110 cl::desc("Print dispatch statistics"),
111 cl::cat(ViewOptions
), cl::init(false));
114 PrintSummaryView("summary-view", cl::Hidden
,
115 cl::desc("Print summary view (enabled by default)"),
116 cl::cat(ViewOptions
), cl::init(true));
118 static cl::opt
<bool> PrintSchedulerStats("scheduler-stats",
119 cl::desc("Print scheduler statistics"),
120 cl::cat(ViewOptions
), cl::init(false));
123 PrintRetireStats("retire-stats",
124 cl::desc("Print retire control unit statistics"),
125 cl::cat(ViewOptions
), cl::init(false));
127 static cl::opt
<bool> PrintResourcePressureView(
129 cl::desc("Print the resource pressure view (enabled by default)"),
130 cl::cat(ViewOptions
), cl::init(true));
132 static cl::opt
<bool> PrintTimelineView("timeline",
133 cl::desc("Print the timeline view"),
134 cl::cat(ViewOptions
), cl::init(false));
136 static cl::opt
<unsigned> TimelineMaxIterations(
137 "timeline-max-iterations",
138 cl::desc("Maximum number of iterations to print in timeline view"),
139 cl::cat(ViewOptions
), cl::init(0));
141 static cl::opt
<unsigned> TimelineMaxCycles(
142 "timeline-max-cycles",
144 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
145 cl::cat(ViewOptions
), cl::init(80));
148 AssumeNoAlias("noalias",
149 cl::desc("If set, assume that loads and stores do not alias"),
150 cl::cat(ToolOptions
), cl::init(true));
152 static cl::opt
<unsigned>
153 LoadQueueSize("lqueue",
154 cl::desc("Size of the load queue (unbound by default)"),
155 cl::cat(ToolOptions
), cl::init(0));
157 static cl::opt
<unsigned>
158 StoreQueueSize("squeue",
159 cl::desc("Size of the store queue (unbound by default)"),
160 cl::cat(ToolOptions
), cl::init(0));
163 PrintInstructionTables("instruction-tables",
164 cl::desc("Print instruction tables"),
165 cl::cat(ToolOptions
), cl::init(false));
167 static cl::opt
<bool> PrintInstructionInfoView(
169 cl::desc("Print the instruction info view (enabled by default)"),
170 cl::cat(ViewOptions
), cl::init(true));
172 static cl::opt
<bool> EnableAllStats("all-stats",
173 cl::desc("Print all hardware statistics"),
174 cl::cat(ViewOptions
), cl::init(false));
177 EnableAllViews("all-views",
178 cl::desc("Print all views including hardware statistics"),
179 cl::cat(ViewOptions
), cl::init(false));
183 const Target
*getTarget(const char *ProgName
) {
184 if (TripleName
.empty())
185 TripleName
= Triple::normalize(sys::getDefaultTargetTriple());
186 Triple
TheTriple(TripleName
);
188 // Get the target specific parser.
190 const Target
*TheTarget
=
191 TargetRegistry::lookupTarget(ArchName
, TheTriple
, Error
);
193 errs() << ProgName
<< ": " << Error
;
197 // Return the found target.
201 // A comment consumer that parses strings.
202 // The only valid tokens are strings.
203 class MCACommentConsumer
: public AsmCommentConsumer
{
205 mca::CodeRegions
&Regions
;
207 MCACommentConsumer(mca::CodeRegions
&R
) : Regions(R
) {}
208 void HandleComment(SMLoc Loc
, StringRef CommentText
) override
{
209 // Skip empty comments.
210 StringRef
Comment(CommentText
);
214 // Skip spaces and tabs
215 unsigned Position
= Comment
.find_first_not_of(" \t");
216 if (Position
>= Comment
.size())
217 // we reached the end of the comment. Bail out.
220 Comment
= Comment
.drop_front(Position
);
221 if (Comment
.consume_front("LLVM-MCA-END")) {
222 Regions
.endRegion(Loc
);
226 // Now try to parse string LLVM-MCA-BEGIN
227 if (!Comment
.consume_front("LLVM-MCA-BEGIN"))
230 // Skip spaces and tabs
231 Position
= Comment
.find_first_not_of(" \t");
232 if (Position
< Comment
.size())
233 Comment
= Comment
.drop_front(Position
);
234 // Use the rest of the string as a descriptor for this code snippet.
235 Regions
.beginRegion(Comment
, Loc
);
239 int AssembleInput(MCAsmParser
&Parser
, const Target
*TheTarget
,
240 MCSubtargetInfo
&STI
, MCInstrInfo
&MCII
,
241 MCTargetOptions
&MCOptions
) {
242 std::unique_ptr
<MCTargetAsmParser
> TAP(
243 TheTarget
->createMCAsmParser(STI
, Parser
, MCII
, MCOptions
));
246 WithColor::error() << "this target does not support assembly parsing.\n";
250 Parser
.setTargetParser(*TAP
);
251 return Parser
.Run(false);
254 ErrorOr
<std::unique_ptr
<ToolOutputFile
>> getOutputStream() {
255 if (OutputFilename
== "")
256 OutputFilename
= "-";
259 llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, sys::fs::F_None
);
261 return std::move(Out
);
265 class MCStreamerWrapper final
: public MCStreamer
{
266 mca::CodeRegions
&Regions
;
269 MCStreamerWrapper(MCContext
&Context
, mca::CodeRegions
&R
)
270 : MCStreamer(Context
), Regions(R
) {}
272 // We only want to intercept the emission of new instructions.
273 virtual void EmitInstruction(const MCInst
&Inst
, const MCSubtargetInfo
&STI
,
274 bool /* unused */) override
{
275 Regions
.addInstruction(llvm::make_unique
<const MCInst
>(Inst
));
278 bool EmitSymbolAttribute(MCSymbol
*Symbol
, MCSymbolAttr Attribute
) override
{
282 void EmitCommonSymbol(MCSymbol
*Symbol
, uint64_t Size
,
283 unsigned ByteAlignment
) override
{}
284 void EmitZerofill(MCSection
*Section
, MCSymbol
*Symbol
= nullptr,
285 uint64_t Size
= 0, unsigned ByteAlignment
= 0,
286 SMLoc Loc
= SMLoc()) override
{}
287 void EmitGPRel32Value(const MCExpr
*Value
) override
{}
288 void BeginCOFFSymbolDef(const MCSymbol
*Symbol
) override
{}
289 void EmitCOFFSymbolStorageClass(int StorageClass
) override
{}
290 void EmitCOFFSymbolType(int Type
) override
{}
291 void EndCOFFSymbolDef() override
{}
293 const std::vector
<std::unique_ptr
<const MCInst
>> &
294 GetInstructionSequence(unsigned Index
) const {
295 return Regions
.getInstructionSequence(Index
);
298 } // end of anonymous namespace
300 static void processOptionImpl(cl::opt
<bool> &O
, const cl::opt
<bool> &Default
) {
301 if (!O
.getNumOccurrences() || O
.getPosition() < Default
.getPosition())
302 O
= Default
.getValue();
305 static void processViewOptions() {
306 if (!EnableAllViews
.getNumOccurrences() &&
307 !EnableAllStats
.getNumOccurrences())
310 if (EnableAllViews
.getNumOccurrences()) {
311 processOptionImpl(PrintSummaryView
, EnableAllViews
);
312 processOptionImpl(PrintResourcePressureView
, EnableAllViews
);
313 processOptionImpl(PrintTimelineView
, EnableAllViews
);
314 processOptionImpl(PrintInstructionInfoView
, EnableAllViews
);
317 const cl::opt
<bool> &Default
=
318 EnableAllViews
.getPosition() < EnableAllStats
.getPosition()
321 processOptionImpl(PrintRegisterFileStats
, Default
);
322 processOptionImpl(PrintDispatchStats
, Default
);
323 processOptionImpl(PrintSchedulerStats
, Default
);
324 processOptionImpl(PrintRetireStats
, Default
);
327 int main(int argc
, char **argv
) {
328 InitLLVM
X(argc
, argv
);
330 // Initialize targets and assembly parsers.
331 llvm::InitializeAllTargetInfos();
332 llvm::InitializeAllTargetMCs();
333 llvm::InitializeAllAsmParsers();
335 // Enable printing of available targets when flag --version is specified.
336 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
338 cl::HideUnrelatedOptions({&ToolOptions
, &ViewOptions
});
340 // Parse flags and initialize target options.
341 cl::ParseCommandLineOptions(argc
, argv
,
342 "llvm machine code performance analyzer.\n");
344 MCTargetOptions MCOptions
;
345 MCOptions
.PreserveAsmComments
= false;
347 // Get the target from the triple. If a triple is not specified, then select
348 // the default triple for the host. If the triple doesn't correspond to any
349 // registered target, then exit with an error message.
350 const char *ProgName
= argv
[0];
351 const Target
*TheTarget
= getTarget(ProgName
);
355 // GetTarget() may replaced TripleName with a default triple.
356 // For safety, reconstruct the Triple object.
357 Triple
TheTriple(TripleName
);
359 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
360 MemoryBuffer::getFileOrSTDIN(InputFilename
);
361 if (std::error_code EC
= BufferPtr
.getError()) {
362 WithColor::error() << InputFilename
<< ": " << EC
.message() << '\n';
366 // Apply overrides to llvm-mca specific options.
367 processViewOptions();
371 // Tell SrcMgr about this buffer, which is what the parser will pick up.
372 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
374 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
375 assert(MRI
&& "Unable to create target register info!");
377 std::unique_ptr
<MCAsmInfo
> MAI(TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
378 assert(MAI
&& "Unable to create target asm info!");
380 MCObjectFileInfo MOFI
;
381 MCContext
Ctx(MAI
.get(), MRI
.get(), &MOFI
, &SrcMgr
);
382 MOFI
.InitMCObjectFileInfo(TheTriple
, /* PIC= */ false, Ctx
);
384 std::unique_ptr
<buffer_ostream
> BOS
;
386 mca::CodeRegions
Regions(SrcMgr
);
387 MCStreamerWrapper
Str(Ctx
, Regions
);
389 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
391 std::unique_ptr
<MCInstrAnalysis
> MCIA(
392 TheTarget
->createMCInstrAnalysis(MCII
.get()));
394 if (!MCPU
.compare("native"))
395 MCPU
= llvm::sys::getHostCPUName();
397 std::unique_ptr
<MCSubtargetInfo
> STI(
398 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, /* FeaturesStr */ ""));
399 if (!STI
->isCPUStringValid(MCPU
))
402 if (!PrintInstructionTables
&& !STI
->getSchedModel().isOutOfOrder()) {
403 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
404 << "' is an in-order cpu.\n";
408 if (!STI
->getSchedModel().hasInstrSchedModel()) {
410 << "unable to find instruction-level scheduling information for"
411 << " target triple '" << TheTriple
.normalize() << "' and cpu '" << MCPU
414 if (STI
->getSchedModel().InstrItineraries
)
416 << "cpu '" << MCPU
<< "' provides itineraries. However, "
417 << "instruction itineraries are currently unsupported.\n";
421 std::unique_ptr
<MCAsmParser
> P(createMCAsmParser(SrcMgr
, Ctx
, Str
, *MAI
));
422 MCAsmLexer
&Lexer
= P
->getLexer();
423 MCACommentConsumer
CC(Regions
);
424 Lexer
.setCommentConsumer(&CC
);
426 if (AssembleInput(*P
, TheTarget
, *STI
, *MCII
, MCOptions
))
429 if (Regions
.empty()) {
430 WithColor::error() << "no assembly instructions found.\n";
434 // Now initialize the output file.
435 auto OF
= getOutputStream();
436 if (std::error_code EC
= OF
.getError()) {
437 WithColor::error() << EC
.message() << '\n';
441 unsigned AssemblerDialect
= P
->getAssemblerDialect();
442 if (OutputAsmVariant
>= 0)
443 AssemblerDialect
= static_cast<unsigned>(OutputAsmVariant
);
444 std::unique_ptr
<MCInstPrinter
> IP(TheTarget
->createMCInstPrinter(
445 Triple(TripleName
), AssemblerDialect
, *MAI
, *MCII
, *MRI
));
448 << "unable to create instruction printer for target triple '"
449 << TheTriple
.normalize() << "' with assembly variant "
450 << AssemblerDialect
<< ".\n";
454 std::unique_ptr
<llvm::ToolOutputFile
> TOF
= std::move(*OF
);
456 const MCSchedModel
&SM
= STI
->getSchedModel();
458 unsigned Width
= SM
.IssueWidth
;
460 Width
= DispatchWidth
;
462 // Create an instruction builder.
463 mca::InstrBuilder
IB(*STI
, *MCII
, *MRI
, *MCIA
, *IP
);
465 // Create a context to control ownership of the pipeline hardware.
466 mca::Context
MCA(*MRI
, *STI
);
468 mca::PipelineOptions
PO(Width
, RegisterFileSize
, LoadQueueSize
,
469 StoreQueueSize
, AssumeNoAlias
);
471 // Number each region in the sequence.
472 unsigned RegionIdx
= 0;
473 for (const std::unique_ptr
<mca::CodeRegion
> &Region
: Regions
) {
474 // Skip empty code regions.
478 // Don't print the header of this region if it is the default region, and
479 // it doesn't have an end location.
480 if (Region
->startLoc().isValid() || Region
->endLoc().isValid()) {
481 TOF
->os() << "\n[" << RegionIdx
++ << "] Code Region";
482 StringRef Desc
= Region
->getDescription();
484 TOF
->os() << " - " << Desc
;
488 mca::SourceMgr
S(Region
->getInstructions(),
489 PrintInstructionTables
? 1 : Iterations
);
491 if (PrintInstructionTables
) {
492 // Create a pipeline, stages, and a printer.
493 auto P
= llvm::make_unique
<mca::Pipeline
>();
494 P
->appendStage(llvm::make_unique
<mca::FetchStage
>(IB
, S
));
495 P
->appendStage(llvm::make_unique
<mca::InstructionTables
>(SM
, IB
));
496 mca::PipelinePrinter
Printer(*P
);
498 // Create the views for this pipeline, execute, and emit a report.
499 if (PrintInstructionInfoView
) {
501 llvm::make_unique
<mca::InstructionInfoView
>(*STI
, *MCII
, S
, *IP
));
504 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, S
));
507 report_fatal_error(toString(std::move(Err
)));
508 Printer
.printReport(TOF
->os());
512 // Create a basic pipeline simulating an out-of-order backend.
513 auto P
= MCA
.createDefaultPipeline(PO
, IB
, S
);
514 mca::PipelinePrinter
Printer(*P
);
516 if (PrintSummaryView
)
517 Printer
.addView(llvm::make_unique
<mca::SummaryView
>(SM
, S
, Width
));
519 if (PrintInstructionInfoView
)
521 llvm::make_unique
<mca::InstructionInfoView
>(*STI
, *MCII
, S
, *IP
));
523 if (PrintDispatchStats
)
524 Printer
.addView(llvm::make_unique
<mca::DispatchStatistics
>());
526 if (PrintSchedulerStats
)
527 Printer
.addView(llvm::make_unique
<mca::SchedulerStatistics
>(*STI
));
529 if (PrintRetireStats
)
530 Printer
.addView(llvm::make_unique
<mca::RetireControlUnitStatistics
>());
532 if (PrintRegisterFileStats
)
533 Printer
.addView(llvm::make_unique
<mca::RegisterFileStatistics
>(*STI
));
535 if (PrintResourcePressureView
)
537 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, S
));
539 if (PrintTimelineView
) {
540 Printer
.addView(llvm::make_unique
<mca::TimelineView
>(
541 *STI
, *IP
, S
, TimelineMaxIterations
, TimelineMaxCycles
));
546 report_fatal_error(toString(std::move(Err
)));
547 Printer
.printReport(TOF
->os());
549 // Clear the InstrBuilder internal state in preparation for another round.