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.getKind() == llvm::DK_SrcMgr) { 294 const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI); 295 const SMDiagnostic &SMD = DISM.getSMDiag(); 296 297 if (SMD.getKind() == SourceMgr::DK_Error) 298 *HasError = true; 299 300 SMD.print(nullptr, errs()); 301 302 // For testing purposes, we print the LocCookie here. 303 if (DISM.isInlineAsmDiag() && DISM.getLocCookie()) 304 WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n"; 305 306 return true; 307 } 308 309 if (DI.getSeverity() == DS_Error) 310 *HasError = true; 311 312 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 313 if (!Remark->isEnabled()) 314 return true; 315 316 DiagnosticPrinterRawOStream DP(errs()); 317 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 318 DI.print(DP); 319 errs() << "\n"; 320 return true; 321 } 322 }; 323 324 // main - Entry point for the llc compiler. 325 // 326 int main(int argc, char **argv) { 327 InitLLVM X(argc, argv); 328 329 // Enable debug stream buffering. 330 EnableDebugBuffering = true; 331 332 LLVMContext Context; 333 334 // Initialize targets first, so that --version shows registered targets. 335 InitializeAllTargets(); 336 InitializeAllTargetMCs(); 337 InitializeAllAsmPrinters(); 338 InitializeAllAsmParsers(); 339 340 // Initialize codegen and IR passes used by llc so that the -print-after, 341 // -print-before, and -stop-after options work. 342 PassRegistry *Registry = PassRegistry::getPassRegistry(); 343 initializeCore(*Registry); 344 initializeCodeGen(*Registry); 345 initializeLoopStrengthReducePass(*Registry); 346 initializeLowerIntrinsicsPass(*Registry); 347 initializeEntryExitInstrumenterPass(*Registry); 348 initializePostInlineEntryExitInstrumenterPass(*Registry); 349 initializeUnreachableBlockElimLegacyPassPass(*Registry); 350 initializeConstantHoistingLegacyPassPass(*Registry); 351 initializeScalarOpts(*Registry); 352 initializeVectorization(*Registry); 353 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry); 354 initializeExpandReductionsPass(*Registry); 355 initializeHardwareLoopsPass(*Registry); 356 initializeTransformUtils(*Registry); 357 initializeReplaceWithVeclibLegacyPass(*Registry); 358 359 // Initialize debugging passes. 360 initializeScavengerTestPass(*Registry); 361 362 // Register the target printer for --version. 363 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 364 365 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 366 367 Context.setDiscardValueNames(DiscardValueNames); 368 369 // Set a diagnostic handler that doesn't exit on the first error 370 bool HasError = false; 371 Context.setDiagnosticHandler( 372 std::make_unique<LLCDiagnosticHandler>(&HasError)); 373 374 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 375 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 376 RemarksFormat, RemarksWithHotness, 377 RemarksHotnessThreshold); 378 if (Error E = RemarksFileOrErr.takeError()) 379 reportError(std::move(E), RemarksFilename); 380 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 381 382 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir") 383 reportError("input language must be '', 'IR' or 'MIR'"); 384 385 // Compile the module TimeCompilations times to give better compile time 386 // metrics. 387 for (unsigned I = TimeCompilations; I; --I) 388 if (int RetVal = compileModule(argv, Context)) 389 return RetVal; 390 391 if (RemarksFile) 392 RemarksFile->keep(); 393 return 0; 394 } 395 396 static bool addPass(PassManagerBase &PM, const char *argv0, 397 StringRef PassName, TargetPassConfig &TPC) { 398 if (PassName == "none") 399 return false; 400 401 const PassRegistry *PR = PassRegistry::getPassRegistry(); 402 const PassInfo *PI = PR->getPassInfo(PassName); 403 if (!PI) { 404 WithColor::error(errs(), argv0) 405 << "run-pass " << PassName << " is not registered.\n"; 406 return true; 407 } 408 409 Pass *P; 410 if (PI->getNormalCtor()) 411 P = PI->getNormalCtor()(); 412 else { 413 WithColor::error(errs(), argv0) 414 << "cannot create pass: " << PI->getPassName() << "\n"; 415 return true; 416 } 417 std::string Banner = std::string("After ") + std::string(P->getPassName()); 418 TPC.addMachinePrePasses(); 419 PM.add(P); 420 TPC.addMachinePostPasses(Banner); 421 422 return false; 423 } 424 425 static int compileModule(char **argv, LLVMContext &Context) { 426 // Load the module to be compiled... 427 SMDiagnostic Err; 428 std::unique_ptr<Module> M; 429 std::unique_ptr<MIRParser> MIR; 430 Triple TheTriple; 431 std::string CPUStr = codegen::getCPUStr(), 432 FeaturesStr = codegen::getFeaturesStr(); 433 434 // Set attributes on functions as loaded from MIR from command line arguments. 435 auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) { 436 codegen::setFunctionAttributes(CPUStr, FeaturesStr, F); 437 }; 438 439 auto MAttrs = codegen::getMAttrs(); 440 bool SkipModule = codegen::getMCPU() == "help" || 441 (!MAttrs.empty() && MAttrs.front() == "help"); 442 443 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 444 switch (OptLevel) { 445 default: 446 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n"; 447 return 1; 448 case ' ': break; 449 case '0': OLvl = CodeGenOpt::None; break; 450 case '1': OLvl = CodeGenOpt::Less; break; 451 case '2': OLvl = CodeGenOpt::Default; break; 452 case '3': OLvl = CodeGenOpt::Aggressive; break; 453 } 454 455 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we 456 // use that to indicate the MC default. 457 if (!BinutilsVersion.empty() && BinutilsVersion != "none") { 458 StringRef V = BinutilsVersion.getValue(); 459 unsigned Num; 460 if (V.consumeInteger(10, Num) || Num == 0 || 461 !(V.empty() || 462 (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) { 463 WithColor::error(errs(), argv[0]) 464 << "invalid -binutils-version, accepting 'none' or major.minor\n"; 465 return 1; 466 } 467 } 468 TargetOptions Options; 469 auto InitializeOptions = [&](const Triple &TheTriple) { 470 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple); 471 Options.BinutilsVersion = 472 TargetMachine::parseBinutilsVersion(BinutilsVersion); 473 Options.DisableIntegratedAS = NoIntegratedAssembler; 474 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 475 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 476 Options.MCOptions.AsmVerbose = AsmVerbose; 477 Options.MCOptions.PreserveAsmComments = PreserveComments; 478 Options.MCOptions.IASSearchPaths = IncludeDirs; 479 Options.MCOptions.SplitDwarfFile = SplitDwarfFile; 480 }; 481 482 Optional<Reloc::Model> RM = codegen::getExplicitRelocModel(); 483 484 const Target *TheTarget = nullptr; 485 std::unique_ptr<TargetMachine> Target; 486 487 // If user just wants to list available options, skip module loading 488 if (!SkipModule) { 489 auto SetDataLayout = 490 [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> { 491 // If we are supposed to override the target triple, do so now. 492 std::string IRTargetTriple = DataLayoutTargetTriple.str(); 493 if (!TargetTriple.empty()) 494 IRTargetTriple = Triple::normalize(TargetTriple); 495 TheTriple = Triple(IRTargetTriple); 496 if (TheTriple.getTriple().empty()) 497 TheTriple.setTriple(sys::getDefaultTargetTriple()); 498 499 std::string Error; 500 TheTarget = 501 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 502 if (!TheTarget) { 503 WithColor::error(errs(), argv[0]) << Error; 504 exit(1); 505 } 506 507 // On AIX, setting the relocation model to anything other than PIC is 508 // considered a user error. 509 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) 510 reportError("invalid relocation model, AIX only supports PIC", 511 InputFilename); 512 513 InitializeOptions(TheTriple); 514 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( 515 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, 516 codegen::getExplicitCodeModel(), OLvl)); 517 assert(Target && "Could not allocate target machine!"); 518 519 return Target->createDataLayout().getStringRepresentation(); 520 }; 521 if (InputLanguage == "mir" || 522 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) { 523 MIR = createMIRParserFromFile(InputFilename, Err, Context, 524 setMIRFunctionAttributes); 525 if (MIR) 526 M = MIR->parseIRModule(SetDataLayout); 527 } else { 528 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 529 } 530 if (!M) { 531 Err.print(argv[0], WithColor::error(errs(), argv[0])); 532 return 1; 533 } 534 if (!TargetTriple.empty()) 535 M->setTargetTriple(Triple::normalize(TargetTriple)); 536 } else { 537 TheTriple = Triple(Triple::normalize(TargetTriple)); 538 if (TheTriple.getTriple().empty()) 539 TheTriple.setTriple(sys::getDefaultTargetTriple()); 540 541 // Get the target specific parser. 542 std::string Error; 543 TheTarget = 544 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 545 if (!TheTarget) { 546 WithColor::error(errs(), argv[0]) << Error; 547 return 1; 548 } 549 550 // On AIX, setting the relocation model to anything other than PIC is 551 // considered a user error. 552 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) { 553 WithColor::error(errs(), argv[0]) 554 << "invalid relocation model, AIX only supports PIC.\n"; 555 return 1; 556 } 557 558 InitializeOptions(TheTriple); 559 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( 560 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, 561 codegen::getExplicitCodeModel(), OLvl)); 562 assert(Target && "Could not allocate target machine!"); 563 564 // If we don't have a module then just exit now. We do this down 565 // here since the CPU/Feature help is underneath the target machine 566 // creation. 567 return 0; 568 } 569 570 assert(M && "Should have exited if we didn't have a module!"); 571 if (codegen::getFloatABIForCalls() != FloatABI::Default) 572 Options.FloatABIType = codegen::getFloatABIForCalls(); 573 574 // Figure out where we are going to send the output. 575 std::unique_ptr<ToolOutputFile> Out = 576 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 577 if (!Out) return 1; 578 579 std::unique_ptr<ToolOutputFile> DwoOut; 580 if (!SplitDwarfOutputFile.empty()) { 581 std::error_code EC; 582 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC, 583 sys::fs::OF_None); 584 if (EC) 585 reportError(EC.message(), SplitDwarfOutputFile); 586 } 587 588 // Build up all of the passes that we want to do to the module. 589 legacy::PassManager PM; 590 591 // Add an appropriate TargetLibraryInfo pass for the module's triple. 592 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 593 594 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 595 if (DisableSimplifyLibCalls) 596 TLII.disableAllFunctions(); 597 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 598 599 // Verify module immediately to catch problems before doInitialization() is 600 // called on any passes. 601 if (!NoVerify && verifyModule(*M, &errs())) 602 reportError("input module cannot be verified", InputFilename); 603 604 // Override function attributes based on CPUStr, FeaturesStr, and command line 605 // flags. 606 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 607 608 if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile) 609 WithColor::warning(errs(), argv[0]) 610 << ": warning: ignoring -mc-relax-all because filetype != obj"; 611 612 { 613 raw_pwrite_stream *OS = &Out->os(); 614 615 // Manually do the buffering rather than using buffer_ostream, 616 // so we can memcmp the contents in CompileTwice mode 617 SmallVector<char, 0> Buffer; 618 std::unique_ptr<raw_svector_ostream> BOS; 619 if ((codegen::getFileType() != CGFT_AssemblyFile && 620 !Out->os().supportsSeeking()) || 621 CompileTwice) { 622 BOS = std::make_unique<raw_svector_ostream>(Buffer); 623 OS = BOS.get(); 624 } 625 626 const char *argv0 = argv[0]; 627 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target); 628 MachineModuleInfoWrapperPass *MMIWP = 629 new MachineModuleInfoWrapperPass(&LLVMTM); 630 631 // Construct a custom pass pipeline that starts after instruction 632 // selection. 633 if (!RunPassNames->empty()) { 634 if (!MIR) { 635 WithColor::warning(errs(), argv[0]) 636 << "run-pass is for .mir file only.\n"; 637 return 1; 638 } 639 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 640 if (TPC.hasLimitedCodeGenPipeline()) { 641 WithColor::warning(errs(), argv[0]) 642 << "run-pass cannot be used with " 643 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n"; 644 return 1; 645 } 646 647 TPC.setDisableVerify(NoVerify); 648 PM.add(&TPC); 649 PM.add(MMIWP); 650 TPC.printAndVerify(""); 651 for (const std::string &RunPassName : *RunPassNames) { 652 if (addPass(PM, argv0, RunPassName, TPC)) 653 return 1; 654 } 655 TPC.setInitialized(); 656 PM.add(createPrintMIRPass(*OS)); 657 PM.add(createFreeMachineFunctionPass()); 658 } else if (Target->addPassesToEmitFile( 659 PM, *OS, DwoOut ? &DwoOut->os() : nullptr, 660 codegen::getFileType(), NoVerify, MMIWP)) { 661 reportError("target does not support generation of this file type"); 662 } 663 664 const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering()) 665 ->Initialize(MMIWP->getMMI().getContext(), *Target); 666 if (MIR) { 667 assert(MMIWP && "Forgot to create MMIWP?"); 668 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI())) 669 return 1; 670 } 671 672 // Before executing passes, print the final values of the LLVM options. 673 cl::PrintOptionValues(); 674 675 // If requested, run the pass manager over the same module again, 676 // to catch any bugs due to persistent state in the passes. Note that 677 // opt has the same functionality, so it may be worth abstracting this out 678 // in the future. 679 SmallVector<char, 0> CompileTwiceBuffer; 680 if (CompileTwice) { 681 std::unique_ptr<Module> M2(llvm::CloneModule(*M)); 682 PM.run(*M2); 683 CompileTwiceBuffer = Buffer; 684 Buffer.clear(); 685 } 686 687 PM.run(*M); 688 689 auto HasError = 690 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError; 691 if (*HasError) 692 return 1; 693 694 // Compare the two outputs and make sure they're the same 695 if (CompileTwice) { 696 if (Buffer.size() != CompileTwiceBuffer.size() || 697 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 698 0)) { 699 errs() 700 << "Running the pass manager twice changed the output.\n" 701 "Writing the result of the second run to the specified output\n" 702 "To generate the one-run comparison binary, just run without\n" 703 "the compile-twice option\n"; 704 Out->os() << Buffer; 705 Out->keep(); 706 return 1; 707 } 708 } 709 710 if (BOS) { 711 Out->os() << Buffer; 712 } 713 } 714 715 // Declare success. 716 Out->keep(); 717 if (DwoOut) 718 DwoOut->keep(); 719 720 return 0; 721 } 722