blob: 49d50476354a92387235e9e7238334a43a286d47 [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 Biagiodf5d9482018-03-23 19:40:04 +000026#include "InstructionInfoView.h"
Andrea Di Biagiod1569292018-03-26 12:04:53 +000027#include "InstructionTables.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000028#include "ResourcePressureView.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000029#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000030#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000031#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCContext.h"
33#include "llvm/MC/MCObjectFileInfo.h"
34#include "llvm/MC/MCParser/MCTargetAsmParser.h"
35#include "llvm/MC/MCRegisterInfo.h"
36#include "llvm/MC/MCStreamer.h"
37#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000038#include "llvm/Support/ErrorOr.h"
39#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000040#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/PrettyStackTrace.h"
42#include "llvm/Support/Signals.h"
43#include "llvm/Support/SourceMgr.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000046#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000047
48using namespace llvm;
49
50static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
52
53static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
54 cl::init("-"),
55 cl::value_desc("filename"));
56
57static cl::opt<std::string>
58 ArchName("march", cl::desc("Target arch to assemble for, "
59 "see -version for available targets"));
60
61static cl::opt<std::string>
62 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000063 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000064
65static cl::opt<std::string>
66 MCPU("mcpu",
67 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
68 cl::value_desc("cpu-name"), cl::init("generic"));
69
70static cl::opt<unsigned>
71 OutputAsmVariant("output-asm-variant",
72 cl::desc("Syntax variant to use for output printing"));
73
74static cl::opt<unsigned> Iterations("iterations",
75 cl::desc("Number of iterations to run"),
76 cl::init(0));
77
78static cl::opt<unsigned> DispatchWidth(
79 "dispatch",
80 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
81 cl::init(0));
82
83static cl::opt<unsigned> MaxRetirePerCycle(
84 "max-retire-per-cycle",
85 cl::desc("Maximum number of instructions that can be retired in one cycle"),
86 cl::init(0));
87
88static cl::opt<unsigned>
89 RegisterFileSize("register-file-size",
90 cl::desc("Maximum number of temporary registers which can "
91 "be used for register mappings"),
92 cl::init(0));
93
Andrea Di Biagio29538c62018-03-23 11:33:09 +000094static cl::opt<bool>
95 PrintResourcePressureView("resource-pressure",
96 cl::desc("Print the resource pressure view"),
97 cl::init(true));
98
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000099static cl::opt<bool> PrintTimelineView("timeline",
100 cl::desc("Print the timeline view"),
101 cl::init(false));
102
103static cl::opt<unsigned> TimelineMaxIterations(
104 "timeline-max-iterations",
105 cl::desc("Maximum number of iterations to print in timeline view"),
106 cl::init(0));
107
108static cl::opt<unsigned> TimelineMaxCycles(
109 "timeline-max-cycles",
110 cl::desc(
111 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
112 cl::init(80));
113
114static cl::opt<bool> PrintModeVerbose("verbose",
115 cl::desc("Enable verbose output"),
116 cl::init(false));
117
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000118static cl::opt<bool> AssumeNoAlias(
119 "noalias",
120 cl::desc("If set, it assumes that loads and stores do not alias"),
121 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000122
123static cl::opt<unsigned>
124 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000125
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000126static cl::opt<unsigned>
127 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
128
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000129static cl::opt<bool>
130 PrintInstructionTables("instruction-tables",
131 cl::desc("Print instruction tables"),
132 cl::init(false));
133
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000134static cl::opt<bool>
135 PrintInstructionInfoView("instruction-info",
136 cl::desc("Print the instruction info view"),
137 cl::init(true));
138
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000139static const Target *getTarget(const char *ProgName) {
140 TripleName = Triple::normalize(TripleName);
141 if (TripleName.empty())
142 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
143 Triple TheTriple(TripleName);
144
145 // Get the target specific parser.
146 std::string Error;
147 const Target *TheTarget =
148 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
149 if (!TheTarget) {
150 errs() << ProgName << ": " << Error;
151 return nullptr;
152 }
153
154 // Return the found target.
155 return TheTarget;
156}
157
158static int AssembleInput(const char *ProgName, const Target *TheTarget,
159 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
160 MCAsmInfo &MAI, MCSubtargetInfo &STI,
161 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
162 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
163 std::unique_ptr<MCTargetAsmParser> TAP(
164 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
165
166 if (!TAP) {
167 errs() << ProgName
168 << ": error: this target does not support assembly parsing.\n";
169 return 1;
170 }
171
172 Parser->setTargetParser(*TAP);
173 return Parser->Run(false);
174}
175
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000176static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
177 if (OutputFilename == "")
178 OutputFilename = "-";
179 std::error_code EC;
180 auto Out =
181 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
182 if (!EC)
183 return std::move(Out);
184 return EC;
185}
186
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000187namespace {
188
189class MCStreamerWrapper final : public MCStreamer {
190 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
191 InstVec &Insts;
192
193public:
194 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
195 : MCStreamer(Context), Insts(Vec) {}
196
197 // We only want to intercept the emission of new instructions.
198 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
199 bool /* unused */) override {
200 Insts.emplace_back(new MCInst(Inst));
201 }
202
203 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
204 return true;
205 }
206
207 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
208 unsigned ByteAlignment) override {}
209 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
210 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
211 void EmitGPRel32Value(const MCExpr *Value) override {}
212 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
213 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
214 void EmitCOFFSymbolType(int Type) override {}
215 void EndCOFFSymbolDef() override {}
216
217 const InstVec &GetInstructionSequence() const { return Insts; }
218};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000219} // end of anonymous namespace
220
221int main(int argc, char **argv) {
222 sys::PrintStackTraceOnErrorSignal(argv[0]);
223 PrettyStackTraceProgram X(argc, argv);
224 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
225
226 // Initialize targets and assembly parsers.
227 llvm::InitializeAllTargetInfos();
228 llvm::InitializeAllTargetMCs();
229 llvm::InitializeAllAsmParsers();
230
231 // Enable printing of available targets when flag --version is specified.
232 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
233
234 // Parse flags and initialize target options.
235 cl::ParseCommandLineOptions(argc, argv,
236 "llvm machine code performance analyzer.\n");
237 MCTargetOptions MCOptions;
238 MCOptions.PreserveAsmComments = false;
239
240 // Get the target from the triple. If a triple is not specified, then select
241 // the default triple for the host. If the triple doesn't correspond to any
242 // registered target, then exit with an error message.
243 const char *ProgName = argv[0];
244 const Target *TheTarget = getTarget(ProgName);
245 if (!TheTarget)
246 return 1;
247
248 // GetTarget() may replaced TripleName with a default triple.
249 // For safety, reconstruct the Triple object.
250 Triple TheTriple(TripleName);
251
252 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
253 MemoryBuffer::getFileOrSTDIN(InputFilename);
254 if (std::error_code EC = BufferPtr.getError()) {
255 errs() << InputFilename << ": " << EC.message() << '\n';
256 return 1;
257 }
258
259 SourceMgr SrcMgr;
260
261 // Tell SrcMgr about this buffer, which is what the parser will pick up.
262 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
263
264 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
265 assert(MRI && "Unable to create target register info!");
266
267 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
268 assert(MAI && "Unable to create target asm info!");
269
270 MCObjectFileInfo MOFI;
271 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
272 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
273
274 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000275
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000276 std::unique_ptr<mca::SourceMgr> S = llvm::make_unique<mca::SourceMgr>(
277 PrintInstructionTables ? 1 : Iterations);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000278 MCStreamerWrapper Str(Ctx, S->getSequence());
279
280 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
281 std::unique_ptr<MCSubtargetInfo> STI(
282 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
283 if (!STI->isCPUStringValid(MCPU))
284 return 1;
285
286 if (!STI->getSchedModel().isOutOfOrder()) {
287 errs() << "error: please specify an out-of-order cpu. '" << MCPU
288 << "' is an in-order cpu.\n";
289 return 1;
290 }
291
292 if (!STI->getSchedModel().hasInstrSchedModel()) {
293 errs()
294 << "error: unable to find instruction-level scheduling information for"
295 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
296 << "'.\n";
297
298 if (STI->getSchedModel().InstrItineraries)
299 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
300 << "instruction itineraries are currently unsupported.\n";
301 return 1;
302 }
303
304 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
305 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
306 if (!IP) {
307 errs() << "error: unable to create instruction printer for target triple '"
308 << TheTriple.normalize() << "' with assembly variant "
309 << OutputAsmVariant << ".\n";
310 return 1;
311 }
312
313 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
314 *MCII, MCOptions);
315 if (Res)
316 return Res;
317
318 if (S->isEmpty()) {
319 errs() << "error: no assembly instructions found.\n";
320 return 1;
321 }
322
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000323 // Now initialize the output file.
324 auto OF = getOutputStream();
325 if (std::error_code EC = OF.getError()) {
326 errs() << EC.message() << '\n';
327 return 1;
328 }
329
330 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
331
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000332 const MCSchedModel &SM = STI->getSchedModel();
333
334 unsigned Width = SM.IssueWidth;
335 if (DispatchWidth)
336 Width = DispatchWidth;
337
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000338 // Create an instruction builder.
339 std::unique_ptr<mca::InstrBuilder> IB =
340 llvm::make_unique<mca::InstrBuilder>(*STI, *MCII);
341
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000342 if (PrintInstructionTables) {
343 mca::InstructionTables IT(STI->getSchedModel(), *IB, *S);
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000344
345 if (PrintInstructionInfoView) {
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000346 IT.addView(
347 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, *S, *IP));
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000348 }
349
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000350 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000351 IT.run();
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000352 IT.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000353 TOF->keep();
354 return 0;
355 }
356
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000357 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000358 *STI, *MRI, *IB, *S, Width, RegisterFileSize, MaxRetirePerCycle,
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000359 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
360
361 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000362 llvm::make_unique<mca::BackendPrinter>(*B);
363
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +0000364 Printer->addView(llvm::make_unique<mca::SummaryView>(*S, Width));
365
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000366 if (PrintInstructionInfoView)
367 Printer->addView(
368 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, *S, *IP));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000369
Andrea Di Biagio35622482018-03-22 10:19:20 +0000370 if (PrintModeVerbose)
371 Printer->addView(llvm::make_unique<mca::BackendStatistics>(*STI));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000372
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000373 if (PrintResourcePressureView)
Andrea Di Biagio94fafdf2018-03-24 16:05:36 +0000374 Printer->addView(
375 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000376
377 if (PrintTimelineView) {
Andrea Di Biagio35622482018-03-22 10:19:20 +0000378 Printer->addView(llvm::make_unique<mca::TimelineView>(
379 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000380 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000381
382 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000383 Printer->printReport(TOF->os());
384 TOF->keep();
385
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000386 return 0;
387}