OSDN Git Service

[llvm-mca] Fix header comments. NFC.
[android-x86/external-llvm.git] / 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 "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"
53
54 using namespace llvm;
55
56 static cl::OptionCategory ToolOptions("Tool Options");
57 static cl::OptionCategory ViewOptions("View Options");
58
59 static cl::opt<std::string> InputFilename(cl::Positional,
60                                           cl::desc("<input file>"),
61                                           cl::cat(ToolOptions), cl::init("-"));
62
63 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
64                                            cl::init("-"), cl::cat(ToolOptions),
65                                            cl::value_desc("filename"));
66
67 static cl::opt<std::string>
68     ArchName("march",
69              cl::desc("Target arch to assemble for, "
70                       "see -version for available targets"),
71              cl::cat(ToolOptions));
72
73 static cl::opt<std::string>
74     TripleName("mtriple",
75                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 temporary 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> PrintSchedulerStats("scheduler-stats",
113                                          cl::desc("Print scheduler statistics"),
114                                          cl::cat(ViewOptions), cl::init(false));
115
116 static cl::opt<bool>
117     PrintRetireStats("retire-stats",
118                      cl::desc("Print retire control unit statistics"),
119                      cl::cat(ViewOptions), cl::init(false));
120
121 static cl::opt<bool> PrintResourcePressureView(
122     "resource-pressure",
123     cl::desc("Print the resource pressure view (enabled by default)"),
124     cl::cat(ViewOptions), cl::init(true));
125
126 static cl::opt<bool> PrintTimelineView("timeline",
127                                        cl::desc("Print the timeline view"),
128                                        cl::cat(ViewOptions), cl::init(false));
129
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));
134
135 static cl::opt<unsigned> TimelineMaxCycles(
136     "timeline-max-cycles",
137     cl::desc(
138         "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
139     cl::cat(ViewOptions), cl::init(80));
140
141 static cl::opt<bool>
142     AssumeNoAlias("noalias",
143                   cl::desc("If set, assume that loads and stores do not alias"),
144                   cl::cat(ToolOptions), cl::init(true));
145
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));
150
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));
155
156 static cl::opt<bool>
157     PrintInstructionTables("instruction-tables",
158                            cl::desc("Print instruction tables"),
159                            cl::cat(ToolOptions), cl::init(false));
160
161 static cl::opt<bool> PrintInstructionInfoView(
162     "instruction-info",
163     cl::desc("Print the instruction info view (enabled by default)"),
164     cl::cat(ViewOptions), cl::init(true));
165
166 static cl::opt<bool> EnableAllStats("all-stats",
167                                     cl::desc("Print all hardware statistics"),
168                                     cl::cat(ViewOptions), cl::init(false));
169
170 static cl::opt<bool>
171     EnableAllViews("all-views",
172                    cl::desc("Print all views including hardware statistics"),
173                    cl::cat(ViewOptions), cl::init(false));
174
175 namespace {
176
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);
182
183   // Get the target specific parser.
184   std::string Error;
185   const Target *TheTarget =
186       TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
187   if (!TheTarget) {
188     errs() << ProgName << ": " << Error;
189     return nullptr;
190   }
191
192   // Return the found target.
193   return TheTarget;
194 }
195
196 // A comment consumer that parses strings.
197 // The only valid tokens are strings.
198 class MCACommentConsumer : public AsmCommentConsumer {
199 public:
200   mca::CodeRegions &Regions;
201
202   MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
203   void HandleComment(SMLoc Loc, StringRef CommentText) override {
204     // Skip empty comments.
205     StringRef Comment(CommentText);
206     if (Comment.empty())
207       return;
208
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.
213       return;
214
215     Comment = Comment.drop_front(Position);
216     if (Comment.consume_front("LLVM-MCA-END")) {
217       Regions.endRegion(Loc);
218       return;
219     }
220
221     // Now try to parse string LLVM-MCA-BEGIN
222     if (!Comment.consume_front("LLVM-MCA-BEGIN"))
223       return;
224
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);
231   }
232 };
233
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));
239
240   if (!TAP) {
241     WithColor::error() << "this target does not support assembly parsing.\n";
242     return 1;
243   }
244
245   Parser.setTargetParser(*TAP);
246   return Parser.Run(false);
247 }
248
249 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
250   if (OutputFilename == "")
251     OutputFilename = "-";
252   std::error_code EC;
253   auto Out =
254       llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
255   if (!EC)
256     return std::move(Out);
257   return EC;
258 }
259
260 class MCStreamerWrapper final : public MCStreamer {
261   mca::CodeRegions &Regions;
262
263 public:
264   MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
265       : MCStreamer(Context), Regions(R) {}
266
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));
271   }
272
273   bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
274     return true;
275   }
276
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 {}
286
287   const std::vector<std::unique_ptr<const MCInst>> &
288   GetInstructionSequence(unsigned Index) const {
289     return Regions.getInstructionSequence(Index);
290   }
291 };
292 } // end of anonymous namespace
293
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();
297 }
298
299 static void processViewOptions() {
300   if (!EnableAllViews.getNumOccurrences() &&
301       !EnableAllStats.getNumOccurrences())
302     return;
303
304   if (EnableAllViews.getNumOccurrences()) {
305     processOptionImpl(PrintResourcePressureView, EnableAllViews);
306     processOptionImpl(PrintTimelineView, EnableAllViews);
307     processOptionImpl(PrintInstructionInfoView, EnableAllViews);
308   }
309
310   const cl::opt<bool> &Default =
311       EnableAllViews.getPosition() < EnableAllStats.getPosition()
312           ? EnableAllStats
313           : EnableAllViews;
314   processOptionImpl(PrintRegisterFileStats, Default);
315   processOptionImpl(PrintDispatchStats, Default);
316   processOptionImpl(PrintSchedulerStats, Default);
317   processOptionImpl(PrintRetireStats, Default);
318 }
319
320 int main(int argc, char **argv) {
321   InitLLVM X(argc, argv);
322
323   // Initialize targets and assembly parsers.
324   llvm::InitializeAllTargetInfos();
325   llvm::InitializeAllTargetMCs();
326   llvm::InitializeAllAsmParsers();
327
328   // Enable printing of available targets when flag --version is specified.
329   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
330
331   cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
332
333   // Parse flags and initialize target options.
334   cl::ParseCommandLineOptions(argc, argv,
335                               "llvm machine code performance analyzer.\n");
336
337   MCTargetOptions MCOptions;
338   MCOptions.PreserveAsmComments = false;
339
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);
345   if (!TheTarget)
346     return 1;
347
348   // GetTarget() may replaced TripleName with a default triple.
349   // For safety, reconstruct the Triple object.
350   Triple TheTriple(TripleName);
351
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';
356     return 1;
357   }
358
359   // Apply overrides to llvm-mca specific options.
360   processViewOptions();
361
362   SourceMgr SrcMgr;
363
364   // Tell SrcMgr about this buffer, which is what the parser will pick up.
365   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
366
367   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
368   assert(MRI && "Unable to create target register info!");
369
370   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
371   assert(MAI && "Unable to create target asm info!");
372
373   MCObjectFileInfo MOFI;
374   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
375   MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
376
377   std::unique_ptr<buffer_ostream> BOS;
378
379   mca::CodeRegions Regions(SrcMgr);
380   MCStreamerWrapper Str(Ctx, Regions);
381
382   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
383
384   if (!MCPU.compare("native"))
385     MCPU = llvm::sys::getHostCPUName();
386
387   std::unique_ptr<MCSubtargetInfo> STI(
388       TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
389   if (!STI->isCPUStringValid(MCPU))
390     return 1;
391
392   if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
393     WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
394                        << "' is an in-order cpu.\n";
395     return 1;
396   }
397
398   if (!STI->getSchedModel().hasInstrSchedModel()) {
399     WithColor::error()
400         << "unable to find instruction-level scheduling information for"
401         << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
402         << "'.\n";
403
404     if (STI->getSchedModel().InstrItineraries)
405       WithColor::note()
406           << "cpu '" << MCPU << "' provides itineraries. However, "
407           << "instruction itineraries are currently unsupported.\n";
408     return 1;
409   }
410
411   std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
412   MCAsmLexer &Lexer = P->getLexer();
413   MCACommentConsumer CC(Regions);
414   Lexer.setCommentConsumer(&CC);
415
416   if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
417     return 1;
418
419   if (Regions.empty()) {
420     WithColor::error() << "no assembly instructions found.\n";
421     return 1;
422   }
423
424   // Now initialize the output file.
425   auto OF = getOutputStream();
426   if (std::error_code EC = OF.getError()) {
427     WithColor::error() << EC.message() << '\n';
428     return 1;
429   }
430
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));
436   if (!IP) {
437     WithColor::error()
438         << "unable to create instruction printer for target triple '"
439         << TheTriple.normalize() << "' with assembly variant "
440         << AssemblerDialect << ".\n";
441     return 1;
442   }
443
444   std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
445
446   const MCSchedModel &SM = STI->getSchedModel();
447
448   unsigned Width = SM.IssueWidth;
449   if (DispatchWidth)
450     Width = DispatchWidth;
451
452   // Create an instruction builder.
453   mca::InstrBuilder IB(*STI, *MCII);
454
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.
459     if (Region->empty())
460       continue;
461
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();
467       if (!Desc.empty())
468         TOF->os() << " - " << Desc;
469       TOF->os() << "\n\n";
470     }
471
472     mca::SourceMgr S(Region->getInstructions(),
473                      PrintInstructionTables ? 1 : Iterations);
474
475     if (PrintInstructionTables) {
476       mca::InstructionTables IT(STI->getSchedModel(), IB, S);
477
478       if (PrintInstructionInfoView) {
479         IT.addView(
480             llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
481       }
482
483       IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
484       IT.run();
485       IT.printReport(TOF->os());
486       continue;
487     }
488
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);
497
498     Printer.addView(llvm::make_unique<mca::SummaryView>(SM, S, Width));
499     if (PrintInstructionInfoView)
500       Printer.addView(
501           llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
502
503     if (PrintDispatchStats)
504       Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
505
506     if (PrintSchedulerStats)
507       Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
508
509     if (PrintRetireStats)
510       Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
511
512     if (PrintRegisterFileStats)
513       Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
514
515     if (PrintResourcePressureView)
516       Printer.addView(
517           llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
518
519     if (PrintTimelineView) {
520       Printer.addView(llvm::make_unique<mca::TimelineView>(
521           *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
522     }
523
524     B.run();
525     Printer.printReport(TOF->os());
526   }
527
528   TOF->keep();
529   return 0;
530 }