blob: 7b50196f418ebcef1d7c4c0e38d1a04612b56fac [file] [log] [blame]
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +00001//===-- 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 'generic'.
20// The output defaults to standard output.
21//
22//===----------------------------------------------------------------------===//
23
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000024#include "BackendPrinter.h"
25#include "BackendStatistics.h"
Andrea Di Biagioc6590122018-04-09 16:39:52 +000026#include "CodeRegion.h"
Andrea Di Biagio821f6502018-04-10 14:55:14 +000027#include "DispatchStatistics.h"
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +000028#include "InstructionInfoView.h"
Andrea Di Biagiod1569292018-03-26 12:04:53 +000029#include "InstructionTables.h"
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000030#include "RegisterFileStatistics.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000031#include "ResourcePressureView.h"
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +000032#include "SchedulerStatistics.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000033#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000034#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000035#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/MC/MCContext.h"
37#include "llvm/MC/MCObjectFileInfo.h"
38#include "llvm/MC/MCParser/MCTargetAsmParser.h"
39#include "llvm/MC/MCRegisterInfo.h"
40#include "llvm/MC/MCStreamer.h"
41#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000042#include "llvm/Support/ErrorOr.h"
43#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000044#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/Support/PrettyStackTrace.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/SourceMgr.h"
48#include "llvm/Support/TargetRegistry.h"
49#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000050#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000051
52using namespace llvm;
53
54static cl::opt<std::string>
55 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
56
57static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
58 cl::init("-"),
59 cl::value_desc("filename"));
60
61static cl::opt<std::string>
62 ArchName("march", cl::desc("Target arch to assemble for, "
63 "see -version for available targets"));
64
65static cl::opt<std::string>
66 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000067 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000068
69static cl::opt<std::string>
70 MCPU("mcpu",
71 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
72 cl::value_desc("cpu-name"), cl::init("generic"));
73
74static cl::opt<unsigned>
75 OutputAsmVariant("output-asm-variant",
76 cl::desc("Syntax variant to use for output printing"));
77
78static cl::opt<unsigned> Iterations("iterations",
79 cl::desc("Number of iterations to run"),
80 cl::init(0));
81
82static cl::opt<unsigned> DispatchWidth(
83 "dispatch",
84 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
85 cl::init(0));
86
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000087static cl::opt<unsigned>
88 RegisterFileSize("register-file-size",
89 cl::desc("Maximum number of temporary registers which can "
90 "be used for register mappings"),
91 cl::init(0));
92
Andrea Di Biagio29538c62018-03-23 11:33:09 +000093static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000094 PrintRegisterFileStats("register-file-stats",
95 cl::desc("Print register file statistics"),
96 cl::init(false));
97
98static cl::opt<bool>
Andrea Di Biagio821f6502018-04-10 14:55:14 +000099 PrintDispatchStats("dispatch-stats",
100 cl::desc("Print dispatch statistics"),
101 cl::init(false));
102
103static cl::opt<bool>
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000104 PrintiSchedulerStats("scheduler-stats",
105 cl::desc("Print scheduler statistics"),
106 cl::init(false));
107
108static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000109 PrintResourcePressureView("resource-pressure",
110 cl::desc("Print the resource pressure view"),
111 cl::init(true));
112
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000113static cl::opt<bool> PrintTimelineView("timeline",
114 cl::desc("Print the timeline view"),
115 cl::init(false));
116
117static cl::opt<unsigned> TimelineMaxIterations(
118 "timeline-max-iterations",
119 cl::desc("Maximum number of iterations to print in timeline view"),
120 cl::init(0));
121
122static cl::opt<unsigned> TimelineMaxCycles(
123 "timeline-max-cycles",
124 cl::desc(
125 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
126 cl::init(80));
127
128static cl::opt<bool> PrintModeVerbose("verbose",
129 cl::desc("Enable verbose output"),
130 cl::init(false));
131
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000132static cl::opt<bool> AssumeNoAlias(
133 "noalias",
134 cl::desc("If set, it assumes that loads and stores do not alias"),
135 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000136
137static cl::opt<unsigned>
138 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000139
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000140static cl::opt<unsigned>
141 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
142
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000143static cl::opt<bool>
144 PrintInstructionTables("instruction-tables",
145 cl::desc("Print instruction tables"),
146 cl::init(false));
147
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000148static cl::opt<bool>
149 PrintInstructionInfoView("instruction-info",
150 cl::desc("Print the instruction info view"),
151 cl::init(true));
152
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000153namespace {
154
155const Target *getTarget(const char *ProgName) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000156 TripleName = Triple::normalize(TripleName);
157 if (TripleName.empty())
158 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
159 Triple TheTriple(TripleName);
160
161 // Get the target specific parser.
162 std::string Error;
163 const Target *TheTarget =
164 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
165 if (!TheTarget) {
166 errs() << ProgName << ": " << Error;
167 return nullptr;
168 }
169
170 // Return the found target.
171 return TheTarget;
172}
173
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000174// A comment consumer that parses strings.
175// The only valid tokens are strings.
176class MCACommentConsumer : public AsmCommentConsumer {
177public:
178 mca::CodeRegions &Regions;
179
180 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
181 void HandleComment(SMLoc Loc, StringRef CommentText) override {
182 // Skip empty comments.
183 StringRef Comment(CommentText);
184 if (Comment.empty())
185 return;
186
187 // Skip spaces and tabs
188 unsigned Position = Comment.find_first_not_of(" \t");
189 if (Position >= Comment.size())
190 // we reached the end of the comment. Bail out.
191 return;
192
193 Comment = Comment.drop_front(Position);
194 if (Comment.consume_front("LLVM-MCA-END")) {
195 Regions.endRegion(Loc);
196 return;
197 }
198
199 // Now try to parse string LLVM-MCA-BEGIN
200 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
201 return;
202
203 // Skip spaces and tabs
204 Position = Comment.find_first_not_of(" \t");
205 if (Position < Comment.size())
Fangrui Songbb082572018-04-09 17:06:57 +0000206 Comment = Comment.drop_front(Position);
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000207 // Use the rest of the string as a descriptor for this code snippet.
208 Regions.beginRegion(Comment, Loc);
209 }
210};
211
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000212int AssembleInput(const char *ProgName, MCAsmParser &Parser,
213 const Target *TheTarget, MCSubtargetInfo &STI,
214 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000215 std::unique_ptr<MCTargetAsmParser> TAP(
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000216 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000217
218 if (!TAP) {
219 errs() << ProgName
220 << ": error: this target does not support assembly parsing.\n";
221 return 1;
222 }
223
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000224 Parser.setTargetParser(*TAP);
225 return Parser.Run(false);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000226}
227
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000228ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000229 if (OutputFilename == "")
230 OutputFilename = "-";
231 std::error_code EC;
232 auto Out =
233 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
234 if (!EC)
235 return std::move(Out);
236 return EC;
237}
238
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000239class MCStreamerWrapper final : public MCStreamer {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000240 mca::CodeRegions &Regions;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000241
242public:
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000243 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
244 : MCStreamer(Context), Regions(R) {}
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000245
246 // We only want to intercept the emission of new instructions.
247 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
248 bool /* unused */) override {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000249 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000250 }
251
252 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
253 return true;
254 }
255
256 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
257 unsigned ByteAlignment) override {}
258 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
259 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
260 void EmitGPRel32Value(const MCExpr *Value) override {}
261 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
262 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
263 void EmitCOFFSymbolType(int Type) override {}
264 void EndCOFFSymbolDef() override {}
265
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000266 const std::vector<std::unique_ptr<const MCInst>> &
267 GetInstructionSequence(unsigned Index) const {
268 return Regions.getInstructionSequence(Index);
269 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000270};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000271} // end of anonymous namespace
272
273int main(int argc, char **argv) {
274 sys::PrintStackTraceOnErrorSignal(argv[0]);
275 PrettyStackTraceProgram X(argc, argv);
276 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
277
278 // Initialize targets and assembly parsers.
279 llvm::InitializeAllTargetInfos();
280 llvm::InitializeAllTargetMCs();
281 llvm::InitializeAllAsmParsers();
282
283 // Enable printing of available targets when flag --version is specified.
284 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
285
286 // Parse flags and initialize target options.
287 cl::ParseCommandLineOptions(argc, argv,
288 "llvm machine code performance analyzer.\n");
289 MCTargetOptions MCOptions;
290 MCOptions.PreserveAsmComments = false;
291
292 // Get the target from the triple. If a triple is not specified, then select
293 // the default triple for the host. If the triple doesn't correspond to any
294 // registered target, then exit with an error message.
295 const char *ProgName = argv[0];
296 const Target *TheTarget = getTarget(ProgName);
297 if (!TheTarget)
298 return 1;
299
300 // GetTarget() may replaced TripleName with a default triple.
301 // For safety, reconstruct the Triple object.
302 Triple TheTriple(TripleName);
303
304 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
305 MemoryBuffer::getFileOrSTDIN(InputFilename);
306 if (std::error_code EC = BufferPtr.getError()) {
307 errs() << InputFilename << ": " << EC.message() << '\n';
308 return 1;
309 }
310
311 SourceMgr SrcMgr;
312
313 // Tell SrcMgr about this buffer, which is what the parser will pick up.
314 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
315
316 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
317 assert(MRI && "Unable to create target register info!");
318
319 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
320 assert(MAI && "Unable to create target asm info!");
321
322 MCObjectFileInfo MOFI;
323 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
324 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
325
326 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000327
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000328 mca::CodeRegions Regions(SrcMgr);
329 MCStreamerWrapper Str(Ctx, Regions);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000330
331 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
332 std::unique_ptr<MCSubtargetInfo> STI(
333 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
334 if (!STI->isCPUStringValid(MCPU))
335 return 1;
336
337 if (!STI->getSchedModel().isOutOfOrder()) {
338 errs() << "error: please specify an out-of-order cpu. '" << MCPU
339 << "' is an in-order cpu.\n";
340 return 1;
341 }
342
343 if (!STI->getSchedModel().hasInstrSchedModel()) {
344 errs()
345 << "error: unable to find instruction-level scheduling information for"
346 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
347 << "'.\n";
348
349 if (STI->getSchedModel().InstrItineraries)
350 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
351 << "instruction itineraries are currently unsupported.\n";
352 return 1;
353 }
354
355 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
356 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
357 if (!IP) {
358 errs() << "error: unable to create instruction printer for target triple '"
359 << TheTriple.normalize() << "' with assembly variant "
360 << OutputAsmVariant << ".\n";
361 return 1;
362 }
363
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000364 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000365 MCAsmLexer &Lexer = P->getLexer();
366 MCACommentConsumer CC(Regions);
367 Lexer.setCommentConsumer(&CC);
368
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000369 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
370 return 1;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000371
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000372 if (Regions.empty()) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000373 errs() << "error: no assembly instructions found.\n";
374 return 1;
375 }
376
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000377 // Now initialize the output file.
378 auto OF = getOutputStream();
379 if (std::error_code EC = OF.getError()) {
380 errs() << EC.message() << '\n';
381 return 1;
382 }
383
384 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
385
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000386 const MCSchedModel &SM = STI->getSchedModel();
387
388 unsigned Width = SM.IssueWidth;
389 if (DispatchWidth)
390 Width = DispatchWidth;
391
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000392 // Create an instruction builder.
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000393 mca::InstrBuilder IB(*STI, *MCII);
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000394
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000395 // Number each region in the sequence.
396 unsigned RegionIdx = 0;
397 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
398 // Skip empty code regions.
399 if (Region->empty())
400 continue;
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000401
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000402 // Don't print the header of this region if it is the default region, and
403 // it doesn't have an end location.
404 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
405 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
406 StringRef Desc = Region->getDescription();
407 if (!Desc.empty())
408 TOF->os() << " - " << Desc;
409 TOF->os() << "\n\n";
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000410 }
411
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000412 mca::SourceMgr S(Region->getInstructions(),
413 PrintInstructionTables ? 1 : Iterations);
414
415 if (PrintInstructionTables) {
416 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
417
418 if (PrintInstructionInfoView) {
419 IT.addView(
420 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
421 }
422
423 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
424 IT.run();
425 IT.printReport(TOF->os());
426 continue;
427 }
428
429 mca::Backend B(*STI, *MRI, IB, S, Width, RegisterFileSize, LoadQueueSize,
430 StoreQueueSize, AssumeNoAlias);
431 mca::BackendPrinter Printer(B);
432
433 Printer.addView(llvm::make_unique<mca::SummaryView>(S, Width));
434 if (PrintInstructionInfoView)
435 Printer.addView(
436 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
437
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000438 if (PrintDispatchStats)
439 Printer.addView(llvm::make_unique<mca::DispatchStatistics>(*STI));
440
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000441 if (PrintiSchedulerStats)
442 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
443
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000444 if (PrintModeVerbose)
445 Printer.addView(llvm::make_unique<mca::BackendStatistics>(*STI));
446
447 if (PrintRegisterFileStats)
448 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
449
450 if (PrintResourcePressureView)
451 Printer.addView(
452 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
453
454 if (PrintTimelineView) {
455 Printer.addView(llvm::make_unique<mca::TimelineView>(
456 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
457 }
458
459 B.run();
460 Printer.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000461 }
462
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000463 TOF->keep();
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000464 return 0;
465}