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