]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-mca/llvm-mca.cpp
MFV: r344395
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-mca / llvm-mca.cpp
1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //   llvm-mca [options] <file-name>
14 //      -march <type>
15 //      -mcpu <cpu>
16 //      -o <file>
17 //
18 // The target defaults to the host target.
19 // The cpu defaults to the 'native' host cpu.
20 // The output defaults to standard output.
21 //
22 //===----------------------------------------------------------------------===//
23
24 #include "CodeRegion.h"
25 #include "Context.h"
26 #include "DispatchStatistics.h"
27 #include "FetchStage.h"
28 #include "InstructionInfoView.h"
29 #include "InstructionTables.h"
30 #include "Pipeline.h"
31 #include "PipelinePrinter.h"
32 #include "RegisterFileStatistics.h"
33 #include "ResourcePressureView.h"
34 #include "RetireControlUnitStatistics.h"
35 #include "SchedulerStatistics.h"
36 #include "SummaryView.h"
37 #include "TimelineView.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/ErrorOr.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/InitLLVM.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/ToolOutputFile.h"
54 #include "llvm/Support/WithColor.h"
55
56 using namespace llvm;
57
58 static cl::OptionCategory ToolOptions("Tool Options");
59 static cl::OptionCategory ViewOptions("View Options");
60
61 static cl::opt<std::string> InputFilename(cl::Positional,
62                                           cl::desc("<input file>"),
63                                           cl::cat(ToolOptions), cl::init("-"));
64
65 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
66                                            cl::init("-"), cl::cat(ToolOptions),
67                                            cl::value_desc("filename"));
68
69 static cl::opt<std::string>
70     ArchName("march", cl::desc("Target arch to assemble for, "
71                                "see -version for available targets"),
72              cl::cat(ToolOptions));
73
74 static cl::opt<std::string>
75     TripleName("mtriple", cl::desc("Target triple to assemble for, "
76                                    "see -version for available targets"),
77                cl::cat(ToolOptions));
78
79 static cl::opt<std::string>
80     MCPU("mcpu",
81          cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82          cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
83
84 static cl::opt<int>
85     OutputAsmVariant("output-asm-variant",
86                      cl::desc("Syntax variant to use for output printing"),
87                      cl::cat(ToolOptions), cl::init(-1));
88
89 static cl::opt<unsigned> Iterations("iterations",
90                                     cl::desc("Number of iterations to run"),
91                                     cl::cat(ToolOptions), cl::init(0));
92
93 static cl::opt<unsigned>
94     DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
95                   cl::cat(ToolOptions), cl::init(0));
96
97 static cl::opt<unsigned>
98     RegisterFileSize("register-file-size",
99                      cl::desc("Maximum number of physical registers which can "
100                               "be used for register mappings"),
101                      cl::cat(ToolOptions), cl::init(0));
102
103 static cl::opt<bool>
104     PrintRegisterFileStats("register-file-stats",
105                            cl::desc("Print register file statistics"),
106                            cl::cat(ViewOptions), cl::init(false));
107
108 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
109                                         cl::desc("Print dispatch statistics"),
110                                         cl::cat(ViewOptions), cl::init(false));
111
112 static cl::opt<bool>
113     PrintSummaryView("summary-view", cl::Hidden,
114                      cl::desc("Print summary view (enabled by default)"),
115                      cl::cat(ViewOptions), cl::init(true));
116
117 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
118                                          cl::desc("Print scheduler statistics"),
119                                          cl::cat(ViewOptions), cl::init(false));
120
121 static cl::opt<bool>
122     PrintRetireStats("retire-stats",
123                      cl::desc("Print retire control unit statistics"),
124                      cl::cat(ViewOptions), cl::init(false));
125
126 static cl::opt<bool> PrintResourcePressureView(
127     "resource-pressure",
128     cl::desc("Print the resource pressure view (enabled by default)"),
129     cl::cat(ViewOptions), cl::init(true));
130
131 static cl::opt<bool> PrintTimelineView("timeline",
132                                        cl::desc("Print the timeline view"),
133                                        cl::cat(ViewOptions), cl::init(false));
134
135 static cl::opt<unsigned> TimelineMaxIterations(
136     "timeline-max-iterations",
137     cl::desc("Maximum number of iterations to print in timeline view"),
138     cl::cat(ViewOptions), cl::init(0));
139
140 static cl::opt<unsigned> TimelineMaxCycles(
141     "timeline-max-cycles",
142     cl::desc(
143         "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
144     cl::cat(ViewOptions), cl::init(80));
145
146 static cl::opt<bool>
147     AssumeNoAlias("noalias",
148                   cl::desc("If set, assume that loads and stores do not alias"),
149                   cl::cat(ToolOptions), cl::init(true));
150
151 static cl::opt<unsigned>
152     LoadQueueSize("lqueue",
153                   cl::desc("Size of the load queue (unbound by default)"),
154                   cl::cat(ToolOptions), cl::init(0));
155
156 static cl::opt<unsigned>
157     StoreQueueSize("squeue",
158                    cl::desc("Size of the store queue (unbound by default)"),
159                    cl::cat(ToolOptions), cl::init(0));
160
161 static cl::opt<bool>
162     PrintInstructionTables("instruction-tables",
163                            cl::desc("Print instruction tables"),
164                            cl::cat(ToolOptions), cl::init(false));
165
166 static cl::opt<bool> PrintInstructionInfoView(
167     "instruction-info",
168     cl::desc("Print the instruction info view (enabled by default)"),
169     cl::cat(ViewOptions), cl::init(true));
170
171 static cl::opt<bool> EnableAllStats("all-stats",
172                                     cl::desc("Print all hardware statistics"),
173                                     cl::cat(ViewOptions), cl::init(false));
174
175 static cl::opt<bool>
176     EnableAllViews("all-views",
177                    cl::desc("Print all views including hardware statistics"),
178                    cl::cat(ViewOptions), cl::init(false));
179
180 namespace {
181
182 const Target *getTarget(const char *ProgName) {
183   TripleName = Triple::normalize(TripleName);
184   if (TripleName.empty())
185     TripleName = Triple::normalize(sys::getDefaultTargetTriple());
186   Triple TheTriple(TripleName);
187
188   // Get the target specific parser.
189   std::string Error;
190   const Target *TheTarget =
191       TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
192   if (!TheTarget) {
193     errs() << ProgName << ": " << Error;
194     return nullptr;
195   }
196
197   // Return the found target.
198   return TheTarget;
199 }
200
201 // A comment consumer that parses strings.
202 // The only valid tokens are strings.
203 class MCACommentConsumer : public AsmCommentConsumer {
204 public:
205   mca::CodeRegions &Regions;
206
207   MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
208   void HandleComment(SMLoc Loc, StringRef CommentText) override {
209     // Skip empty comments.
210     StringRef Comment(CommentText);
211     if (Comment.empty())
212       return;
213
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.
218       return;
219
220     Comment = Comment.drop_front(Position);
221     if (Comment.consume_front("LLVM-MCA-END")) {
222       Regions.endRegion(Loc);
223       return;
224     }
225
226     // Now try to parse string LLVM-MCA-BEGIN
227     if (!Comment.consume_front("LLVM-MCA-BEGIN"))
228       return;
229
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);
236   }
237 };
238
239 int AssembleInput(const char *ProgName, MCAsmParser &Parser,
240                   const Target *TheTarget, MCSubtargetInfo &STI,
241                   MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
242   std::unique_ptr<MCTargetAsmParser> TAP(
243       TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
244
245   if (!TAP) {
246     WithColor::error() << "this target does not support assembly parsing.\n";
247     return 1;
248   }
249
250   Parser.setTargetParser(*TAP);
251   return Parser.Run(false);
252 }
253
254 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
255   if (OutputFilename == "")
256     OutputFilename = "-";
257   std::error_code EC;
258   auto Out =
259       llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
260   if (!EC)
261     return std::move(Out);
262   return EC;
263 }
264
265 class MCStreamerWrapper final : public MCStreamer {
266   mca::CodeRegions &Regions;
267
268 public:
269   MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
270       : MCStreamer(Context), Regions(R) {}
271
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));
276   }
277
278   bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
279     return true;
280   }
281
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 {}
292
293   const std::vector<std::unique_ptr<const MCInst>> &
294   GetInstructionSequence(unsigned Index) const {
295     return Regions.getInstructionSequence(Index);
296   }
297 };
298 } // end of anonymous namespace
299
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();
303 }
304
305 static void processViewOptions() {
306   if (!EnableAllViews.getNumOccurrences() &&
307       !EnableAllStats.getNumOccurrences())
308     return;
309
310   if (EnableAllViews.getNumOccurrences()) {
311     processOptionImpl(PrintSummaryView, EnableAllViews);
312     processOptionImpl(PrintResourcePressureView, EnableAllViews);
313     processOptionImpl(PrintTimelineView, EnableAllViews);
314     processOptionImpl(PrintInstructionInfoView, EnableAllViews);
315   }
316
317   const cl::opt<bool> &Default =
318       EnableAllViews.getPosition() < EnableAllStats.getPosition()
319           ? EnableAllStats
320           : EnableAllViews;
321   processOptionImpl(PrintSummaryView, Default);
322   processOptionImpl(PrintRegisterFileStats, Default);
323   processOptionImpl(PrintDispatchStats, Default);
324   processOptionImpl(PrintSchedulerStats, Default);
325   processOptionImpl(PrintRetireStats, Default);
326 }
327
328 int main(int argc, char **argv) {
329   InitLLVM X(argc, argv);
330
331   // Initialize targets and assembly parsers.
332   llvm::InitializeAllTargetInfos();
333   llvm::InitializeAllTargetMCs();
334   llvm::InitializeAllAsmParsers();
335
336   // Enable printing of available targets when flag --version is specified.
337   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
338
339   cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
340
341   // Parse flags and initialize target options.
342   cl::ParseCommandLineOptions(argc, argv,
343                               "llvm machine code performance analyzer.\n");
344
345   MCTargetOptions MCOptions;
346   MCOptions.PreserveAsmComments = false;
347
348   // Get the target from the triple. If a triple is not specified, then select
349   // the default triple for the host. If the triple doesn't correspond to any
350   // registered target, then exit with an error message.
351   const char *ProgName = argv[0];
352   const Target *TheTarget = getTarget(ProgName);
353   if (!TheTarget)
354     return 1;
355
356   // GetTarget() may replaced TripleName with a default triple.
357   // For safety, reconstruct the Triple object.
358   Triple TheTriple(TripleName);
359
360   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
361       MemoryBuffer::getFileOrSTDIN(InputFilename);
362   if (std::error_code EC = BufferPtr.getError()) {
363     WithColor::error() << InputFilename << ": " << EC.message() << '\n';
364     return 1;
365   }
366
367   // Apply overrides to llvm-mca specific options.
368   processViewOptions();
369
370   SourceMgr SrcMgr;
371
372   // Tell SrcMgr about this buffer, which is what the parser will pick up.
373   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
374
375   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
376   assert(MRI && "Unable to create target register info!");
377
378   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
379   assert(MAI && "Unable to create target asm info!");
380
381   MCObjectFileInfo MOFI;
382   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
383   MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
384
385   std::unique_ptr<buffer_ostream> BOS;
386
387   mca::CodeRegions Regions(SrcMgr);
388   MCStreamerWrapper Str(Ctx, Regions);
389
390   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
391
392   std::unique_ptr<MCInstrAnalysis> MCIA(
393       TheTarget->createMCInstrAnalysis(MCII.get()));
394
395   if (!MCPU.compare("native"))
396     MCPU = llvm::sys::getHostCPUName();
397
398   std::unique_ptr<MCSubtargetInfo> STI(
399       TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
400   if (!STI->isCPUStringValid(MCPU))
401     return 1;
402
403   if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
404     WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
405                        << "' is an in-order cpu.\n";
406     return 1;
407   }
408
409   if (!STI->getSchedModel().hasInstrSchedModel()) {
410     WithColor::error()
411         << "unable to find instruction-level scheduling information for"
412         << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
413         << "'.\n";
414
415     if (STI->getSchedModel().InstrItineraries)
416       WithColor::note()
417           << "cpu '" << MCPU << "' provides itineraries. However, "
418           << "instruction itineraries are currently unsupported.\n";
419     return 1;
420   }
421
422   std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
423   MCAsmLexer &Lexer = P->getLexer();
424   MCACommentConsumer CC(Regions);
425   Lexer.setCommentConsumer(&CC);
426
427   if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
428     return 1;
429
430   if (Regions.empty()) {
431     WithColor::error() << "no assembly instructions found.\n";
432     return 1;
433   }
434
435   // Now initialize the output file.
436   auto OF = getOutputStream();
437   if (std::error_code EC = OF.getError()) {
438     WithColor::error() << EC.message() << '\n';
439     return 1;
440   }
441
442   unsigned AssemblerDialect = P->getAssemblerDialect();
443   if (OutputAsmVariant >= 0)
444     AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
445   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
446       Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
447   if (!IP) {
448     WithColor::error()
449         << "unable to create instruction printer for target triple '"
450         << TheTriple.normalize() << "' with assembly variant "
451         << AssemblerDialect << ".\n";
452     return 1;
453   }
454
455   std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
456
457   const MCSchedModel &SM = STI->getSchedModel();
458
459   unsigned Width = SM.IssueWidth;
460   if (DispatchWidth)
461     Width = DispatchWidth;
462
463   // Create an instruction builder.
464   mca::InstrBuilder IB(*STI, *MCII, *MRI, *MCIA, *IP);
465
466   // Create a context to control ownership of the pipeline hardware.
467   mca::Context MCA(*MRI, *STI);
468
469   mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
470                           StoreQueueSize, AssumeNoAlias);
471
472   // Number each region in the sequence.
473   unsigned RegionIdx = 0;
474   for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
475     // Skip empty code regions.
476     if (Region->empty())
477       continue;
478
479     // Don't print the header of this region if it is the default region, and
480     // it doesn't have an end location.
481     if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
482       TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
483       StringRef Desc = Region->getDescription();
484       if (!Desc.empty())
485         TOF->os() << " - " << Desc;
486       TOF->os() << "\n\n";
487     }
488
489     mca::SourceMgr S(Region->getInstructions(),
490                      PrintInstructionTables ? 1 : Iterations);
491
492     if (PrintInstructionTables) {
493       //  Create a pipeline, stages, and a printer.
494       auto P = llvm::make_unique<mca::Pipeline>();
495       P->appendStage(llvm::make_unique<mca::FetchStage>(IB, S));
496       P->appendStage(llvm::make_unique<mca::InstructionTables>(SM, IB));
497       mca::PipelinePrinter Printer(*P);
498
499       // Create the views for this pipeline, execute, and emit a report.
500       if (PrintInstructionInfoView) {
501         Printer.addView(
502             llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
503       }
504       Printer.addView(
505           llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
506       P->run();
507       Printer.printReport(TOF->os());
508       continue;
509     }
510
511     // Create a basic pipeline simulating an out-of-order backend.
512     auto P = MCA.createDefaultPipeline(PO, IB, S);
513     mca::PipelinePrinter Printer(*P);
514
515     if (PrintSummaryView)
516       Printer.addView(llvm::make_unique<mca::SummaryView>(SM, S, Width));
517
518     if (PrintInstructionInfoView)
519       Printer.addView(
520           llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
521
522     if (PrintDispatchStats)
523       Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
524
525     if (PrintSchedulerStats)
526       Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
527
528     if (PrintRetireStats)
529       Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
530
531     if (PrintRegisterFileStats)
532       Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
533
534     if (PrintResourcePressureView)
535       Printer.addView(
536           llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
537
538     if (PrintTimelineView) {
539       Printer.addView(llvm::make_unique<mca::TimelineView>(
540           *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
541     }
542
543     P->run();
544     Printer.printReport(TOF->os());
545
546     // Clear the InstrBuilder internal state in preparation for another round.
547     IB.clear();
548   }
549
550   TOF->keep();
551   return 0;
552 }