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