blob: 88d33facd2b8401b618f778d57c68750f578c20e [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"
26#include "ResourcePressureView.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000027#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000028#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000029#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCObjectFileInfo.h"
32#include "llvm/MC/MCParser/MCTargetAsmParser.h"
33#include "llvm/MC/MCRegisterInfo.h"
34#include "llvm/MC/MCStreamer.h"
35#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000036#include "llvm/Support/ErrorOr.h"
37#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000038#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/Support/PrettyStackTrace.h"
40#include "llvm/Support/Signals.h"
41#include "llvm/Support/SourceMgr.h"
42#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000044#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000045
46using namespace llvm;
47
48static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
50
51static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
52 cl::init("-"),
53 cl::value_desc("filename"));
54
55static cl::opt<std::string>
56 ArchName("march", cl::desc("Target arch to assemble for, "
57 "see -version for available targets"));
58
59static cl::opt<std::string>
60 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000061 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000062
63static cl::opt<std::string>
64 MCPU("mcpu",
65 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
66 cl::value_desc("cpu-name"), cl::init("generic"));
67
68static cl::opt<unsigned>
69 OutputAsmVariant("output-asm-variant",
70 cl::desc("Syntax variant to use for output printing"));
71
72static cl::opt<unsigned> Iterations("iterations",
73 cl::desc("Number of iterations to run"),
74 cl::init(0));
75
76static cl::opt<unsigned> DispatchWidth(
77 "dispatch",
78 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
79 cl::init(0));
80
81static cl::opt<unsigned> MaxRetirePerCycle(
82 "max-retire-per-cycle",
83 cl::desc("Maximum number of instructions that can be retired in one cycle"),
84 cl::init(0));
85
86static 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
92static cl::opt<bool> PrintTimelineView("timeline",
93 cl::desc("Print the timeline view"),
94 cl::init(false));
95
96static cl::opt<unsigned> TimelineMaxIterations(
97 "timeline-max-iterations",
98 cl::desc("Maximum number of iterations to print in timeline view"),
99 cl::init(0));
100
101static cl::opt<unsigned> TimelineMaxCycles(
102 "timeline-max-cycles",
103 cl::desc(
104 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
105 cl::init(80));
106
107static cl::opt<bool> PrintModeVerbose("verbose",
108 cl::desc("Enable verbose output"),
109 cl::init(false));
110
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000111static cl::opt<bool> AssumeNoAlias(
112 "noalias",
113 cl::desc("If set, it assumes that loads and stores do not alias"),
114 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000115
116static cl::opt<unsigned>
117 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
118static cl::opt<unsigned>
119 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
120
121static const Target *getTarget(const char *ProgName) {
122 TripleName = Triple::normalize(TripleName);
123 if (TripleName.empty())
124 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
125 Triple TheTriple(TripleName);
126
127 // Get the target specific parser.
128 std::string Error;
129 const Target *TheTarget =
130 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
131 if (!TheTarget) {
132 errs() << ProgName << ": " << Error;
133 return nullptr;
134 }
135
136 // Return the found target.
137 return TheTarget;
138}
139
140static int AssembleInput(const char *ProgName, const Target *TheTarget,
141 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
142 MCAsmInfo &MAI, MCSubtargetInfo &STI,
143 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
144 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
145 std::unique_ptr<MCTargetAsmParser> TAP(
146 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
147
148 if (!TAP) {
149 errs() << ProgName
150 << ": error: this target does not support assembly parsing.\n";
151 return 1;
152 }
153
154 Parser->setTargetParser(*TAP);
155 return Parser->Run(false);
156}
157
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000158static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
159 if (OutputFilename == "")
160 OutputFilename = "-";
161 std::error_code EC;
162 auto Out =
163 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
164 if (!EC)
165 return std::move(Out);
166 return EC;
167}
168
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000169namespace {
170
171class MCStreamerWrapper final : public MCStreamer {
172 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
173 InstVec &Insts;
174
175public:
176 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
177 : MCStreamer(Context), Insts(Vec) {}
178
179 // We only want to intercept the emission of new instructions.
180 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
181 bool /* unused */) override {
182 Insts.emplace_back(new MCInst(Inst));
183 }
184
185 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
186 return true;
187 }
188
189 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
190 unsigned ByteAlignment) override {}
191 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
192 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
193 void EmitGPRel32Value(const MCExpr *Value) override {}
194 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
195 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
196 void EmitCOFFSymbolType(int Type) override {}
197 void EndCOFFSymbolDef() override {}
198
199 const InstVec &GetInstructionSequence() const { return Insts; }
200};
201
202} // end of anonymous namespace
203
204int main(int argc, char **argv) {
205 sys::PrintStackTraceOnErrorSignal(argv[0]);
206 PrettyStackTraceProgram X(argc, argv);
207 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
208
209 // Initialize targets and assembly parsers.
210 llvm::InitializeAllTargetInfos();
211 llvm::InitializeAllTargetMCs();
212 llvm::InitializeAllAsmParsers();
213
214 // Enable printing of available targets when flag --version is specified.
215 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
216
217 // Parse flags and initialize target options.
218 cl::ParseCommandLineOptions(argc, argv,
219 "llvm machine code performance analyzer.\n");
220 MCTargetOptions MCOptions;
221 MCOptions.PreserveAsmComments = false;
222
223 // Get the target from the triple. If a triple is not specified, then select
224 // the default triple for the host. If the triple doesn't correspond to any
225 // registered target, then exit with an error message.
226 const char *ProgName = argv[0];
227 const Target *TheTarget = getTarget(ProgName);
228 if (!TheTarget)
229 return 1;
230
231 // GetTarget() may replaced TripleName with a default triple.
232 // For safety, reconstruct the Triple object.
233 Triple TheTriple(TripleName);
234
235 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
236 MemoryBuffer::getFileOrSTDIN(InputFilename);
237 if (std::error_code EC = BufferPtr.getError()) {
238 errs() << InputFilename << ": " << EC.message() << '\n';
239 return 1;
240 }
241
242 SourceMgr SrcMgr;
243
244 // Tell SrcMgr about this buffer, which is what the parser will pick up.
245 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
246
247 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
248 assert(MRI && "Unable to create target register info!");
249
250 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
251 assert(MAI && "Unable to create target asm info!");
252
253 MCObjectFileInfo MOFI;
254 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
255 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
256
257 std::unique_ptr<buffer_ostream> BOS;
258 std::unique_ptr<mca::SourceMgr> S =
259 llvm::make_unique<mca::SourceMgr>(Iterations);
260 MCStreamerWrapper Str(Ctx, S->getSequence());
261
262 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
263 std::unique_ptr<MCSubtargetInfo> STI(
264 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
265 if (!STI->isCPUStringValid(MCPU))
266 return 1;
267
268 if (!STI->getSchedModel().isOutOfOrder()) {
269 errs() << "error: please specify an out-of-order cpu. '" << MCPU
270 << "' is an in-order cpu.\n";
271 return 1;
272 }
273
274 if (!STI->getSchedModel().hasInstrSchedModel()) {
275 errs()
276 << "error: unable to find instruction-level scheduling information for"
277 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
278 << "'.\n";
279
280 if (STI->getSchedModel().InstrItineraries)
281 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
282 << "instruction itineraries are currently unsupported.\n";
283 return 1;
284 }
285
286 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
287 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
288 if (!IP) {
289 errs() << "error: unable to create instruction printer for target triple '"
290 << TheTriple.normalize() << "' with assembly variant "
291 << OutputAsmVariant << ".\n";
292 return 1;
293 }
294
295 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
296 *MCII, MCOptions);
297 if (Res)
298 return Res;
299
300 if (S->isEmpty()) {
301 errs() << "error: no assembly instructions found.\n";
302 return 1;
303 }
304
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000305 // Now initialize the output file.
306 auto OF = getOutputStream();
307 if (std::error_code EC = OF.getError()) {
308 errs() << EC.message() << '\n';
309 return 1;
310 }
311
312 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
313
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000314 const MCSchedModel &SM = STI->getSchedModel();
315
316 unsigned Width = SM.IssueWidth;
317 if (DispatchWidth)
318 Width = DispatchWidth;
319
320 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000321 *STI, *MCII, *MRI, *S, Width, RegisterFileSize, MaxRetirePerCycle,
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000322 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
323
324 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000325 llvm::make_unique<mca::BackendPrinter>(*B);
326
Andrea Di Biagiob5229752018-03-13 17:24:32 +0000327 std::unique_ptr<mca::SummaryView> SV =
328 llvm::make_unique<mca::SummaryView>(*STI, *MCII, *S, *IP, Width);
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000329 Printer->addView(std::move(SV));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000330
331 if (PrintModeVerbose) {
332 std::unique_ptr<mca::BackendStatistics> BS =
Andrea Di Biagio12ef5262018-03-21 18:11:05 +0000333 llvm::make_unique<mca::BackendStatistics>(*STI);
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000334 Printer->addView(std::move(BS));
335 }
336
337 std::unique_ptr<mca::ResourcePressureView> RPV =
Andrea Di Biagio0c541292018-03-10 16:55:07 +0000338 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S);
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000339 Printer->addView(std::move(RPV));
340
341 if (PrintTimelineView) {
342 std::unique_ptr<mca::TimelineView> TV =
343 llvm::make_unique<mca::TimelineView>(
344 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles);
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000345 Printer->addView(std::move(TV));
346 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000347
348 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000349 Printer->printReport(TOF->os());
350 TOF->keep();
351
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000352 return 0;
353}