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 "BackendPrinter.h"
25 #include "CodeRegion.h"
26 #include "DispatchStatistics.h"
27 #include "FetchStage.h"
28 #include "InstructionInfoView.h"
29 #include "InstructionTables.h"
30 #include "RegisterFileStatistics.h"
31 #include "ResourcePressureView.h"
32 #include "RetireControlUnitStatistics.h"
33 #include "SchedulerStatistics.h"
34 #include "SummaryView.h"
35 #include "TimelineView.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCObjectFileInfo.h"
39 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorOr.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/InitLLVM.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/WithColor.h"
56 static cl::OptionCategory ToolOptions("Tool Options");
57 static cl::OptionCategory ViewOptions("View Options");
59 static cl::opt<std::string> InputFilename(cl::Positional,
60 cl::desc("<input file>"),
61 cl::cat(ToolOptions), cl::init("-"));
63 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
64 cl::init("-"), cl::cat(ToolOptions),
65 cl::value_desc("filename"));
67 static cl::opt<std::string>
69 cl::desc("Target arch to assemble for, "
70 "see -version for available targets"),
71 cl::cat(ToolOptions));
73 static cl::opt<std::string>
75 cl::desc("Target triple to assemble for, "
76 "see -version for available targets"),
77 cl::cat(ToolOptions));
79 static cl::opt<std::string>
81 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
85 OutputAsmVariant("output-asm-variant",
86 cl::desc("Syntax variant to use for output printing"),
87 cl::cat(ToolOptions), cl::init(-1));
89 static cl::opt<unsigned> Iterations("iterations",
90 cl::desc("Number of iterations to run"),
91 cl::cat(ToolOptions), cl::init(0));
93 static cl::opt<unsigned>
94 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
95 cl::cat(ToolOptions), cl::init(0));
97 static cl::opt<unsigned>
98 RegisterFileSize("register-file-size",
99 cl::desc("Maximum number of temporary registers which can "
100 "be used for register mappings"),
101 cl::cat(ToolOptions), cl::init(0));
104 PrintRegisterFileStats("register-file-stats",
105 cl::desc("Print register file statistics"),
106 cl::cat(ViewOptions), cl::init(false));
108 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
109 cl::desc("Print dispatch statistics"),
110 cl::cat(ViewOptions), cl::init(false));
112 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
113 cl::desc("Print scheduler statistics"),
114 cl::cat(ViewOptions), cl::init(false));
117 PrintRetireStats("retire-stats",
118 cl::desc("Print retire control unit statistics"),
119 cl::cat(ViewOptions), cl::init(false));
121 static cl::opt<bool> PrintResourcePressureView(
123 cl::desc("Print the resource pressure view (enabled by default)"),
124 cl::cat(ViewOptions), cl::init(true));
126 static cl::opt<bool> PrintTimelineView("timeline",
127 cl::desc("Print the timeline view"),
128 cl::cat(ViewOptions), cl::init(false));
130 static cl::opt<unsigned> TimelineMaxIterations(
131 "timeline-max-iterations",
132 cl::desc("Maximum number of iterations to print in timeline view"),
133 cl::cat(ViewOptions), cl::init(0));
135 static cl::opt<unsigned> TimelineMaxCycles(
136 "timeline-max-cycles",
138 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
139 cl::cat(ViewOptions), cl::init(80));
142 AssumeNoAlias("noalias",
143 cl::desc("If set, assume that loads and stores do not alias"),
144 cl::cat(ToolOptions), cl::init(true));
146 static cl::opt<unsigned>
147 LoadQueueSize("lqueue",
148 cl::desc("Size of the load queue (unbound by default)"),
149 cl::cat(ToolOptions), cl::init(0));
151 static cl::opt<unsigned>
152 StoreQueueSize("squeue",
153 cl::desc("Size of the store queue (unbound by default)"),
154 cl::cat(ToolOptions), cl::init(0));
157 PrintInstructionTables("instruction-tables",
158 cl::desc("Print instruction tables"),
159 cl::cat(ToolOptions), cl::init(false));
161 static cl::opt<bool> PrintInstructionInfoView(
163 cl::desc("Print the instruction info view (enabled by default)"),
164 cl::cat(ViewOptions), cl::init(true));
166 static cl::opt<bool> EnableAllStats("all-stats",
167 cl::desc("Print all hardware statistics"),
168 cl::cat(ViewOptions), cl::init(false));
171 EnableAllViews("all-views",
172 cl::desc("Print all views including hardware statistics"),
173 cl::cat(ViewOptions), cl::init(false));
177 const Target *getTarget(const char *ProgName) {
178 TripleName = Triple::normalize(TripleName);
179 if (TripleName.empty())
180 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
181 Triple TheTriple(TripleName);
183 // Get the target specific parser.
185 const Target *TheTarget =
186 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
188 errs() << ProgName << ": " << Error;
192 // Return the found target.
196 // A comment consumer that parses strings.
197 // The only valid tokens are strings.
198 class MCACommentConsumer : public AsmCommentConsumer {
200 mca::CodeRegions &Regions;
202 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
203 void HandleComment(SMLoc Loc, StringRef CommentText) override {
204 // Skip empty comments.
205 StringRef Comment(CommentText);
209 // Skip spaces and tabs
210 unsigned Position = Comment.find_first_not_of(" \t");
211 if (Position >= Comment.size())
212 // we reached the end of the comment. Bail out.
215 Comment = Comment.drop_front(Position);
216 if (Comment.consume_front("LLVM-MCA-END")) {
217 Regions.endRegion(Loc);
221 // Now try to parse string LLVM-MCA-BEGIN
222 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
225 // Skip spaces and tabs
226 Position = Comment.find_first_not_of(" \t");
227 if (Position < Comment.size())
228 Comment = Comment.drop_front(Position);
229 // Use the rest of the string as a descriptor for this code snippet.
230 Regions.beginRegion(Comment, Loc);
234 int AssembleInput(const char *ProgName, MCAsmParser &Parser,
235 const Target *TheTarget, MCSubtargetInfo &STI,
236 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
237 std::unique_ptr<MCTargetAsmParser> TAP(
238 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
241 WithColor::error() << "this target does not support assembly parsing.\n";
245 Parser.setTargetParser(*TAP);
246 return Parser.Run(false);
249 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
250 if (OutputFilename == "")
251 OutputFilename = "-";
254 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
256 return std::move(Out);
260 class MCStreamerWrapper final : public MCStreamer {
261 mca::CodeRegions &Regions;
264 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
265 : MCStreamer(Context), Regions(R) {}
267 // We only want to intercept the emission of new instructions.
268 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
269 bool /* unused */) override {
270 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
273 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
277 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
278 unsigned ByteAlignment) override {}
279 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
280 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
281 void EmitGPRel32Value(const MCExpr *Value) override {}
282 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
283 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
284 void EmitCOFFSymbolType(int Type) override {}
285 void EndCOFFSymbolDef() override {}
287 const std::vector<std::unique_ptr<const MCInst>> &
288 GetInstructionSequence(unsigned Index) const {
289 return Regions.getInstructionSequence(Index);
292 } // end of anonymous namespace
294 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
295 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
296 O = Default.getValue();
299 static void processViewOptions() {
300 if (!EnableAllViews.getNumOccurrences() &&
301 !EnableAllStats.getNumOccurrences())
304 if (EnableAllViews.getNumOccurrences()) {
305 processOptionImpl(PrintResourcePressureView, EnableAllViews);
306 processOptionImpl(PrintTimelineView, EnableAllViews);
307 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
310 const cl::opt<bool> &Default =
311 EnableAllViews.getPosition() < EnableAllStats.getPosition()
314 processOptionImpl(PrintRegisterFileStats, Default);
315 processOptionImpl(PrintDispatchStats, Default);
316 processOptionImpl(PrintSchedulerStats, Default);
317 processOptionImpl(PrintRetireStats, Default);
320 int main(int argc, char **argv) {
321 InitLLVM X(argc, argv);
323 // Initialize targets and assembly parsers.
324 llvm::InitializeAllTargetInfos();
325 llvm::InitializeAllTargetMCs();
326 llvm::InitializeAllAsmParsers();
328 // Enable printing of available targets when flag --version is specified.
329 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
331 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
333 // Parse flags and initialize target options.
334 cl::ParseCommandLineOptions(argc, argv,
335 "llvm machine code performance analyzer.\n");
337 MCTargetOptions MCOptions;
338 MCOptions.PreserveAsmComments = false;
340 // Get the target from the triple. If a triple is not specified, then select
341 // the default triple for the host. If the triple doesn't correspond to any
342 // registered target, then exit with an error message.
343 const char *ProgName = argv[0];
344 const Target *TheTarget = getTarget(ProgName);
348 // GetTarget() may replaced TripleName with a default triple.
349 // For safety, reconstruct the Triple object.
350 Triple TheTriple(TripleName);
352 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
353 MemoryBuffer::getFileOrSTDIN(InputFilename);
354 if (std::error_code EC = BufferPtr.getError()) {
355 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
359 // Apply overrides to llvm-mca specific options.
360 processViewOptions();
364 // Tell SrcMgr about this buffer, which is what the parser will pick up.
365 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
367 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
368 assert(MRI && "Unable to create target register info!");
370 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
371 assert(MAI && "Unable to create target asm info!");
373 MCObjectFileInfo MOFI;
374 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
375 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
377 std::unique_ptr<buffer_ostream> BOS;
379 mca::CodeRegions Regions(SrcMgr);
380 MCStreamerWrapper Str(Ctx, Regions);
382 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
384 if (!MCPU.compare("native"))
385 MCPU = llvm::sys::getHostCPUName();
387 std::unique_ptr<MCSubtargetInfo> STI(
388 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
389 if (!STI->isCPUStringValid(MCPU))
392 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
393 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
394 << "' is an in-order cpu.\n";
398 if (!STI->getSchedModel().hasInstrSchedModel()) {
400 << "unable to find instruction-level scheduling information for"
401 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
404 if (STI->getSchedModel().InstrItineraries)
406 << "cpu '" << MCPU << "' provides itineraries. However, "
407 << "instruction itineraries are currently unsupported.\n";
411 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
412 MCAsmLexer &Lexer = P->getLexer();
413 MCACommentConsumer CC(Regions);
414 Lexer.setCommentConsumer(&CC);
416 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
419 if (Regions.empty()) {
420 WithColor::error() << "no assembly instructions found.\n";
424 // Now initialize the output file.
425 auto OF = getOutputStream();
426 if (std::error_code EC = OF.getError()) {
427 WithColor::error() << EC.message() << '\n';
431 unsigned AssemblerDialect = P->getAssemblerDialect();
432 if (OutputAsmVariant >= 0)
433 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
434 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
435 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
438 << "unable to create instruction printer for target triple '"
439 << TheTriple.normalize() << "' with assembly variant "
440 << AssemblerDialect << ".\n";
444 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
446 const MCSchedModel &SM = STI->getSchedModel();
448 unsigned Width = SM.IssueWidth;
450 Width = DispatchWidth;
452 // Create an instruction builder.
453 mca::InstrBuilder IB(*STI, *MCII);
455 // Number each region in the sequence.
456 unsigned RegionIdx = 0;
457 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
458 // Skip empty code regions.
462 // Don't print the header of this region if it is the default region, and
463 // it doesn't have an end location.
464 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
465 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
466 StringRef Desc = Region->getDescription();
468 TOF->os() << " - " << Desc;
472 mca::SourceMgr S(Region->getInstructions(),
473 PrintInstructionTables ? 1 : Iterations);
475 if (PrintInstructionTables) {
476 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
478 if (PrintInstructionInfoView) {
480 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
483 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
485 IT.printReport(TOF->os());
489 // Ideally, I'd like to expose the pipeline building here,
490 // by registering all of the Stage instances.
491 // But for now, it's just this single puppy.
492 std::unique_ptr<mca::FetchStage> Fetch =
493 llvm::make_unique<mca::FetchStage>(IB, S);
494 mca::Backend B(*STI, *MRI, std::move(Fetch), Width, RegisterFileSize,
495 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
496 mca::BackendPrinter Printer(B);
498 Printer.addView(llvm::make_unique<mca::SummaryView>(SM, S, Width));
499 if (PrintInstructionInfoView)
501 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
503 if (PrintDispatchStats)
504 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
506 if (PrintSchedulerStats)
507 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
509 if (PrintRetireStats)
510 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
512 if (PrintRegisterFileStats)
513 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
515 if (PrintResourcePressureView)
517 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
519 if (PrintTimelineView) {
520 Printer.addView(llvm::make_unique<mca::TimelineView>(
521 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
525 Printer.printReport(TOF->os());