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