1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// 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 is the llc code generator driver. It provides a convenient 10 // command-line interface for generating native assembly-language code 11 // or C code, given LLVM bitcode. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/Analysis/TargetLibraryInfo.h" 18 #include "llvm/CodeGen/CommandFlags.h" 19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 20 #include "llvm/CodeGen/LinkAllCodegenComponents.h" 21 #include "llvm/CodeGen/MIRParser/MIRParser.h" 22 #include "llvm/CodeGen/MachineFunctionPass.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/TargetPassConfig.h" 25 #include "llvm/CodeGen/TargetSubtargetInfo.h" 26 #include "llvm/IR/AutoUpgrade.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DiagnosticInfo.h" 29 #include "llvm/IR/DiagnosticPrinter.h" 30 #include "llvm/IR/IRPrintingPasses.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/IR/LLVMRemarkStreamer.h" 33 #include "llvm/IR/LegacyPassManager.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/IRReader/IRReader.h" 37 #include "llvm/InitializePasses.h" 38 #include "llvm/MC/SubtargetFeature.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Remarks/HotnessThresholdParser.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/FormattedStream.h" 45 #include "llvm/Support/Host.h" 46 #include "llvm/Support/InitLLVM.h" 47 #include "llvm/Support/ManagedStatic.h" 48 #include "llvm/Support/PluginLoader.h" 49 #include "llvm/Support/SourceMgr.h" 50 #include "llvm/Support/TargetRegistry.h" 51 #include "llvm/Support/TargetSelect.h" 52 #include "llvm/Support/ToolOutputFile.h" 53 #include "llvm/Support/WithColor.h" 54 #include "llvm/Target/TargetLoweringObjectFile.h" 55 #include "llvm/Target/TargetMachine.h" 56 #include "llvm/Transforms/Utils/Cloning.h" 57 #include <memory> 58 using namespace llvm; 59 60 static codegen::RegisterCodeGenFlags CGF; 61 62 // General options for llc. Other pass-specific options are specified 63 // within the corresponding llc passes, and target-specific options 64 // and back-end code generation options are specified with the target machine. 65 // 66 static cl::opt<std::string> 67 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 68 69 static cl::opt<std::string> 70 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')")); 71 72 static cl::opt<std::string> 73 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 74 75 static cl::opt<std::string> 76 SplitDwarfOutputFile("split-dwarf-output", 77 cl::desc(".dwo output filename"), 78 cl::value_desc("filename")); 79 80 static cl::opt<unsigned> 81 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 82 cl::value_desc("N"), 83 cl::desc("Repeat compilation N times for timing")); 84 85 static cl::opt<std::string> 86 BinutilsVersion("binutils-version", cl::Hidden, 87 cl::desc("Produced object files can use all ELF features " 88 "supported by this binutils version and newer." 89 "If -no-integrated-as is specified, the generated " 90 "assembly will consider GNU as support." 91 "'none' means that all ELF features can be used, " 92 "regardless of binutils support")); 93 94 static cl::opt<bool> 95 NoIntegratedAssembler("no-integrated-as", cl::Hidden, 96 cl::desc("Disable integrated assembler")); 97 98 static cl::opt<bool> 99 PreserveComments("preserve-as-comments", cl::Hidden, 100 cl::desc("Preserve Comments in outputted assembly"), 101 cl::init(true)); 102 103 // Determine optimization level. 104 static cl::opt<char> 105 OptLevel("O", 106 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 107 "(default = '-O2')"), 108 cl::Prefix, 109 cl::ZeroOrMore, 110 cl::init(' ')); 111 112 static cl::opt<std::string> 113 TargetTriple("mtriple", cl::desc("Override target triple for module")); 114 115 static cl::opt<std::string> SplitDwarfFile( 116 "split-dwarf-file", 117 cl::desc( 118 "Specify the name of the .dwo file to encode in the DWARF output")); 119 120 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 121 cl::desc("Do not verify input module")); 122 123 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 124 cl::desc("Disable simplify-libcalls")); 125 126 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 127 cl::desc("Show encoding in .s output")); 128 129 static cl::opt<bool> EnableDwarfDirectory( 130 "enable-dwarf-directory", cl::Hidden, 131 cl::desc("Use .file directives with an explicit directory.")); 132 133 static cl::opt<bool> AsmVerbose("asm-verbose", 134 cl::desc("Add comments to directives."), 135 cl::init(true)); 136 137 static cl::opt<bool> 138 CompileTwice("compile-twice", cl::Hidden, 139 cl::desc("Run everything twice, re-using the same pass " 140 "manager and verify the result is the same."), 141 cl::init(false)); 142 143 static cl::opt<bool> DiscardValueNames( 144 "discard-value-names", 145 cl::desc("Discard names from Value (other than GlobalValue)."), 146 cl::init(false), cl::Hidden); 147 148 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path")); 149 150 static cl::opt<bool> RemarksWithHotness( 151 "pass-remarks-with-hotness", 152 cl::desc("With PGO, include profile count in optimization remarks"), 153 cl::Hidden); 154 155 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser> 156 RemarksHotnessThreshold( 157 "pass-remarks-hotness-threshold", 158 cl::desc("Minimum profile count required for " 159 "an optimization remark to be output. " 160 "Use 'auto' to apply the threshold from profile summary."), 161 cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden); 162 163 static cl::opt<std::string> 164 RemarksFilename("pass-remarks-output", 165 cl::desc("Output filename for pass remarks"), 166 cl::value_desc("filename")); 167 168 static cl::opt<std::string> 169 RemarksPasses("pass-remarks-filter", 170 cl::desc("Only record optimization remarks from passes whose " 171 "names match the given regular expression"), 172 cl::value_desc("regex")); 173 174 static cl::opt<std::string> RemarksFormat( 175 "pass-remarks-format", 176 cl::desc("The format used for serializing remarks (default: YAML)"), 177 cl::value_desc("format"), cl::init("yaml")); 178 179 namespace { 180 static ManagedStatic<std::vector<std::string>> RunPassNames; 181 182 struct RunPassOption { 183 void operator=(const std::string &Val) const { 184 if (Val.empty()) 185 return; 186 SmallVector<StringRef, 8> PassNames; 187 StringRef(Val).split(PassNames, ',', -1, false); 188 for (auto PassName : PassNames) 189 RunPassNames->push_back(std::string(PassName)); 190 } 191 }; 192 } 193 194 static RunPassOption RunPassOpt; 195 196 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass( 197 "run-pass", 198 cl::desc("Run compiler only for specified passes (comma separated list)"), 199 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt)); 200 201 static int compileModule(char **, LLVMContext &); 202 203 LLVM_ATTRIBUTE_NORETURN static void reportError(Twine Msg, 204 StringRef Filename = "") { 205 SmallString<256> Prefix; 206 if (!Filename.empty()) { 207 if (Filename == "-") 208 Filename = "<stdin>"; 209 ("'" + Twine(Filename) + "': ").toStringRef(Prefix); 210 } 211 WithColor::error(errs(), "llc") << Prefix << Msg << "\n"; 212 exit(1); 213 } 214 215 LLVM_ATTRIBUTE_NORETURN static void reportError(Error Err, StringRef Filename) { 216 assert(Err); 217 handleAllErrors(createFileError(Filename, std::move(Err)), 218 [&](const ErrorInfoBase &EI) { reportError(EI.message()); }); 219 llvm_unreachable("reportError() should not return"); 220 } 221 222 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName, 223 Triple::OSType OS, 224 const char *ProgName) { 225 // If we don't yet have an output filename, make one. 226 if (OutputFilename.empty()) { 227 if (InputFilename == "-") 228 OutputFilename = "-"; 229 else { 230 // If InputFilename ends in .bc or .ll, remove it. 231 StringRef IFN = InputFilename; 232 if (IFN.endswith(".bc") || IFN.endswith(".ll")) 233 OutputFilename = std::string(IFN.drop_back(3)); 234 else if (IFN.endswith(".mir")) 235 OutputFilename = std::string(IFN.drop_back(4)); 236 else 237 OutputFilename = std::string(IFN); 238 239 switch (codegen::getFileType()) { 240 case CGFT_AssemblyFile: 241 if (TargetName[0] == 'c') { 242 if (TargetName[1] == 0) 243 OutputFilename += ".cbe.c"; 244 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 245 OutputFilename += ".cpp"; 246 else 247 OutputFilename += ".s"; 248 } else 249 OutputFilename += ".s"; 250 break; 251 case CGFT_ObjectFile: 252 if (OS == Triple::Win32) 253 OutputFilename += ".obj"; 254 else 255 OutputFilename += ".o"; 256 break; 257 case CGFT_Null: 258 OutputFilename = "-"; 259 break; 260 } 261 } 262 } 263 264 // Decide if we need "binary" output. 265 bool Binary = false; 266 switch (codegen::getFileType()) { 267 case CGFT_AssemblyFile: 268 break; 269 case CGFT_ObjectFile: 270 case CGFT_Null: 271 Binary = true; 272 break; 273 } 274 275 // Open the file. 276 std::error_code EC; 277 sys::fs::OpenFlags OpenFlags = sys::fs::OF_None; 278 if (!Binary) 279 OpenFlags |= sys::fs::OF_Text; 280 auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags); 281 if (EC) { 282 reportError(EC.message()); 283 return nullptr; 284 } 285 286 return FDOut; 287 } 288 289 struct LLCDiagnosticHandler : public DiagnosticHandler { 290 bool *HasError; 291 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {} 292 bool handleDiagnostics(const DiagnosticInfo &DI) override { 293 if (DI.getSeverity() == DS_Error) 294 *HasError = true; 295 296 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 297 if (!Remark->isEnabled()) 298 return true; 299 300 DiagnosticPrinterRawOStream DP(errs()); 301 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 302 DI.print(DP); 303 errs() << "\n"; 304 return true; 305 } 306 }; 307 308 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context, 309 unsigned LocCookie) { 310 bool *HasError = static_cast<bool *>(Context); 311 if (SMD.getKind() == SourceMgr::DK_Error) 312 *HasError = true; 313 314 SMD.print(nullptr, errs()); 315 316 // For testing purposes, we print the LocCookie here. 317 if (LocCookie) 318 WithColor::note() << "!srcloc = " << LocCookie << "\n"; 319 } 320 321 // main - Entry point for the llc compiler. 322 // 323 int main(int argc, char **argv) { 324 InitLLVM X(argc, argv); 325 326 // Enable debug stream buffering. 327 EnableDebugBuffering = true; 328 329 LLVMContext Context; 330 331 // Initialize targets first, so that --version shows registered targets. 332 InitializeAllTargets(); 333 InitializeAllTargetMCs(); 334 InitializeAllAsmPrinters(); 335 InitializeAllAsmParsers(); 336 337 // Initialize codegen and IR passes used by llc so that the -print-after, 338 // -print-before, and -stop-after options work. 339 PassRegistry *Registry = PassRegistry::getPassRegistry(); 340 initializeCore(*Registry); 341 initializeCodeGen(*Registry); 342 initializeLoopStrengthReducePass(*Registry); 343 initializeLowerIntrinsicsPass(*Registry); 344 initializeEntryExitInstrumenterPass(*Registry); 345 initializePostInlineEntryExitInstrumenterPass(*Registry); 346 initializeUnreachableBlockElimLegacyPassPass(*Registry); 347 initializeConstantHoistingLegacyPassPass(*Registry); 348 initializeScalarOpts(*Registry); 349 initializeVectorization(*Registry); 350 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry); 351 initializeExpandReductionsPass(*Registry); 352 initializeHardwareLoopsPass(*Registry); 353 initializeTransformUtils(*Registry); 354 355 // Initialize debugging passes. 356 initializeScavengerTestPass(*Registry); 357 358 // Register the target printer for --version. 359 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 360 361 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 362 363 Context.setDiscardValueNames(DiscardValueNames); 364 365 // Set a diagnostic handler that doesn't exit on the first error 366 bool HasError = false; 367 Context.setDiagnosticHandler( 368 std::make_unique<LLCDiagnosticHandler>(&HasError)); 369 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError); 370 371 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 372 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 373 RemarksFormat, RemarksWithHotness, 374 RemarksHotnessThreshold); 375 if (Error E = RemarksFileOrErr.takeError()) 376 reportError(std::move(E), RemarksFilename); 377 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 378 379 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir") 380 reportError("input language must be '', 'IR' or 'MIR'"); 381 382 // Compile the module TimeCompilations times to give better compile time 383 // metrics. 384 for (unsigned I = TimeCompilations; I; --I) 385 if (int RetVal = compileModule(argv, Context)) 386 return RetVal; 387 388 if (RemarksFile) 389 RemarksFile->keep(); 390 return 0; 391 } 392 393 static bool addPass(PassManagerBase &PM, const char *argv0, 394 StringRef PassName, TargetPassConfig &TPC) { 395 if (PassName == "none") 396 return false; 397 398 const PassRegistry *PR = PassRegistry::getPassRegistry(); 399 const PassInfo *PI = PR->getPassInfo(PassName); 400 if (!PI) { 401 WithColor::error(errs(), argv0) 402 << "run-pass " << PassName << " is not registered.\n"; 403 return true; 404 } 405 406 Pass *P; 407 if (PI->getNormalCtor()) 408 P = PI->getNormalCtor()(); 409 else { 410 WithColor::error(errs(), argv0) 411 << "cannot create pass: " << PI->getPassName() << "\n"; 412 return true; 413 } 414 std::string Banner = std::string("After ") + std::string(P->getPassName()); 415 TPC.addMachinePrePasses(); 416 PM.add(P); 417 TPC.addMachinePostPasses(Banner); 418 419 return false; 420 } 421 422 static int compileModule(char **argv, LLVMContext &Context) { 423 // Load the module to be compiled... 424 SMDiagnostic Err; 425 std::unique_ptr<Module> M; 426 std::unique_ptr<MIRParser> MIR; 427 Triple TheTriple; 428 std::string CPUStr = codegen::getCPUStr(), 429 FeaturesStr = codegen::getFeaturesStr(); 430 431 // Set attributes on functions as loaded from MIR from command line arguments. 432 auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) { 433 codegen::setFunctionAttributes(CPUStr, FeaturesStr, F); 434 }; 435 436 auto MAttrs = codegen::getMAttrs(); 437 bool SkipModule = codegen::getMCPU() == "help" || 438 (!MAttrs.empty() && MAttrs.front() == "help"); 439 440 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 441 switch (OptLevel) { 442 default: 443 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n"; 444 return 1; 445 case ' ': break; 446 case '0': OLvl = CodeGenOpt::None; break; 447 case '1': OLvl = CodeGenOpt::Less; break; 448 case '2': OLvl = CodeGenOpt::Default; break; 449 case '3': OLvl = CodeGenOpt::Aggressive; break; 450 } 451 452 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we 453 // use that to indicate the MC default. 454 if (!BinutilsVersion.empty() && BinutilsVersion != "none") { 455 StringRef V = BinutilsVersion.getValue(); 456 unsigned Num; 457 if (V.consumeInteger(10, Num) || Num == 0 || 458 !(V.empty() || 459 (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) { 460 WithColor::error(errs(), argv[0]) 461 << "invalid -binutils-version, accepting 'none' or major.minor\n"; 462 return 1; 463 } 464 } 465 TargetOptions Options; 466 auto InitializeOptions = [&](const Triple &TheTriple) { 467 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple); 468 Options.BinutilsVersion = 469 TargetMachine::parseBinutilsVersion(BinutilsVersion); 470 Options.DisableIntegratedAS = NoIntegratedAssembler; 471 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 472 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 473 Options.MCOptions.AsmVerbose = AsmVerbose; 474 Options.MCOptions.PreserveAsmComments = PreserveComments; 475 Options.MCOptions.IASSearchPaths = IncludeDirs; 476 Options.MCOptions.SplitDwarfFile = SplitDwarfFile; 477 }; 478 479 Optional<Reloc::Model> RM = codegen::getExplicitRelocModel(); 480 481 const Target *TheTarget = nullptr; 482 std::unique_ptr<TargetMachine> Target; 483 484 // If user just wants to list available options, skip module loading 485 if (!SkipModule) { 486 auto SetDataLayout = 487 [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> { 488 // If we are supposed to override the target triple, do so now. 489 std::string IRTargetTriple = DataLayoutTargetTriple.str(); 490 if (!TargetTriple.empty()) 491 IRTargetTriple = Triple::normalize(TargetTriple); 492 TheTriple = Triple(IRTargetTriple); 493 if (TheTriple.getTriple().empty()) 494 TheTriple.setTriple(sys::getDefaultTargetTriple()); 495 496 std::string Error; 497 TheTarget = 498 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 499 if (!TheTarget) { 500 WithColor::error(errs(), argv[0]) << Error; 501 exit(1); 502 } 503 504 // On AIX, setting the relocation model to anything other than PIC is 505 // considered a user error. 506 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) 507 reportError("invalid relocation model, AIX only supports PIC", 508 InputFilename); 509 510 InitializeOptions(TheTriple); 511 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( 512 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, 513 codegen::getExplicitCodeModel(), OLvl)); 514 assert(Target && "Could not allocate target machine!"); 515 516 return Target->createDataLayout().getStringRepresentation(); 517 }; 518 if (InputLanguage == "mir" || 519 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) { 520 MIR = createMIRParserFromFile(InputFilename, Err, Context, 521 setMIRFunctionAttributes); 522 if (MIR) 523 M = MIR->parseIRModule(SetDataLayout); 524 } else { 525 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 526 } 527 if (!M) { 528 Err.print(argv[0], WithColor::error(errs(), argv[0])); 529 return 1; 530 } 531 if (!TargetTriple.empty()) 532 M->setTargetTriple(Triple::normalize(TargetTriple)); 533 } else { 534 TheTriple = Triple(Triple::normalize(TargetTriple)); 535 if (TheTriple.getTriple().empty()) 536 TheTriple.setTriple(sys::getDefaultTargetTriple()); 537 538 // Get the target specific parser. 539 std::string Error; 540 TheTarget = 541 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 542 if (!TheTarget) { 543 WithColor::error(errs(), argv[0]) << Error; 544 return 1; 545 } 546 547 // On AIX, setting the relocation model to anything other than PIC is 548 // considered a user error. 549 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) { 550 WithColor::error(errs(), argv[0]) 551 << "invalid relocation model, AIX only supports PIC.\n"; 552 return 1; 553 } 554 555 InitializeOptions(TheTriple); 556 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( 557 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, 558 codegen::getExplicitCodeModel(), OLvl)); 559 assert(Target && "Could not allocate target machine!"); 560 561 // If we don't have a module then just exit now. We do this down 562 // here since the CPU/Feature help is underneath the target machine 563 // creation. 564 return 0; 565 } 566 567 assert(M && "Should have exited if we didn't have a module!"); 568 if (codegen::getFloatABIForCalls() != FloatABI::Default) 569 Options.FloatABIType = codegen::getFloatABIForCalls(); 570 571 // Figure out where we are going to send the output. 572 std::unique_ptr<ToolOutputFile> Out = 573 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 574 if (!Out) return 1; 575 576 std::unique_ptr<ToolOutputFile> DwoOut; 577 if (!SplitDwarfOutputFile.empty()) { 578 std::error_code EC; 579 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC, 580 sys::fs::OF_None); 581 if (EC) 582 reportError(EC.message(), SplitDwarfOutputFile); 583 } 584 585 // Build up all of the passes that we want to do to the module. 586 legacy::PassManager PM; 587 588 // Add an appropriate TargetLibraryInfo pass for the module's triple. 589 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 590 591 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 592 if (DisableSimplifyLibCalls) 593 TLII.disableAllFunctions(); 594 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 595 596 // Verify module immediately to catch problems before doInitialization() is 597 // called on any passes. 598 if (!NoVerify && verifyModule(*M, &errs())) 599 reportError("input module cannot be verified", InputFilename); 600 601 // Override function attributes based on CPUStr, FeaturesStr, and command line 602 // flags. 603 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 604 605 if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile) 606 WithColor::warning(errs(), argv[0]) 607 << ": warning: ignoring -mc-relax-all because filetype != obj"; 608 609 { 610 raw_pwrite_stream *OS = &Out->os(); 611 612 // Manually do the buffering rather than using buffer_ostream, 613 // so we can memcmp the contents in CompileTwice mode 614 SmallVector<char, 0> Buffer; 615 std::unique_ptr<raw_svector_ostream> BOS; 616 if ((codegen::getFileType() != CGFT_AssemblyFile && 617 !Out->os().supportsSeeking()) || 618 CompileTwice) { 619 BOS = std::make_unique<raw_svector_ostream>(Buffer); 620 OS = BOS.get(); 621 } 622 623 const char *argv0 = argv[0]; 624 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target); 625 MachineModuleInfoWrapperPass *MMIWP = 626 new MachineModuleInfoWrapperPass(&LLVMTM); 627 628 // Construct a custom pass pipeline that starts after instruction 629 // selection. 630 if (!RunPassNames->empty()) { 631 if (!MIR) { 632 WithColor::warning(errs(), argv[0]) 633 << "run-pass is for .mir file only.\n"; 634 return 1; 635 } 636 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 637 if (TPC.hasLimitedCodeGenPipeline()) { 638 WithColor::warning(errs(), argv[0]) 639 << "run-pass cannot be used with " 640 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n"; 641 return 1; 642 } 643 644 TPC.setDisableVerify(NoVerify); 645 PM.add(&TPC); 646 PM.add(MMIWP); 647 TPC.printAndVerify(""); 648 for (const std::string &RunPassName : *RunPassNames) { 649 if (addPass(PM, argv0, RunPassName, TPC)) 650 return 1; 651 } 652 TPC.setInitialized(); 653 PM.add(createPrintMIRPass(*OS)); 654 PM.add(createFreeMachineFunctionPass()); 655 } else if (Target->addPassesToEmitFile( 656 PM, *OS, DwoOut ? &DwoOut->os() : nullptr, 657 codegen::getFileType(), NoVerify, MMIWP)) { 658 reportError("target does not support generation of this file type"); 659 } 660 661 const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering()) 662 ->Initialize(MMIWP->getMMI().getContext(), *Target); 663 if (MIR) { 664 assert(MMIWP && "Forgot to create MMIWP?"); 665 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI())) 666 return 1; 667 } 668 669 // Before executing passes, print the final values of the LLVM options. 670 cl::PrintOptionValues(); 671 672 // If requested, run the pass manager over the same module again, 673 // to catch any bugs due to persistent state in the passes. Note that 674 // opt has the same functionality, so it may be worth abstracting this out 675 // in the future. 676 SmallVector<char, 0> CompileTwiceBuffer; 677 if (CompileTwice) { 678 std::unique_ptr<Module> M2(llvm::CloneModule(*M)); 679 PM.run(*M2); 680 CompileTwiceBuffer = Buffer; 681 Buffer.clear(); 682 } 683 684 PM.run(*M); 685 686 auto HasError = 687 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError; 688 if (*HasError) 689 return 1; 690 691 // Compare the two outputs and make sure they're the same 692 if (CompileTwice) { 693 if (Buffer.size() != CompileTwiceBuffer.size() || 694 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 695 0)) { 696 errs() 697 << "Running the pass manager twice changed the output.\n" 698 "Writing the result of the second run to the specified output\n" 699 "To generate the one-run comparison binary, just run without\n" 700 "the compile-twice option\n"; 701 Out->os() << Buffer; 702 Out->keep(); 703 return 1; 704 } 705 } 706 707 if (BOS) { 708 Out->os() << Buffer; 709 } 710 } 711 712 // Declare success. 713 Out->keep(); 714 if (DwoOut) 715 DwoOut->keep(); 716 717 return 0; 718 } 719