1//===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This utility is a simple driver that allows static performance analysis on
10// machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
11//
12// llvm-mca [options] <file-name>
13// -march <type>
14// -mcpu <cpu>
15// -o <file>
16//
17// The target defaults to the host target.
18// The cpu is derived from the triple if not specified; pass -mcpu=native to
19// select the host cpu.
20// The output defaults to standard output.
21//
22//===----------------------------------------------------------------------===//
23
24#include "CodeRegion.h"
25#include "CodeRegionGenerator.h"
26#include "PipelinePrinter.h"
27#include "Views/BottleneckAnalysis.h"
28#include "Views/DispatchStatistics.h"
29#include "Views/InstructionInfoView.h"
30#include "Views/RegisterFileStatistics.h"
31#include "Views/ResourcePressureView.h"
32#include "Views/RetireControlUnitStatistics.h"
33#include "Views/SchedulerStatistics.h"
34#include "Views/SummaryView.h"
35#include "Views/TimelineView.h"
36#include "llvm/MC/MCAsmBackend.h"
37#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCCodeEmitter.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCObjectFileInfo.h"
41#include "llvm/MC/MCRegisterInfo.h"
42#include "llvm/MC/MCSchedule.h"
43#include "llvm/MC/MCSubtargetInfo.h"
44#include "llvm/MC/MCTargetOptionsCommandFlags.h"
45#include "llvm/MC/TargetRegistry.h"
46#include "llvm/MCA/CodeEmitter.h"
47#include "llvm/MCA/Context.h"
48#include "llvm/MCA/CustomBehaviour.h"
49#include "llvm/MCA/InstrBuilder.h"
50#include "llvm/MCA/Pipeline.h"
51#include "llvm/MCA/Stages/EntryStage.h"
52#include "llvm/MCA/Stages/InstructionTables.h"
53#include "llvm/MCA/Support.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/ErrorOr.h"
57#include "llvm/Support/FileSystem.h"
58#include "llvm/Support/InitLLVM.h"
59#include "llvm/Support/MemoryBuffer.h"
60#include "llvm/Support/SourceMgr.h"
61#include "llvm/Support/TargetSelect.h"
62#include "llvm/Support/ToolOutputFile.h"
63#include "llvm/Support/WithColor.h"
64#include "llvm/TargetParser/Host.h"
65
66using namespace llvm;
67
68static mc::RegisterMCTargetOptionsFlags MOF;
69
70static cl::OptionCategory ToolOptions("Tool Options");
71static cl::OptionCategory ViewOptions("View Options");
72
73static cl::opt<std::string> InputFilename(cl::Positional,
74 cl::desc("<input file>"),
75 cl::cat(ToolOptions), cl::init(Val: "-"));
76
77static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
78 cl::init(Val: "-"), cl::cat(ToolOptions),
79 cl::value_desc("filename"));
80
81static cl::opt<std::string>
82 ArchName("march",
83 cl::desc("Target architecture. "
84 "See -version for available targets"),
85 cl::cat(ToolOptions));
86
87static cl::opt<std::string>
88 TripleNameOpt("mtriple",
89 cl::desc("Target triple. See -version for available targets"),
90 cl::cat(ToolOptions));
91
92static cl::opt<std::string>
93 MCPU("mcpu",
94 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
95 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init(Val: ""));
96
97static cl::list<std::string>
98 MATTRS("mattr", cl::CommaSeparated,
99 cl::desc("Target specific attributes (-mattr=help for details)"),
100 cl::value_desc("a1,+a2,-a3,..."), cl::cat(ToolOptions));
101
102static cl::opt<bool> PrintJson("json",
103 cl::desc("Print the output in json format"),
104 cl::cat(ToolOptions), cl::init(Val: false));
105
106static cl::opt<int>
107 OutputAsmVariant("output-asm-variant",
108 cl::desc("Syntax variant to use for output printing"),
109 cl::cat(ToolOptions), cl::init(Val: -1));
110
111static cl::opt<bool>
112 PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(Val: false),
113 cl::desc("Prefer hex format when printing immediate values"));
114
115static cl::opt<unsigned> Iterations("iterations",
116 cl::desc("Number of iterations to run"),
117 cl::cat(ToolOptions), cl::init(Val: 0));
118
119static cl::opt<unsigned>
120 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
121 cl::cat(ToolOptions), cl::init(Val: 0));
122
123static cl::opt<unsigned>
124 RegisterFileSize("register-file-size",
125 cl::desc("Maximum number of physical registers which can "
126 "be used for register mappings"),
127 cl::cat(ToolOptions), cl::init(Val: 0));
128
129static cl::opt<unsigned>
130 MicroOpQueue("micro-op-queue-size", cl::Hidden,
131 cl::desc("Number of entries in the micro-op queue"),
132 cl::cat(ToolOptions), cl::init(Val: 0));
133
134static cl::opt<unsigned>
135 DecoderThroughput("decoder-throughput", cl::Hidden,
136 cl::desc("Maximum throughput from the decoders "
137 "(instructions per cycle)"),
138 cl::cat(ToolOptions), cl::init(Val: 0));
139
140static cl::opt<unsigned>
141 CallLatency("call-latency", cl::Hidden,
142 cl::desc("Number of cycles to assume for a call instruction"),
143 cl::cat(ToolOptions), cl::init(Val: 100U));
144
145enum class SkipType { NONE, LACK_SCHED, PARSE_FAILURE, ANY_FAILURE };
146
147static cl::opt<enum SkipType> SkipUnsupportedInstructions(
148 "skip-unsupported-instructions",
149 cl::desc("Force analysis to continue in the presence of unsupported "
150 "instructions"),
151 cl::values(
152 clEnumValN(SkipType::NONE, "none",
153 "Exit with an error when an instruction is unsupported for "
154 "any reason (default)"),
155 clEnumValN(
156 SkipType::LACK_SCHED, "lack-sched",
157 "Skip instructions on input which lack scheduling information"),
158 clEnumValN(
159 SkipType::PARSE_FAILURE, "parse-failure",
160 "Skip lines on the input which fail to parse for any reason"),
161 clEnumValN(SkipType::ANY_FAILURE, "any",
162 "Skip instructions or lines on input which are unsupported "
163 "for any reason")),
164 cl::init(Val: SkipType::NONE), cl::cat(ViewOptions));
165
166bool shouldSkip(enum SkipType skipType) {
167 if (SkipUnsupportedInstructions == SkipType::NONE)
168 return false;
169 if (SkipUnsupportedInstructions == SkipType::ANY_FAILURE)
170 return true;
171 return skipType == SkipUnsupportedInstructions;
172}
173
174static cl::opt<bool>
175 PrintRegisterFileStats("register-file-stats",
176 cl::desc("Print register file statistics"),
177 cl::cat(ViewOptions), cl::init(Val: false));
178
179static cl::opt<bool> PrintDispatchStats("dispatch-stats",
180 cl::desc("Print dispatch statistics"),
181 cl::cat(ViewOptions), cl::init(Val: false));
182
183static cl::opt<bool>
184 PrintSummaryView("summary-view", cl::Hidden,
185 cl::desc("Print summary view (enabled by default)"),
186 cl::cat(ViewOptions), cl::init(Val: true));
187
188static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
189 cl::desc("Print scheduler statistics"),
190 cl::cat(ViewOptions), cl::init(Val: false));
191
192static cl::opt<bool>
193 PrintRetireStats("retire-stats",
194 cl::desc("Print retire control unit statistics"),
195 cl::cat(ViewOptions), cl::init(Val: false));
196
197static cl::opt<bool> PrintResourcePressureView(
198 "resource-pressure",
199 cl::desc("Print the resource pressure view (enabled by default)"),
200 cl::cat(ViewOptions), cl::init(Val: true));
201
202static cl::opt<bool> PrintTimelineView("timeline",
203 cl::desc("Print the timeline view"),
204 cl::cat(ViewOptions), cl::init(Val: false));
205
206static cl::opt<unsigned> TimelineMaxIterations(
207 "timeline-max-iterations",
208 cl::desc("Maximum number of iterations to print in timeline view"),
209 cl::cat(ViewOptions), cl::init(Val: 0));
210
211static cl::opt<unsigned>
212 TimelineMaxCycles("timeline-max-cycles",
213 cl::desc("Maximum number of cycles in the timeline view, "
214 "or 0 for unlimited. Defaults to 80 cycles"),
215 cl::cat(ViewOptions), cl::init(Val: 80));
216
217static cl::opt<bool>
218 AssumeNoAlias("noalias",
219 cl::desc("If set, assume that loads and stores do not alias"),
220 cl::cat(ToolOptions), cl::init(Val: true));
221
222static cl::opt<unsigned> LoadQueueSize("lqueue",
223 cl::desc("Size of the load queue"),
224 cl::cat(ToolOptions), cl::init(Val: 0));
225
226static cl::opt<unsigned> StoreQueueSize("squeue",
227 cl::desc("Size of the store queue"),
228 cl::cat(ToolOptions), cl::init(Val: 0));
229
230enum class InstructionTablesType { NONE, NORMAL, FULL };
231
232static cl::opt<enum InstructionTablesType> InstructionTablesOption(
233 "instruction-tables", cl::desc("Print instruction tables"),
234 cl::values(clEnumValN(InstructionTablesType::NONE, "none",
235 "Do not print instruction tables"),
236 clEnumValN(InstructionTablesType::NORMAL, "normal",
237 "Print instruction tables"),
238 clEnumValN(InstructionTablesType::NORMAL, "", ""),
239 clEnumValN(InstructionTablesType::FULL, "full",
240 "Print instruction tables with additional"
241 " information: bypass latency, LLVM opcode,"
242 " used resources")),
243 cl::cat(ToolOptions), cl::init(Val: InstructionTablesType::NONE),
244 cl::ValueOptional);
245
246static bool shouldPrintInstructionTables(enum InstructionTablesType ITType) {
247 return InstructionTablesOption == ITType;
248}
249
250static bool shouldPrintInstructionTables() {
251 return !shouldPrintInstructionTables(ITType: InstructionTablesType::NONE);
252}
253
254static cl::opt<bool> PrintInstructionInfoView(
255 "instruction-info",
256 cl::desc("Print the instruction info view (enabled by default)"),
257 cl::cat(ViewOptions), cl::init(Val: true));
258
259static cl::opt<bool> EnableAllStats("all-stats",
260 cl::desc("Print all hardware statistics"),
261 cl::cat(ViewOptions), cl::init(Val: false));
262
263static cl::opt<bool>
264 EnableAllViews("all-views",
265 cl::desc("Print all views including hardware statistics"),
266 cl::cat(ViewOptions), cl::init(Val: false));
267
268static cl::opt<bool> EnableBottleneckAnalysis(
269 "bottleneck-analysis",
270 cl::desc("Enable bottleneck analysis (disabled by default)"),
271 cl::cat(ViewOptions), cl::init(Val: false));
272
273static cl::opt<bool> ShowEncoding(
274 "show-encoding",
275 cl::desc("Print encoding information in the instruction info view"),
276 cl::cat(ViewOptions), cl::init(Val: false));
277
278static cl::opt<bool> ShowBarriers(
279 "show-barriers",
280 cl::desc("Print memory barrier information in the instruction info view"),
281 cl::cat(ViewOptions), cl::init(Val: false));
282
283static cl::opt<bool> DisableCustomBehaviour(
284 "disable-cb",
285 cl::desc(
286 "Disable custom behaviour (use the default class which does nothing)."),
287 cl::cat(ViewOptions), cl::init(Val: false));
288
289static cl::opt<bool> DisableInstrumentManager(
290 "disable-im",
291 cl::desc("Disable instrumentation manager (use the default class which "
292 "ignores instruments.)."),
293 cl::cat(ViewOptions), cl::init(Val: false));
294
295namespace {
296
297const Target *getTarget(Triple &TheTriple, const char *ProgName) {
298 // Get the target specific parser.
299 std::string Error;
300 const Target *TheTarget =
301 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
302 if (!TheTarget) {
303 errs() << ProgName << ": " << Error;
304 return nullptr;
305 }
306
307 // Return the found target.
308 return TheTarget;
309}
310
311ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
312 if (OutputFilename == "")
313 OutputFilename = "-";
314 std::error_code EC;
315 auto Out = std::make_unique<ToolOutputFile>(args&: OutputFilename, args&: EC,
316 args: sys::fs::OF_TextWithCRLF);
317 if (!EC)
318 return std::move(Out);
319 return EC;
320}
321} // end of anonymous namespace
322
323static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
324 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
325 O = Default.getValue();
326}
327
328static void processViewOptions(bool IsOutOfOrder) {
329 if (!EnableAllViews.getNumOccurrences() &&
330 !EnableAllStats.getNumOccurrences())
331 return;
332
333 if (EnableAllViews.getNumOccurrences()) {
334 processOptionImpl(O&: PrintSummaryView, Default: EnableAllViews);
335 if (IsOutOfOrder)
336 processOptionImpl(O&: EnableBottleneckAnalysis, Default: EnableAllViews);
337 processOptionImpl(O&: PrintResourcePressureView, Default: EnableAllViews);
338 processOptionImpl(O&: PrintTimelineView, Default: EnableAllViews);
339 processOptionImpl(O&: PrintInstructionInfoView, Default: EnableAllViews);
340 }
341
342 const cl::opt<bool> &Default =
343 EnableAllViews.getPosition() < EnableAllStats.getPosition()
344 ? EnableAllStats
345 : EnableAllViews;
346 processOptionImpl(O&: PrintRegisterFileStats, Default);
347 processOptionImpl(O&: PrintDispatchStats, Default);
348 processOptionImpl(O&: PrintSchedulerStats, Default);
349 if (IsOutOfOrder)
350 processOptionImpl(O&: PrintRetireStats, Default);
351}
352
353// Returns true on success.
354static bool runPipeline(mca::Pipeline &P) {
355 // Handle pipeline errors here.
356 Expected<unsigned> Cycles = P.run();
357 if (!Cycles) {
358 WithColor::error() << toString(E: Cycles.takeError());
359 return false;
360 }
361 return true;
362}
363
364int main(int argc, char **argv) {
365 InitLLVM X(argc, argv);
366
367 // Initialize targets and assembly parsers.
368 InitializeAllTargetInfos();
369 InitializeAllTargetMCs();
370 InitializeAllAsmParsers();
371 InitializeAllTargetMCAs();
372
373 // Register the Target and CPU printer for --version.
374 cl::AddExtraVersionPrinter(func: sys::printDefaultTargetAndDetectedCPU);
375
376 // Enable printing of available targets when flag --version is specified.
377 cl::AddExtraVersionPrinter(func: TargetRegistry::printRegisteredTargetsForVersion);
378
379 cl::HideUnrelatedOptions(Categories: {&ToolOptions, &ViewOptions, &MCScheduleOptions});
380
381 // Parse flags and initialize target options.
382 cl::ParseCommandLineOptions(argc, argv,
383 Overview: "llvm machine code performance analyzer.\n");
384
385 Triple TheTriple(TripleNameOpt.empty()
386 ? Triple::normalize(Str: sys::getDefaultTargetTriple())
387 : TripleNameOpt);
388
389 // Get the target from the triple. If a triple is not specified, then select
390 // the default triple for the host. If the triple doesn't correspond to any
391 // registered target, then exit with an error message.
392 const char *ProgName = argv[0];
393 const Target *TheTarget = getTarget(TheTriple, ProgName);
394 if (!TheTarget)
395 return 1;
396
397 const bool WantsCPUHelp = MCPU == "help";
398
399 std::unique_ptr<MemoryBuffer> InputBuffer;
400 if (!WantsCPUHelp) {
401 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
402 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename);
403 if (!BufferOrErr) {
404 std::error_code EC = BufferOrErr.getError();
405 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
406 return 1;
407 }
408 InputBuffer = std::move(*BufferOrErr);
409 }
410
411 if (MCPU == "native")
412 MCPU = std::string(llvm::sys::getHostCPUName());
413
414 // Package up features to be passed to target/subtarget
415 std::string FeaturesStr;
416 if (MATTRS.size()) {
417 SubtargetFeatures Features;
418 for (std::string &MAttr : MATTRS)
419 Features.AddFeature(String: MAttr);
420 FeaturesStr = Features.getString();
421 }
422
423 std::unique_ptr<MCSubtargetInfo> STI(
424 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: FeaturesStr));
425 if (!STI) {
426 WithColor::error() << "unable to create subtarget info\n";
427 return 1;
428 }
429
430 if (TheTriple.isAArch64() && STI->checkFeatures(FS: "+mca-streaming-sched"))
431 WithColor::warning()
432 << "AArch64 streaming SVE scheduling is enabled via "
433 "'-mattr=+mca-streaming-sched'; llvm-mca results are approximate.\n";
434
435 if (WantsCPUHelp)
436 return 0;
437
438 if (!STI->getSchedModel().hasInstrSchedModel()) {
439 WithColor::error()
440 << "unable to find instruction-level scheduling information for"
441 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
442 << "'.\n";
443
444 if (STI->getSchedModel().InstrItineraries)
445 WithColor::note()
446 << "cpu '" << MCPU << "' provides itineraries. However, "
447 << "instruction itineraries are currently unsupported.\n";
448 return 1;
449 }
450
451 // Apply overrides to llvm-mca specific options.
452 bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
453 processViewOptions(IsOutOfOrder);
454
455 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TheTriple));
456 assert(MRI && "Unable to create target register info!");
457
458 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
459 std::unique_ptr<MCAsmInfo> MAI(
460 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
461 assert(MAI && "Unable to create target asm info!");
462
463 SourceMgr SrcMgr;
464
465 // Tell SrcMgr about this buffer, which is what the parser will pick up.
466 SrcMgr.AddNewSourceBuffer(F: std::move(InputBuffer), IncludeLoc: SMLoc());
467
468 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
469 assert(MCII && "Unable to create instruction info!");
470
471 std::unique_ptr<MCInstrAnalysis> MCIA(
472 TheTarget->createMCInstrAnalysis(Info: MCII.get()));
473
474 // Need to initialize an MCInstPrinter as it is
475 // required for initializing the MCTargetStreamer
476 // which needs to happen within the CRG.parseAnalysisRegions() call below.
477 // Without an MCTargetStreamer, certain assembly directives can trigger a
478 // segfault. (For example, the .cv_fpo_proc directive on x86 will segfault if
479 // we don't initialize the MCTargetStreamer.)
480 unsigned IPtempOutputAsmVariant =
481 OutputAsmVariant == -1 ? 0 : OutputAsmVariant;
482 std::unique_ptr<MCInstPrinter> IPtemp(TheTarget->createMCInstPrinter(
483 T: TheTriple, SyntaxVariant: IPtempOutputAsmVariant, MAI: *MAI, MII: *MCII, MRI: *MRI));
484 if (!IPtemp) {
485 WithColor::error()
486 << "unable to create instruction printer for target triple '"
487 << TheTriple.normalize() << "' with assembly variant "
488 << IPtempOutputAsmVariant << ".\n";
489 return 1;
490 }
491
492 // Parse the input and create CodeRegions that llvm-mca can analyze.
493 MCContext ACtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
494 std::unique_ptr<MCObjectFileInfo> AMOFI(
495 TheTarget->createMCObjectFileInfo(Ctx&: ACtx, /*PIC=*/false));
496 ACtx.setObjectFileInfo(AMOFI.get());
497 mca::AsmAnalysisRegionGenerator CRG(*TheTarget, SrcMgr, ACtx, *MAI, *STI,
498 *MCII);
499 Expected<const mca::AnalysisRegions &> RegionsOrErr =
500 CRG.parseAnalysisRegions(IP: std::move(IPtemp),
501 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
502 if (!RegionsOrErr) {
503 if (auto Err =
504 handleErrors(E: RegionsOrErr.takeError(), Hs: [](const StringError &E) {
505 WithColor::error() << E.getMessage() << '\n';
506 })) {
507 // Default case.
508 WithColor::error() << toString(E: std::move(Err)) << '\n';
509 }
510 return 1;
511 }
512 const mca::AnalysisRegions &Regions = *RegionsOrErr;
513
514 // Early exit if errors were found by the code region parsing logic.
515 if (!Regions.isValid())
516 return 1;
517
518 if (Regions.empty()) {
519 WithColor::error() << "no assembly instructions found.\n";
520 return 1;
521 }
522
523 std::unique_ptr<mca::InstrumentManager> IM;
524 if (!DisableInstrumentManager) {
525 IM = std::unique_ptr<mca::InstrumentManager>(
526 TheTarget->createInstrumentManager(STI: *STI, MCII: *MCII));
527 if (!IM) {
528 // If the target doesn't have its own IM implemented we use base class
529 // with instruments enabled.
530 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII);
531 }
532 } else {
533 // If the -disable-im flag is set then we use the default base class
534 // implementation and disable the instruments.
535 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII,
536 /*EnableInstruments=*/args: false);
537 }
538
539 // Parse the input and create InstrumentRegion that llvm-mca
540 // can use to improve analysis.
541 MCContext ICtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
542 std::unique_ptr<MCObjectFileInfo> IMOFI(
543 TheTarget->createMCObjectFileInfo(Ctx&: ICtx, /*PIC=*/false));
544 ICtx.setObjectFileInfo(IMOFI.get());
545 mca::AsmInstrumentRegionGenerator IRG(*TheTarget, SrcMgr, ICtx, *MAI, *STI,
546 *MCII, *IM);
547 Expected<const mca::InstrumentRegions &> InstrumentRegionsOrErr =
548 IRG.parseInstrumentRegions(IP: std::move(IPtemp),
549 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
550 if (!InstrumentRegionsOrErr) {
551 if (auto Err = handleErrors(E: InstrumentRegionsOrErr.takeError(),
552 Hs: [](const StringError &E) {
553 WithColor::error() << E.getMessage() << '\n';
554 })) {
555 // Default case.
556 WithColor::error() << toString(E: std::move(Err)) << '\n';
557 }
558 return 1;
559 }
560 const mca::InstrumentRegions &InstrumentRegions = *InstrumentRegionsOrErr;
561
562 // Early exit if errors were found by the instrumentation parsing logic.
563 if (!InstrumentRegions.isValid())
564 return 1;
565
566 // Now initialize the output file.
567 auto OF = getOutputStream();
568 if (std::error_code EC = OF.getError()) {
569 WithColor::error() << EC.message() << '\n';
570 return 1;
571 }
572
573 unsigned AssemblerDialect = CRG.getAssemblerDialect();
574 if (OutputAsmVariant >= 0)
575 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
576 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
577 T: TheTriple, SyntaxVariant: AssemblerDialect, MAI: *MAI, MII: *MCII, MRI: *MRI));
578 if (!IP) {
579 WithColor::error()
580 << "unable to create instruction printer for target triple '"
581 << TheTriple.normalize() << "' with assembly variant "
582 << AssemblerDialect << ".\n";
583 return 1;
584 }
585
586 // Set the display preference for hex vs. decimal immediates.
587 IP->setPrintImmHex(PrintImmHex);
588
589 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
590
591 const MCSchedModel &SM = STI->getSchedModel();
592
593 std::unique_ptr<mca::InstrPostProcess> IPP;
594 if (!DisableCustomBehaviour) {
595 // TODO: It may be a good idea to separate CB and IPP so that they can
596 // be used independently of each other. What I mean by this is to add
597 // an extra command-line arg --disable-ipp so that CB and IPP can be
598 // toggled without needing to toggle both of them together.
599 IPP = std::unique_ptr<mca::InstrPostProcess>(
600 TheTarget->createInstrPostProcess(STI: *STI, MCII: *MCII));
601 }
602 if (!IPP) {
603 // If the target doesn't have its own IPP implemented (or the -disable-cb
604 // flag is set) then we use the base class (which does nothing).
605 IPP = std::make_unique<mca::InstrPostProcess>(args&: *STI, args&: *MCII);
606 }
607
608 // Create an instruction builder.
609 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get(), *IM, CallLatency);
610
611 // Create a context to control ownership of the pipeline hardware.
612 mca::Context MCA(*MRI, *STI);
613
614 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
615 RegisterFileSize, LoadQueueSize, StoreQueueSize,
616 AssumeNoAlias, EnableBottleneckAnalysis);
617
618 // Number each region in the sequence.
619 unsigned RegionIdx = 0;
620
621 std::unique_ptr<MCCodeEmitter> MCE(
622 TheTarget->createMCCodeEmitter(II: *MCII, Ctx&: ACtx));
623 assert(MCE && "Unable to create code emitter!");
624
625 std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
626 STI: *STI, MRI: *MRI, Options: mc::InitMCTargetOptionsFromFlags()));
627 assert(MAB && "Unable to create asm backend!");
628
629 json::Object JSONOutput;
630 int NonEmptyRegions = 0;
631 for (const std::unique_ptr<mca::AnalysisRegion> &Region : Regions) {
632 // Skip empty code regions.
633 if (Region->empty())
634 continue;
635
636 IB.clear();
637
638 // Lower the MCInst sequence into an mca::Instruction sequence.
639 ArrayRef<MCInst> Insts = Region->getInstructions();
640 mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
641
642 IPP->resetState();
643
644 DenseMap<const MCInst *, SmallVector<mca::Instrument *>> InstToInstruments;
645 SmallVector<std::unique_ptr<mca::Instruction>> LoweredSequence;
646 SmallPtrSet<const MCInst *, 16> DroppedInsts;
647 for (const MCInst &MCI : Insts) {
648 SMLoc Loc = MCI.getLoc();
649 const SmallVector<mca::Instrument *> Instruments =
650 InstrumentRegions.getActiveInstruments(Loc);
651
652 Expected<std::unique_ptr<mca::Instruction>> Inst =
653 IB.createInstruction(MCI, IVec: Instruments);
654 if (!Inst) {
655 if (auto NewE = handleErrors(
656 E: Inst.takeError(),
657 Hs: [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
658 std::string InstructionStr;
659 raw_string_ostream SS(InstructionStr);
660 if (shouldSkip(skipType: SkipType::LACK_SCHED))
661 WithColor::warning()
662 << IE.Message
663 << ", skipping with -skip-unsupported-instructions, "
664 "note accuracy will be impacted:\n";
665 else
666 WithColor::error()
667 << IE.Message
668 << ", use -skip-unsupported-instructions=lack-sched to "
669 "ignore these on the input.\n";
670 IP->printInst(MI: &IE.Inst, Address: 0, Annot: "", STI: *STI, OS&: SS);
671 WithColor::note()
672 << "instruction: " << InstructionStr << '\n';
673 })) {
674 // Default case.
675 WithColor::error() << toString(E: std::move(NewE));
676 }
677 if (shouldSkip(skipType: SkipType::LACK_SCHED)) {
678 DroppedInsts.insert(Ptr: &MCI);
679 continue;
680 }
681 return 1;
682 }
683
684 IPP->postProcessInstruction(Inst&: *Inst.get(), MCI);
685 InstToInstruments.insert(KV: {&MCI, Instruments});
686 LoweredSequence.emplace_back(Args: std::move(Inst.get()));
687 }
688
689 Insts = Region->dropInstructions(Insts: DroppedInsts);
690
691 // Skip empty regions.
692 if (Insts.empty())
693 continue;
694 NonEmptyRegions++;
695
696 mca::CircularSourceMgr S(LoweredSequence,
697 shouldPrintInstructionTables() ? 1 : Iterations);
698
699 if (shouldPrintInstructionTables()) {
700 // Create a pipeline, stages, and a printer.
701 auto P = std::make_unique<mca::Pipeline>();
702 P->appendStage(S: std::make_unique<mca::EntryStage>(args&: S));
703 P->appendStage(S: std::make_unique<mca::InstructionTables>(args: SM));
704
705 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
706 if (PrintJson) {
707 Printer.addView(
708 V: std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts));
709 }
710
711 // Create the views for this pipeline, execute, and emit a report.
712 if (PrintInstructionInfoView) {
713 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
714 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
715 args&: ShowBarriers,
716 args: shouldPrintInstructionTables(ITType: InstructionTablesType::FULL), args&: *IM,
717 args&: InstToInstruments));
718 }
719
720 if (PrintResourcePressureView)
721 Printer.addView(
722 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
723
724 if (!runPipeline(P&: *P))
725 return 1;
726
727 if (PrintJson) {
728 Printer.printReport(JO&: JSONOutput);
729 } else {
730 Printer.printReport(OS&: TOF->os());
731 }
732
733 ++RegionIdx;
734 continue;
735 }
736
737 // Create the CustomBehaviour object for enforcing Target Specific
738 // behaviours and dependencies that aren't expressed well enough
739 // in the tablegen. CB cannot depend on the list of MCInst or
740 // the source code (but it can depend on the list of
741 // mca::Instruction or any objects that can be reconstructed
742 // from the target information).
743 std::unique_ptr<mca::CustomBehaviour> CB;
744 if (!DisableCustomBehaviour)
745 CB = std::unique_ptr<mca::CustomBehaviour>(
746 TheTarget->createCustomBehaviour(STI: *STI, SrcMgr: S, MCII: *MCII));
747 if (!CB)
748 // If the target doesn't have its own CB implemented (or the -disable-cb
749 // flag is set) then we use the base class (which does nothing).
750 CB = std::make_unique<mca::CustomBehaviour>(args&: *STI, args&: S, args&: *MCII);
751
752 // Create a basic pipeline simulating an out-of-order backend.
753 auto P = MCA.createDefaultPipeline(Opts: PO, SrcMgr&: S, CB&: *CB);
754
755 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
756
757 // Targets can define their own custom Views that exist within their
758 // /lib/Target/ directory so that the View can utilize their CustomBehaviour
759 // or other backend symbols / functionality that are not already exposed
760 // through one of the MC-layer classes. These Views will be initialized
761 // using the CustomBehaviour::getViews() variants.
762 // If a target makes a custom View that does not depend on their target
763 // CB or their backend, they should put the View within
764 // /tools/llvm-mca/Views/ instead.
765 if (!DisableCustomBehaviour) {
766 std::vector<std::unique_ptr<mca::View>> CBViews =
767 CB->getStartViews(IP&: *IP, Insts);
768 for (auto &CBView : CBViews)
769 Printer.addView(V: std::move(CBView));
770 }
771
772 // When we output JSON, we add a view that contains the instructions
773 // and CPU resource information.
774 if (PrintJson) {
775 auto IV = std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts);
776 Printer.addView(V: std::move(IV));
777 }
778
779 if (PrintSummaryView)
780 Printer.addView(
781 V: std::make_unique<mca::SummaryView>(args: SM, args&: Insts, args&: DispatchWidth));
782
783 if (EnableBottleneckAnalysis) {
784 if (!IsOutOfOrder) {
785 WithColor::warning()
786 << "bottleneck analysis is not supported for in-order CPU '" << MCPU
787 << "'.\n";
788 }
789 Printer.addView(V: std::make_unique<mca::BottleneckAnalysis>(
790 args&: *STI, args&: *IP, args&: Insts, args: S.getNumIterations()));
791 }
792
793 if (PrintInstructionInfoView)
794 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
795 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
796 args&: ShowBarriers, /*ShouldPrintFullInfo=*/args: false, args&: *IM, args&: InstToInstruments));
797
798 // Fetch custom Views that are to be placed after the InstructionInfoView.
799 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
800 // for more info.
801 if (!DisableCustomBehaviour) {
802 std::vector<std::unique_ptr<mca::View>> CBViews =
803 CB->getPostInstrInfoViews(IP&: *IP, Insts);
804 for (auto &CBView : CBViews)
805 Printer.addView(V: std::move(CBView));
806 }
807
808 if (PrintDispatchStats)
809 Printer.addView(V: std::make_unique<mca::DispatchStatistics>());
810
811 if (PrintSchedulerStats)
812 Printer.addView(V: std::make_unique<mca::SchedulerStatistics>(args&: *STI));
813
814 if (PrintRetireStats)
815 Printer.addView(V: std::make_unique<mca::RetireControlUnitStatistics>(args: SM));
816
817 if (PrintRegisterFileStats)
818 Printer.addView(V: std::make_unique<mca::RegisterFileStatistics>(args&: *STI));
819
820 if (PrintResourcePressureView)
821 Printer.addView(
822 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
823
824 if (PrintTimelineView) {
825 unsigned TimelineIterations =
826 TimelineMaxIterations ? TimelineMaxIterations : 10;
827 Printer.addView(V: std::make_unique<mca::TimelineView>(
828 args&: *STI, args&: *IP, args&: Insts, args: std::min(a: TimelineIterations, b: S.getNumIterations()),
829 args&: TimelineMaxCycles));
830 }
831
832 // Fetch custom Views that are to be placed after all other Views.
833 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
834 // for more info.
835 if (!DisableCustomBehaviour) {
836 std::vector<std::unique_ptr<mca::View>> CBViews =
837 CB->getEndViews(IP&: *IP, Insts);
838 for (auto &CBView : CBViews)
839 Printer.addView(V: std::move(CBView));
840 }
841
842 if (!runPipeline(P&: *P))
843 return 1;
844
845 if (PrintJson) {
846 Printer.printReport(JO&: JSONOutput);
847 } else {
848 Printer.printReport(OS&: TOF->os());
849 }
850
851 ++RegionIdx;
852 }
853
854 if (NonEmptyRegions == 0) {
855 WithColor::error() << "no assembly instructions found.\n";
856 return 1;
857 }
858
859 if (PrintJson)
860 TOF->os() << formatv(Fmt: "{0:2}", Vals: json::Value(std::move(JSONOutput))) << "\n";
861
862 TOF->keep();
863 return 0;
864}
865