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