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/MCAsmInfo.h" 36 #include "llvm/MC/MCContext.h" 37 #include "llvm/MC/MCObjectFileInfo.h" 38 #include "llvm/MC/MCRegisterInfo.h" 39 #include "llvm/MCA/Context.h" 40 #include "llvm/MCA/Pipeline.h" 41 #include "llvm/MCA/Stages/EntryStage.h" 42 #include "llvm/MCA/Stages/InstructionTables.h" 43 #include "llvm/MCA/Support.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/ErrorOr.h" 47 #include "llvm/Support/FileSystem.h" 48 #include "llvm/Support/Host.h" 49 #include "llvm/Support/InitLLVM.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/SourceMgr.h" 52 #include "llvm/Support/TargetRegistry.h" 53 #include "llvm/Support/TargetSelect.h" 54 #include "llvm/Support/ToolOutputFile.h" 55 #include "llvm/Support/WithColor.h" 56 57 using namespace llvm; 58 59 static cl::OptionCategory ToolOptions("Tool Options"); 60 static cl::OptionCategory ViewOptions("View Options"); 61 62 static cl::opt<std::string> InputFilename(cl::Positional, 63 cl::desc("<input file>"), 64 cl::cat(ToolOptions), cl::init("-")); 65 66 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), 67 cl::init("-"), cl::cat(ToolOptions), 68 cl::value_desc("filename")); 69 70 static cl::opt<std::string> 71 ArchName("march", 72 cl::desc("Target architecture. " 73 "See -version for available targets"), 74 cl::cat(ToolOptions)); 75 76 static cl::opt<std::string> 77 TripleName("mtriple", 78 cl::desc("Target triple. See -version for available targets"), 79 cl::cat(ToolOptions)); 80 81 static cl::opt<std::string> 82 MCPU("mcpu", 83 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 84 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native")); 85 86 static cl::opt<int> 87 OutputAsmVariant("output-asm-variant", 88 cl::desc("Syntax variant to use for output printing"), 89 cl::cat(ToolOptions), cl::init(-1)); 90 91 static cl::opt<unsigned> Iterations("iterations", 92 cl::desc("Number of iterations to run"), 93 cl::cat(ToolOptions), cl::init(0)); 94 95 static cl::opt<unsigned> 96 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"), 97 cl::cat(ToolOptions), cl::init(0)); 98 99 static cl::opt<unsigned> 100 RegisterFileSize("register-file-size", 101 cl::desc("Maximum number of physical registers which can " 102 "be used for register mappings"), 103 cl::cat(ToolOptions), cl::init(0)); 104 105 static cl::opt<unsigned> 106 MicroOpQueue("micro-op-queue-size", cl::Hidden, 107 cl::desc("Number of entries in the micro-op queue"), 108 cl::cat(ToolOptions), cl::init(0)); 109 110 static cl::opt<unsigned> 111 DecoderThroughput("decoder-throughput", cl::Hidden, 112 cl::desc("Maximum throughput from the decoders " 113 "(instructions per cycle)"), 114 cl::cat(ToolOptions), cl::init(0)); 115 116 static cl::opt<bool> 117 PrintRegisterFileStats("register-file-stats", 118 cl::desc("Print register file statistics"), 119 cl::cat(ViewOptions), cl::init(false)); 120 121 static cl::opt<bool> PrintDispatchStats("dispatch-stats", 122 cl::desc("Print dispatch statistics"), 123 cl::cat(ViewOptions), cl::init(false)); 124 125 static cl::opt<bool> 126 PrintSummaryView("summary-view", cl::Hidden, 127 cl::desc("Print summary view (enabled by default)"), 128 cl::cat(ViewOptions), cl::init(true)); 129 130 static cl::opt<bool> PrintSchedulerStats("scheduler-stats", 131 cl::desc("Print scheduler statistics"), 132 cl::cat(ViewOptions), cl::init(false)); 133 134 static cl::opt<bool> 135 PrintRetireStats("retire-stats", 136 cl::desc("Print retire control unit statistics"), 137 cl::cat(ViewOptions), cl::init(false)); 138 139 static cl::opt<bool> PrintResourcePressureView( 140 "resource-pressure", 141 cl::desc("Print the resource pressure view (enabled by default)"), 142 cl::cat(ViewOptions), cl::init(true)); 143 144 static cl::opt<bool> PrintTimelineView("timeline", 145 cl::desc("Print the timeline view"), 146 cl::cat(ViewOptions), cl::init(false)); 147 148 static cl::opt<unsigned> TimelineMaxIterations( 149 "timeline-max-iterations", 150 cl::desc("Maximum number of iterations to print in timeline view"), 151 cl::cat(ViewOptions), cl::init(0)); 152 153 static cl::opt<unsigned> TimelineMaxCycles( 154 "timeline-max-cycles", 155 cl::desc( 156 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"), 157 cl::cat(ViewOptions), cl::init(80)); 158 159 static cl::opt<bool> 160 AssumeNoAlias("noalias", 161 cl::desc("If set, assume that loads and stores do not alias"), 162 cl::cat(ToolOptions), cl::init(true)); 163 164 static cl::opt<unsigned> LoadQueueSize("lqueue", 165 cl::desc("Size of the load queue"), 166 cl::cat(ToolOptions), cl::init(0)); 167 168 static cl::opt<unsigned> StoreQueueSize("squeue", 169 cl::desc("Size of the store queue"), 170 cl::cat(ToolOptions), cl::init(0)); 171 172 static cl::opt<bool> 173 PrintInstructionTables("instruction-tables", 174 cl::desc("Print instruction tables"), 175 cl::cat(ToolOptions), cl::init(false)); 176 177 static cl::opt<bool> PrintInstructionInfoView( 178 "instruction-info", 179 cl::desc("Print the instruction info view (enabled by default)"), 180 cl::cat(ViewOptions), cl::init(true)); 181 182 static cl::opt<bool> EnableAllStats("all-stats", 183 cl::desc("Print all hardware statistics"), 184 cl::cat(ViewOptions), cl::init(false)); 185 186 static cl::opt<bool> 187 EnableAllViews("all-views", 188 cl::desc("Print all views including hardware statistics"), 189 cl::cat(ViewOptions), cl::init(false)); 190 191 static cl::opt<bool> EnableBottleneckAnalysis( 192 "bottleneck-analysis", 193 cl::desc("Enable bottleneck analysis (disabled by default)"), 194 cl::cat(ViewOptions), cl::init(false)); 195 196 namespace { 197 198 const Target *getTarget(const char *ProgName) { 199 if (TripleName.empty()) 200 TripleName = Triple::normalize(sys::getDefaultTargetTriple()); 201 Triple TheTriple(TripleName); 202 203 // Get the target specific parser. 204 std::string Error; 205 const Target *TheTarget = 206 TargetRegistry::lookupTarget(ArchName, TheTriple, Error); 207 if (!TheTarget) { 208 errs() << ProgName << ": " << Error; 209 return nullptr; 210 } 211 212 // Return the found target. 213 return TheTarget; 214 } 215 216 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() { 217 if (OutputFilename == "") 218 OutputFilename = "-"; 219 std::error_code EC; 220 auto Out = 221 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None); 222 if (!EC) 223 return std::move(Out); 224 return EC; 225 } 226 } // end of anonymous namespace 227 228 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) { 229 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition()) 230 O = Default.getValue(); 231 } 232 233 static void processViewOptions() { 234 if (!EnableAllViews.getNumOccurrences() && 235 !EnableAllStats.getNumOccurrences()) 236 return; 237 238 if (EnableAllViews.getNumOccurrences()) { 239 processOptionImpl(PrintSummaryView, EnableAllViews); 240 processOptionImpl(EnableBottleneckAnalysis, EnableAllViews); 241 processOptionImpl(PrintResourcePressureView, EnableAllViews); 242 processOptionImpl(PrintTimelineView, EnableAllViews); 243 processOptionImpl(PrintInstructionInfoView, EnableAllViews); 244 } 245 246 const cl::opt<bool> &Default = 247 EnableAllViews.getPosition() < EnableAllStats.getPosition() 248 ? EnableAllStats 249 : EnableAllViews; 250 processOptionImpl(PrintRegisterFileStats, Default); 251 processOptionImpl(PrintDispatchStats, Default); 252 processOptionImpl(PrintSchedulerStats, Default); 253 processOptionImpl(PrintRetireStats, Default); 254 } 255 256 // Returns true on success. 257 static bool runPipeline(mca::Pipeline &P) { 258 // Handle pipeline errors here. 259 Expected<unsigned> Cycles = P.run(); 260 if (!Cycles) { 261 WithColor::error() << toString(Cycles.takeError()); 262 return false; 263 } 264 return true; 265 } 266 267 int main(int argc, char **argv) { 268 InitLLVM X(argc, argv); 269 270 // Initialize targets and assembly parsers. 271 InitializeAllTargetInfos(); 272 InitializeAllTargetMCs(); 273 InitializeAllAsmParsers(); 274 275 // Enable printing of available targets when flag --version is specified. 276 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 277 278 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions}); 279 280 // Parse flags and initialize target options. 281 cl::ParseCommandLineOptions(argc, argv, 282 "llvm machine code performance analyzer.\n"); 283 284 // Get the target from the triple. If a triple is not specified, then select 285 // the default triple for the host. If the triple doesn't correspond to any 286 // registered target, then exit with an error message. 287 const char *ProgName = argv[0]; 288 const Target *TheTarget = getTarget(ProgName); 289 if (!TheTarget) 290 return 1; 291 292 // GetTarget() may replaced TripleName with a default triple. 293 // For safety, reconstruct the Triple object. 294 Triple TheTriple(TripleName); 295 296 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr = 297 MemoryBuffer::getFileOrSTDIN(InputFilename); 298 if (std::error_code EC = BufferPtr.getError()) { 299 WithColor::error() << InputFilename << ": " << EC.message() << '\n'; 300 return 1; 301 } 302 303 // Apply overrides to llvm-mca specific options. 304 processViewOptions(); 305 306 SourceMgr SrcMgr; 307 308 // Tell SrcMgr about this buffer, which is what the parser will pick up. 309 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc()); 310 311 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 312 assert(MRI && "Unable to create target register info!"); 313 314 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName)); 315 assert(MAI && "Unable to create target asm info!"); 316 317 MCObjectFileInfo MOFI; 318 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr); 319 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx); 320 321 std::unique_ptr<buffer_ostream> BOS; 322 323 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 324 325 std::unique_ptr<MCInstrAnalysis> MCIA( 326 TheTarget->createMCInstrAnalysis(MCII.get())); 327 328 if (!MCPU.compare("native")) 329 MCPU = llvm::sys::getHostCPUName(); 330 331 std::unique_ptr<MCSubtargetInfo> STI( 332 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ "")); 333 if (!STI->isCPUStringValid(MCPU)) 334 return 1; 335 336 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) { 337 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU 338 << "' is an in-order cpu.\n"; 339 return 1; 340 } 341 342 if (!STI->getSchedModel().hasInstrSchedModel()) { 343 WithColor::error() 344 << "unable to find instruction-level scheduling information for" 345 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU 346 << "'.\n"; 347 348 if (STI->getSchedModel().InstrItineraries) 349 WithColor::note() 350 << "cpu '" << MCPU << "' provides itineraries. However, " 351 << "instruction itineraries are currently unsupported.\n"; 352 return 1; 353 } 354 355 // Parse the input and create CodeRegions that llvm-mca can analyze. 356 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII); 357 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions(); 358 if (!RegionsOrErr) { 359 if (auto Err = 360 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) { 361 WithColor::error() << E.getMessage() << '\n'; 362 })) { 363 // Default case. 364 WithColor::error() << toString(std::move(Err)) << '\n'; 365 } 366 return 1; 367 } 368 const mca::CodeRegions &Regions = *RegionsOrErr; 369 370 // Early exit if errors were found by the code region parsing logic. 371 if (!Regions.isValid()) 372 return 1; 373 374 if (Regions.empty()) { 375 WithColor::error() << "no assembly instructions found.\n"; 376 return 1; 377 } 378 379 // Now initialize the output file. 380 auto OF = getOutputStream(); 381 if (std::error_code EC = OF.getError()) { 382 WithColor::error() << EC.message() << '\n'; 383 return 1; 384 } 385 386 unsigned AssemblerDialect = CRG.getAssemblerDialect(); 387 if (OutputAsmVariant >= 0) 388 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant); 389 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 390 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI)); 391 if (!IP) { 392 WithColor::error() 393 << "unable to create instruction printer for target triple '" 394 << TheTriple.normalize() << "' with assembly variant " 395 << AssemblerDialect << ".\n"; 396 return 1; 397 } 398 399 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF); 400 401 const MCSchedModel &SM = STI->getSchedModel(); 402 403 // Create an instruction builder. 404 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get()); 405 406 // Create a context to control ownership of the pipeline hardware. 407 mca::Context MCA(*MRI, *STI); 408 409 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth, 410 RegisterFileSize, LoadQueueSize, StoreQueueSize, 411 AssumeNoAlias, EnableBottleneckAnalysis); 412 413 // Number each region in the sequence. 414 unsigned RegionIdx = 0; 415 416 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) { 417 // Skip empty code regions. 418 if (Region->empty()) 419 continue; 420 421 // Don't print the header of this region if it is the default region, and 422 // it doesn't have an end location. 423 if (Region->startLoc().isValid() || Region->endLoc().isValid()) { 424 TOF->os() << "\n[" << RegionIdx++ << "] Code Region"; 425 StringRef Desc = Region->getDescription(); 426 if (!Desc.empty()) 427 TOF->os() << " - " << Desc; 428 TOF->os() << "\n\n"; 429 } 430 431 // Lower the MCInst sequence into an mca::Instruction sequence. 432 ArrayRef<MCInst> Insts = Region->getInstructions(); 433 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence; 434 for (const MCInst &MCI : Insts) { 435 Expected<std::unique_ptr<mca::Instruction>> Inst = 436 IB.createInstruction(MCI); 437 if (!Inst) { 438 if (auto NewE = handleErrors( 439 Inst.takeError(), 440 [&IP, &STI](const mca::InstructionError<MCInst> &IE) { 441 std::string InstructionStr; 442 raw_string_ostream SS(InstructionStr); 443 WithColor::error() << IE.Message << '\n'; 444 IP->printInst(&IE.Inst, SS, "", *STI); 445 SS.flush(); 446 WithColor::note() 447 << "instruction: " << InstructionStr << '\n'; 448 })) { 449 // Default case. 450 WithColor::error() << toString(std::move(NewE)); 451 } 452 return 1; 453 } 454 455 LoweredSequence.emplace_back(std::move(Inst.get())); 456 } 457 458 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations); 459 460 if (PrintInstructionTables) { 461 // Create a pipeline, stages, and a printer. 462 auto P = llvm::make_unique<mca::Pipeline>(); 463 P->appendStage(llvm::make_unique<mca::EntryStage>(S)); 464 P->appendStage(llvm::make_unique<mca::InstructionTables>(SM)); 465 mca::PipelinePrinter Printer(*P); 466 467 // Create the views for this pipeline, execute, and emit a report. 468 if (PrintInstructionInfoView) { 469 Printer.addView(llvm::make_unique<mca::InstructionInfoView>( 470 *STI, *MCII, Insts, *IP)); 471 } 472 Printer.addView( 473 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts)); 474 475 if (!runPipeline(*P)) 476 return 1; 477 478 Printer.printReport(TOF->os()); 479 continue; 480 } 481 482 // Create a basic pipeline simulating an out-of-order backend. 483 auto P = MCA.createDefaultPipeline(PO, IB, S); 484 mca::PipelinePrinter Printer(*P); 485 486 if (PrintSummaryView) 487 Printer.addView( 488 llvm::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth)); 489 490 if (EnableBottleneckAnalysis) { 491 Printer.addView(llvm::make_unique<mca::BottleneckAnalysis>( 492 *STI, *IP, Insts, S.getNumIterations())); 493 } 494 495 if (PrintInstructionInfoView) 496 Printer.addView( 497 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP)); 498 499 if (PrintDispatchStats) 500 Printer.addView(llvm::make_unique<mca::DispatchStatistics>()); 501 502 if (PrintSchedulerStats) 503 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI)); 504 505 if (PrintRetireStats) 506 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM)); 507 508 if (PrintRegisterFileStats) 509 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI)); 510 511 if (PrintResourcePressureView) 512 Printer.addView( 513 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts)); 514 515 if (PrintTimelineView) { 516 unsigned TimelineIterations = 517 TimelineMaxIterations ? TimelineMaxIterations : 10; 518 Printer.addView(llvm::make_unique<mca::TimelineView>( 519 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()), 520 TimelineMaxCycles)); 521 } 522 523 if (!runPipeline(*P)) 524 return 1; 525 526 Printer.printReport(TOF->os()); 527 528 // Clear the InstrBuilder internal state in preparation for another round. 529 IB.clear(); 530 } 531 532 TOF->keep(); 533 return 0; 534 } 535