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