blob: 127b22f67f4b0dced920098bae0580180b49990a [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 Biagio3a6b0922018-03-08 13:05:02 +0000134static const Target *getTarget(const char *ProgName) {
135 TripleName = Triple::normalize(TripleName);
136 if (TripleName.empty())
137 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
138 Triple TheTriple(TripleName);
139
140 // Get the target specific parser.
141 std::string Error;
142 const Target *TheTarget =
143 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
144 if (!TheTarget) {
145 errs() << ProgName << ": " << Error;
146 return nullptr;
147 }
148
149 // Return the found target.
150 return TheTarget;
151}
152
153static int AssembleInput(const char *ProgName, const Target *TheTarget,
154 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
155 MCAsmInfo &MAI, MCSubtargetInfo &STI,
156 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
157 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
158 std::unique_ptr<MCTargetAsmParser> TAP(
159 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
160
161 if (!TAP) {
162 errs() << ProgName
163 << ": error: this target does not support assembly parsing.\n";
164 return 1;
165 }
166
167 Parser->setTargetParser(*TAP);
168 return Parser->Run(false);
169}
170
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000171static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
172 if (OutputFilename == "")
173 OutputFilename = "-";
174 std::error_code EC;
175 auto Out =
176 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
177 if (!EC)
178 return std::move(Out);
179 return EC;
180}
181
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000182namespace {
183
184class MCStreamerWrapper final : public MCStreamer {
185 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
186 InstVec &Insts;
187
188public:
189 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
190 : MCStreamer(Context), Insts(Vec) {}
191
192 // We only want to intercept the emission of new instructions.
193 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
194 bool /* unused */) override {
195 Insts.emplace_back(new MCInst(Inst));
196 }
197
198 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
199 return true;
200 }
201
202 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
203 unsigned ByteAlignment) override {}
204 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
205 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
206 void EmitGPRel32Value(const MCExpr *Value) override {}
207 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
208 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
209 void EmitCOFFSymbolType(int Type) override {}
210 void EndCOFFSymbolDef() override {}
211
212 const InstVec &GetInstructionSequence() const { return Insts; }
213};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000214} // end of anonymous namespace
215
216int main(int argc, char **argv) {
217 sys::PrintStackTraceOnErrorSignal(argv[0]);
218 PrettyStackTraceProgram X(argc, argv);
219 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
220
221 // Initialize targets and assembly parsers.
222 llvm::InitializeAllTargetInfos();
223 llvm::InitializeAllTargetMCs();
224 llvm::InitializeAllAsmParsers();
225
226 // Enable printing of available targets when flag --version is specified.
227 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
228
229 // Parse flags and initialize target options.
230 cl::ParseCommandLineOptions(argc, argv,
231 "llvm machine code performance analyzer.\n");
232 MCTargetOptions MCOptions;
233 MCOptions.PreserveAsmComments = false;
234
235 // Get the target from the triple. If a triple is not specified, then select
236 // the default triple for the host. If the triple doesn't correspond to any
237 // registered target, then exit with an error message.
238 const char *ProgName = argv[0];
239 const Target *TheTarget = getTarget(ProgName);
240 if (!TheTarget)
241 return 1;
242
243 // GetTarget() may replaced TripleName with a default triple.
244 // For safety, reconstruct the Triple object.
245 Triple TheTriple(TripleName);
246
247 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
248 MemoryBuffer::getFileOrSTDIN(InputFilename);
249 if (std::error_code EC = BufferPtr.getError()) {
250 errs() << InputFilename << ": " << EC.message() << '\n';
251 return 1;
252 }
253
254 SourceMgr SrcMgr;
255
256 // Tell SrcMgr about this buffer, which is what the parser will pick up.
257 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
258
259 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
260 assert(MRI && "Unable to create target register info!");
261
262 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
263 assert(MAI && "Unable to create target asm info!");
264
265 MCObjectFileInfo MOFI;
266 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
267 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
268
269 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000270
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000271 std::unique_ptr<mca::SourceMgr> S =
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000272 llvm::make_unique<mca::SourceMgr>(PrintInstructionTables ? 1 : Iterations);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000273 MCStreamerWrapper Str(Ctx, S->getSequence());
274
275 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
276 std::unique_ptr<MCSubtargetInfo> STI(
277 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
278 if (!STI->isCPUStringValid(MCPU))
279 return 1;
280
281 if (!STI->getSchedModel().isOutOfOrder()) {
282 errs() << "error: please specify an out-of-order cpu. '" << MCPU
283 << "' is an in-order cpu.\n";
284 return 1;
285 }
286
287 if (!STI->getSchedModel().hasInstrSchedModel()) {
288 errs()
289 << "error: unable to find instruction-level scheduling information for"
290 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
291 << "'.\n";
292
293 if (STI->getSchedModel().InstrItineraries)
294 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
295 << "instruction itineraries are currently unsupported.\n";
296 return 1;
297 }
298
299 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
300 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
301 if (!IP) {
302 errs() << "error: unable to create instruction printer for target triple '"
303 << TheTriple.normalize() << "' with assembly variant "
304 << OutputAsmVariant << ".\n";
305 return 1;
306 }
307
308 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
309 *MCII, MCOptions);
310 if (Res)
311 return Res;
312
313 if (S->isEmpty()) {
314 errs() << "error: no assembly instructions found.\n";
315 return 1;
316 }
317
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000318 // Now initialize the output file.
319 auto OF = getOutputStream();
320 if (std::error_code EC = OF.getError()) {
321 errs() << EC.message() << '\n';
322 return 1;
323 }
324
325 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
326
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000327 const MCSchedModel &SM = STI->getSchedModel();
328
329 unsigned Width = SM.IssueWidth;
330 if (DispatchWidth)
331 Width = DispatchWidth;
332
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000333 // Create an instruction builder.
334 std::unique_ptr<mca::InstrBuilder> IB =
335 llvm::make_unique<mca::InstrBuilder>(*STI, *MCII);
336
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000337 if (PrintInstructionTables) {
338 mca::InstructionTables IT(STI->getSchedModel(), *IB, *S);
339 mca::ResourcePressureView RPV(*STI, *IP, *S);
340 mca::InstructionInfoView IIV(*STI, *MCII, *S, *IP);
341 IT.addEventListener(&IIV);
342 IT.addEventListener(&RPV);
343 IT.run();
344 RPV.printView(TOF->os());
345 TOF->keep();
346 return 0;
347 }
348
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000349 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000350 *STI, *MRI, *IB, *S, Width, RegisterFileSize, MaxRetirePerCycle,
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000351 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
352
353 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000354 llvm::make_unique<mca::BackendPrinter>(*B);
355
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +0000356 Printer->addView(llvm::make_unique<mca::SummaryView>(*S, Width));
357
Andrea Di Biagio35622482018-03-22 10:19:20 +0000358 Printer->addView(
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +0000359 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, *S, *IP));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000360
Andrea Di Biagio35622482018-03-22 10:19:20 +0000361 if (PrintModeVerbose)
362 Printer->addView(llvm::make_unique<mca::BackendStatistics>(*STI));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000363
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000364 if (PrintResourcePressureView)
Andrea Di Biagio94fafdf2018-03-24 16:05:36 +0000365 Printer->addView(
366 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000367
368 if (PrintTimelineView) {
Andrea Di Biagio35622482018-03-22 10:19:20 +0000369 Printer->addView(llvm::make_unique<mca::TimelineView>(
370 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000371 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000372
373 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000374 Printer->printReport(TOF->os());
375 TOF->keep();
376
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000377 return 0;
378}