blob: f49ae23309de5bc4b8899801e5093d0403e8ffc5 [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 Biagio0cc66c72018-03-09 13:52:03 +000032#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000033#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000034#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCContext.h"
36#include "llvm/MC/MCObjectFileInfo.h"
37#include "llvm/MC/MCParser/MCTargetAsmParser.h"
38#include "llvm/MC/MCRegisterInfo.h"
39#include "llvm/MC/MCStreamer.h"
40#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000041#include "llvm/Support/ErrorOr.h"
42#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/PrettyStackTrace.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/SourceMgr.h"
47#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000049#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000050
51using namespace llvm;
52
53static cl::opt<std::string>
54 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
55
56static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
57 cl::init("-"),
58 cl::value_desc("filename"));
59
60static cl::opt<std::string>
61 ArchName("march", cl::desc("Target arch to assemble for, "
62 "see -version for available targets"));
63
64static cl::opt<std::string>
65 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000066 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000067
68static cl::opt<std::string>
69 MCPU("mcpu",
70 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
71 cl::value_desc("cpu-name"), cl::init("generic"));
72
73static cl::opt<unsigned>
74 OutputAsmVariant("output-asm-variant",
75 cl::desc("Syntax variant to use for output printing"));
76
77static cl::opt<unsigned> Iterations("iterations",
78 cl::desc("Number of iterations to run"),
79 cl::init(0));
80
81static cl::opt<unsigned> DispatchWidth(
82 "dispatch",
83 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
84 cl::init(0));
85
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000086static cl::opt<unsigned>
87 RegisterFileSize("register-file-size",
88 cl::desc("Maximum number of temporary registers which can "
89 "be used for register mappings"),
90 cl::init(0));
91
Andrea Di Biagio29538c62018-03-23 11:33:09 +000092static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000093 PrintRegisterFileStats("register-file-stats",
94 cl::desc("Print register file statistics"),
95 cl::init(false));
96
97static cl::opt<bool>
Andrea Di Biagio821f6502018-04-10 14:55:14 +000098 PrintDispatchStats("dispatch-stats",
99 cl::desc("Print dispatch statistics"),
100 cl::init(false));
101
102static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000103 PrintResourcePressureView("resource-pressure",
104 cl::desc("Print the resource pressure view"),
105 cl::init(true));
106
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000107static cl::opt<bool> PrintTimelineView("timeline",
108 cl::desc("Print the timeline view"),
109 cl::init(false));
110
111static cl::opt<unsigned> TimelineMaxIterations(
112 "timeline-max-iterations",
113 cl::desc("Maximum number of iterations to print in timeline view"),
114 cl::init(0));
115
116static cl::opt<unsigned> TimelineMaxCycles(
117 "timeline-max-cycles",
118 cl::desc(
119 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
120 cl::init(80));
121
122static cl::opt<bool> PrintModeVerbose("verbose",
123 cl::desc("Enable verbose output"),
124 cl::init(false));
125
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000126static cl::opt<bool> AssumeNoAlias(
127 "noalias",
128 cl::desc("If set, it assumes that loads and stores do not alias"),
129 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000130
131static cl::opt<unsigned>
132 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000133
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000134static cl::opt<unsigned>
135 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
136
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000137static cl::opt<bool>
138 PrintInstructionTables("instruction-tables",
139 cl::desc("Print instruction tables"),
140 cl::init(false));
141
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000142static cl::opt<bool>
143 PrintInstructionInfoView("instruction-info",
144 cl::desc("Print the instruction info view"),
145 cl::init(true));
146
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000147namespace {
148
149const Target *getTarget(const char *ProgName) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000150 TripleName = Triple::normalize(TripleName);
151 if (TripleName.empty())
152 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
153 Triple TheTriple(TripleName);
154
155 // Get the target specific parser.
156 std::string Error;
157 const Target *TheTarget =
158 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
159 if (!TheTarget) {
160 errs() << ProgName << ": " << Error;
161 return nullptr;
162 }
163
164 // Return the found target.
165 return TheTarget;
166}
167
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000168// A comment consumer that parses strings.
169// The only valid tokens are strings.
170class MCACommentConsumer : public AsmCommentConsumer {
171public:
172 mca::CodeRegions &Regions;
173
174 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
175 void HandleComment(SMLoc Loc, StringRef CommentText) override {
176 // Skip empty comments.
177 StringRef Comment(CommentText);
178 if (Comment.empty())
179 return;
180
181 // Skip spaces and tabs
182 unsigned Position = Comment.find_first_not_of(" \t");
183 if (Position >= Comment.size())
184 // we reached the end of the comment. Bail out.
185 return;
186
187 Comment = Comment.drop_front(Position);
188 if (Comment.consume_front("LLVM-MCA-END")) {
189 Regions.endRegion(Loc);
190 return;
191 }
192
193 // Now try to parse string LLVM-MCA-BEGIN
194 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
195 return;
196
197 // Skip spaces and tabs
198 Position = Comment.find_first_not_of(" \t");
199 if (Position < Comment.size())
Fangrui Songbb082572018-04-09 17:06:57 +0000200 Comment = Comment.drop_front(Position);
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000201 // Use the rest of the string as a descriptor for this code snippet.
202 Regions.beginRegion(Comment, Loc);
203 }
204};
205
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000206int AssembleInput(const char *ProgName, MCAsmParser &Parser,
207 const Target *TheTarget, MCSubtargetInfo &STI,
208 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000209 std::unique_ptr<MCTargetAsmParser> TAP(
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000210 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000211
212 if (!TAP) {
213 errs() << ProgName
214 << ": error: this target does not support assembly parsing.\n";
215 return 1;
216 }
217
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000218 Parser.setTargetParser(*TAP);
219 return Parser.Run(false);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000220}
221
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000222ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000223 if (OutputFilename == "")
224 OutputFilename = "-";
225 std::error_code EC;
226 auto Out =
227 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
228 if (!EC)
229 return std::move(Out);
230 return EC;
231}
232
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000233class MCStreamerWrapper final : public MCStreamer {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000234 mca::CodeRegions &Regions;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000235
236public:
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000237 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
238 : MCStreamer(Context), Regions(R) {}
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000239
240 // We only want to intercept the emission of new instructions.
241 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
242 bool /* unused */) override {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000243 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000244 }
245
246 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
247 return true;
248 }
249
250 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
251 unsigned ByteAlignment) override {}
252 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
253 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
254 void EmitGPRel32Value(const MCExpr *Value) override {}
255 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
256 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
257 void EmitCOFFSymbolType(int Type) override {}
258 void EndCOFFSymbolDef() override {}
259
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000260 const std::vector<std::unique_ptr<const MCInst>> &
261 GetInstructionSequence(unsigned Index) const {
262 return Regions.getInstructionSequence(Index);
263 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000264};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000265} // end of anonymous namespace
266
267int main(int argc, char **argv) {
268 sys::PrintStackTraceOnErrorSignal(argv[0]);
269 PrettyStackTraceProgram X(argc, argv);
270 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
271
272 // Initialize targets and assembly parsers.
273 llvm::InitializeAllTargetInfos();
274 llvm::InitializeAllTargetMCs();
275 llvm::InitializeAllAsmParsers();
276
277 // Enable printing of available targets when flag --version is specified.
278 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
279
280 // Parse flags and initialize target options.
281 cl::ParseCommandLineOptions(argc, argv,
282 "llvm machine code performance analyzer.\n");
283 MCTargetOptions MCOptions;
284 MCOptions.PreserveAsmComments = false;
285
286 // Get the target from the triple. If a triple is not specified, then select
287 // the default triple for the host. If the triple doesn't correspond to any
288 // registered target, then exit with an error message.
289 const char *ProgName = argv[0];
290 const Target *TheTarget = getTarget(ProgName);
291 if (!TheTarget)
292 return 1;
293
294 // GetTarget() may replaced TripleName with a default triple.
295 // For safety, reconstruct the Triple object.
296 Triple TheTriple(TripleName);
297
298 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
299 MemoryBuffer::getFileOrSTDIN(InputFilename);
300 if (std::error_code EC = BufferPtr.getError()) {
301 errs() << InputFilename << ": " << EC.message() << '\n';
302 return 1;
303 }
304
305 SourceMgr SrcMgr;
306
307 // Tell SrcMgr about this buffer, which is what the parser will pick up.
308 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
309
310 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
311 assert(MRI && "Unable to create target register info!");
312
313 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
314 assert(MAI && "Unable to create target asm info!");
315
316 MCObjectFileInfo MOFI;
317 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
318 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
319
320 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000321
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000322 mca::CodeRegions Regions(SrcMgr);
323 MCStreamerWrapper Str(Ctx, Regions);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000324
325 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
326 std::unique_ptr<MCSubtargetInfo> STI(
327 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
328 if (!STI->isCPUStringValid(MCPU))
329 return 1;
330
331 if (!STI->getSchedModel().isOutOfOrder()) {
332 errs() << "error: please specify an out-of-order cpu. '" << MCPU
333 << "' is an in-order cpu.\n";
334 return 1;
335 }
336
337 if (!STI->getSchedModel().hasInstrSchedModel()) {
338 errs()
339 << "error: unable to find instruction-level scheduling information for"
340 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
341 << "'.\n";
342
343 if (STI->getSchedModel().InstrItineraries)
344 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
345 << "instruction itineraries are currently unsupported.\n";
346 return 1;
347 }
348
349 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
350 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
351 if (!IP) {
352 errs() << "error: unable to create instruction printer for target triple '"
353 << TheTriple.normalize() << "' with assembly variant "
354 << OutputAsmVariant << ".\n";
355 return 1;
356 }
357
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000358 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000359 MCAsmLexer &Lexer = P->getLexer();
360 MCACommentConsumer CC(Regions);
361 Lexer.setCommentConsumer(&CC);
362
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000363 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
364 return 1;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000365
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000366 if (Regions.empty()) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000367 errs() << "error: no assembly instructions found.\n";
368 return 1;
369 }
370
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000371 // Now initialize the output file.
372 auto OF = getOutputStream();
373 if (std::error_code EC = OF.getError()) {
374 errs() << EC.message() << '\n';
375 return 1;
376 }
377
378 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
379
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000380 const MCSchedModel &SM = STI->getSchedModel();
381
382 unsigned Width = SM.IssueWidth;
383 if (DispatchWidth)
384 Width = DispatchWidth;
385
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000386 // Create an instruction builder.
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000387 mca::InstrBuilder IB(*STI, *MCII);
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000388
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000389 // Number each region in the sequence.
390 unsigned RegionIdx = 0;
391 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
392 // Skip empty code regions.
393 if (Region->empty())
394 continue;
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000395
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000396 // Don't print the header of this region if it is the default region, and
397 // it doesn't have an end location.
398 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
399 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
400 StringRef Desc = Region->getDescription();
401 if (!Desc.empty())
402 TOF->os() << " - " << Desc;
403 TOF->os() << "\n\n";
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000404 }
405
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000406 mca::SourceMgr S(Region->getInstructions(),
407 PrintInstructionTables ? 1 : Iterations);
408
409 if (PrintInstructionTables) {
410 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
411
412 if (PrintInstructionInfoView) {
413 IT.addView(
414 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
415 }
416
417 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
418 IT.run();
419 IT.printReport(TOF->os());
420 continue;
421 }
422
423 mca::Backend B(*STI, *MRI, IB, S, Width, RegisterFileSize, LoadQueueSize,
424 StoreQueueSize, AssumeNoAlias);
425 mca::BackendPrinter Printer(B);
426
427 Printer.addView(llvm::make_unique<mca::SummaryView>(S, Width));
428 if (PrintInstructionInfoView)
429 Printer.addView(
430 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
431
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000432 if (PrintDispatchStats)
433 Printer.addView(llvm::make_unique<mca::DispatchStatistics>(*STI));
434
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000435 if (PrintModeVerbose)
436 Printer.addView(llvm::make_unique<mca::BackendStatistics>(*STI));
437
438 if (PrintRegisterFileStats)
439 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
440
441 if (PrintResourcePressureView)
442 Printer.addView(
443 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
444
445 if (PrintTimelineView) {
446 Printer.addView(llvm::make_unique<mca::TimelineView>(
447 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
448 }
449
450 B.run();
451 Printer.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000452 }
453
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000454 TOF->keep();
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000455 return 0;
456}