[llvm-shlib] Fix the version naming style of libLLVM for Windows (#85710)
[llvm-project.git] / llvm / tools / llc / llc.cpp
blob3e2567c441df5ca23520263b9d5eda38f3f59e78
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.
13 //===----------------------------------------------------------------------===//
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;
63 static codegen::RegisterCodeGenFlags CGF;
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.
69 static cl::opt<std::string>
70 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
72 static cl::opt<std::string>
73 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
75 static cl::opt<std::string>
76 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
78 static cl::opt<std::string>
79 SplitDwarfOutputFile("split-dwarf-output",
80 cl::desc(".dwo output filename"),
81 cl::value_desc("filename"));
83 static cl::opt<unsigned>
84 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
85 cl::value_desc("N"),
86 cl::desc("Repeat compilation N times for timing"));
88 static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
90 static cl::opt<unsigned> TimeTraceGranularity(
91 "time-trace-granularity",
92 cl::desc(
93 "Minimum time granularity (in microseconds) traced by time profiler"),
94 cl::init(500), cl::Hidden);
96 static cl::opt<std::string>
97 TimeTraceFile("time-trace-file",
98 cl::desc("Specify time trace file destination"),
99 cl::value_desc("filename"));
101 static cl::opt<std::string>
102 BinutilsVersion("binutils-version", cl::Hidden,
103 cl::desc("Produced object files can use all ELF features "
104 "supported by this binutils version and newer."
105 "If -no-integrated-as is specified, the generated "
106 "assembly will consider GNU as support."
107 "'none' means that all ELF features can be used, "
108 "regardless of binutils support"));
110 static cl::opt<bool>
111 PreserveComments("preserve-as-comments", cl::Hidden,
112 cl::desc("Preserve Comments in outputted assembly"),
113 cl::init(true));
115 // Determine optimization level.
116 static cl::opt<char>
117 OptLevel("O",
118 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
119 "(default = '-O2')"),
120 cl::Prefix, cl::init('2'));
122 static cl::opt<std::string>
123 TargetTriple("mtriple", cl::desc("Override target triple for module"));
125 static cl::opt<std::string> SplitDwarfFile(
126 "split-dwarf-file",
127 cl::desc(
128 "Specify the name of the .dwo file to encode in the DWARF output"));
130 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
131 cl::desc("Do not verify input module"));
133 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
134 cl::desc("Disable simplify-libcalls"));
136 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
137 cl::desc("Show encoding in .s output"));
139 static cl::opt<bool>
140 DwarfDirectory("dwarf-directory", cl::Hidden,
141 cl::desc("Use .file directives with an explicit directory"),
142 cl::init(true));
144 static cl::opt<bool> AsmVerbose("asm-verbose",
145 cl::desc("Add comments to directives."),
146 cl::init(true));
148 static cl::opt<bool>
149 CompileTwice("compile-twice", cl::Hidden,
150 cl::desc("Run everything twice, re-using the same pass "
151 "manager and verify the result is the same."),
152 cl::init(false));
154 static cl::opt<bool> DiscardValueNames(
155 "discard-value-names",
156 cl::desc("Discard names from Value (other than GlobalValue)."),
157 cl::init(false), cl::Hidden);
159 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
161 static cl::opt<bool> RemarksWithHotness(
162 "pass-remarks-with-hotness",
163 cl::desc("With PGO, include profile count in optimization remarks"),
164 cl::Hidden);
166 static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
167 RemarksHotnessThreshold(
168 "pass-remarks-hotness-threshold",
169 cl::desc("Minimum profile count required for "
170 "an optimization remark to be output. "
171 "Use 'auto' to apply the threshold from profile summary."),
172 cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
174 static cl::opt<std::string>
175 RemarksFilename("pass-remarks-output",
176 cl::desc("Output filename for pass remarks"),
177 cl::value_desc("filename"));
179 static cl::opt<std::string>
180 RemarksPasses("pass-remarks-filter",
181 cl::desc("Only record optimization remarks from passes whose "
182 "names match the given regular expression"),
183 cl::value_desc("regex"));
185 static cl::opt<std::string> RemarksFormat(
186 "pass-remarks-format",
187 cl::desc("The format used for serializing remarks (default: YAML)"),
188 cl::value_desc("format"), cl::init("yaml"));
190 static cl::opt<bool> EnableNewPassManager(
191 "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(false));
193 // This flag specifies a textual description of the optimization pass pipeline
194 // to run over the module. This flag switches opt to use the new pass manager
195 // infrastructure, completely disabling all of the flags specific to the old
196 // pass management.
197 static cl::opt<std::string> PassPipeline(
198 "passes",
199 cl::desc(
200 "A textual description of the pass pipeline. To have analysis passes "
201 "available before a certain pass, add 'require<foo-analysis>'."));
202 static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),
203 cl::desc("Alias for -passes"));
205 static cl::opt<bool> TryUseNewDbgInfoFormat(
206 "try-experimental-debuginfo-iterators",
207 cl::desc("Enable debuginfo iterator positions, if they're built in"),
208 cl::init(false), cl::Hidden);
210 extern cl::opt<bool> UseNewDbgInfoFormat;
212 namespace {
214 std::vector<std::string> &getRunPassNames() {
215 static std::vector<std::string> RunPassNames;
216 return RunPassNames;
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(PassNames, ',', -1, false);
225 for (auto PassName : PassNames)
226 getRunPassNames().push_back(std::string(PassName));
229 } // namespace
231 static RunPassOption RunPassOpt;
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(RunPassOpt));
238 static int compileModule(char **, LLVMContext &);
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(Prefix);
247 WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
248 exit(1);
251 [[noreturn]] static void reportError(Error Err, StringRef Filename) {
252 assert(Err);
253 handleAllErrors(createFileError(Filename, std::move(Err)),
254 [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
255 llvm_unreachable("reportError() should not return");
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(".bc") || IFN.ends_with(".ll"))
269 OutputFilename = std::string(IFN.drop_back(3));
270 else if (IFN.ends_with(".mir"))
271 OutputFilename = std::string(IFN.drop_back(4));
272 else
273 OutputFilename = std::string(IFN);
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;
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;
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>(OutputFilename, EC, OpenFlags);
309 if (EC) {
310 reportError(EC.message());
311 return nullptr;
314 return FDOut;
317 // main - Entry point for the llc compiler.
319 int main(int argc, char **argv) {
320 InitLLVM X(argc, argv);
322 // Enable debug stream buffering.
323 EnableDebugBuffering = true;
325 // Initialize targets first, so that --version shows registered targets.
326 InitializeAllTargets();
327 InitializeAllTargetMCs();
328 InitializeAllAsmPrinters();
329 InitializeAllAsmParsers();
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 initializeUnreachableBlockElimLegacyPassPass(*Registry);
339 initializeConstantHoistingLegacyPassPass(*Registry);
340 initializeScalarOpts(*Registry);
341 initializeVectorization(*Registry);
342 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
343 initializeExpandReductionsPass(*Registry);
344 initializeExpandVectorPredicationPass(*Registry);
345 initializeHardwareLoopsLegacyPass(*Registry);
346 initializeTransformUtils(*Registry);
347 initializeReplaceWithVeclibLegacyPass(*Registry);
348 initializeTLSVariableHoistLegacyPassPass(*Registry);
350 // Initialize debugging passes.
351 initializeScavengerTestPass(*Registry);
353 // Register the Target and CPU printer for --version.
354 cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
355 // Register the target printer for --version.
356 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
358 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
360 if (!PassPipeline.empty() && !getRunPassNames().empty()) {
361 errs() << "The `llc -run-pass=...` syntax for the new pass manager is "
362 "not supported, please use `llc -passes=<pipeline>` (or the `-p` "
363 "alias for a more concise version).\n";
364 return 1;
367 // RemoveDIs debug-info transition: tests may request that we /try/ to use the
368 // new debug-info format, if it's built in.
369 #ifdef EXPERIMENTAL_DEBUGINFO_ITERATORS
370 if (TryUseNewDbgInfoFormat) {
371 // If LLVM was built with support for this, turn the new debug-info format
372 // on.
373 UseNewDbgInfoFormat = true;
375 #endif
376 (void)TryUseNewDbgInfoFormat;
378 if (TimeTrace)
379 timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
380 auto TimeTraceScopeExit = make_scope_exit([]() {
381 if (TimeTrace) {
382 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
383 handleAllErrors(std::move(E), [&](const StringError &SE) {
384 errs() << SE.getMessage() << "\n";
386 return;
388 timeTraceProfilerCleanup();
392 LLVMContext Context;
393 Context.setDiscardValueNames(DiscardValueNames);
395 // Set a diagnostic handler that doesn't exit on the first error
396 Context.setDiagnosticHandler(std::make_unique<LLCDiagnosticHandler>());
398 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
399 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
400 RemarksFormat, RemarksWithHotness,
401 RemarksHotnessThreshold);
402 if (Error E = RemarksFileOrErr.takeError())
403 reportError(std::move(E), RemarksFilename);
404 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
406 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
407 reportError("input language must be '', 'IR' or 'MIR'");
409 // Compile the module TimeCompilations times to give better compile time
410 // metrics.
411 for (unsigned I = TimeCompilations; I; --I)
412 if (int RetVal = compileModule(argv, Context))
413 return RetVal;
415 if (RemarksFile)
416 RemarksFile->keep();
417 return 0;
420 static bool addPass(PassManagerBase &PM, const char *argv0,
421 StringRef PassName, TargetPassConfig &TPC) {
422 if (PassName == "none")
423 return false;
425 const PassRegistry *PR = PassRegistry::getPassRegistry();
426 const PassInfo *PI = PR->getPassInfo(PassName);
427 if (!PI) {
428 WithColor::error(errs(), argv0)
429 << "run-pass " << PassName << " is not registered.\n";
430 return true;
433 Pass *P;
434 if (PI->getNormalCtor())
435 P = PI->getNormalCtor()();
436 else {
437 WithColor::error(errs(), argv0)
438 << "cannot create pass: " << PI->getPassName() << "\n";
439 return true;
441 std::string Banner = std::string("After ") + std::string(P->getPassName());
442 TPC.addMachinePrePasses();
443 PM.add(P);
444 TPC.addMachinePostPasses(Banner);
446 return false;
449 static int compileModule(char **argv, LLVMContext &Context) {
450 // Load the module to be compiled...
451 SMDiagnostic Err;
452 std::unique_ptr<Module> M;
453 std::unique_ptr<MIRParser> MIR;
454 Triple TheTriple;
455 std::string CPUStr = codegen::getCPUStr(),
456 FeaturesStr = codegen::getFeaturesStr();
458 // Set attributes on functions as loaded from MIR from command line arguments.
459 auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
460 codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
463 auto MAttrs = codegen::getMAttrs();
464 bool SkipModule =
465 CPUStr == "help" || (!MAttrs.empty() && MAttrs.front() == "help");
467 CodeGenOptLevel OLvl;
468 if (auto Level = CodeGenOpt::parseLevel(OptLevel)) {
469 OLvl = *Level;
470 } else {
471 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
472 return 1;
475 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
476 // use that to indicate the MC default.
477 if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
478 StringRef V = BinutilsVersion.getValue();
479 unsigned Num;
480 if (V.consumeInteger(10, Num) || Num == 0 ||
481 !(V.empty() ||
482 (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
483 WithColor::error(errs(), argv[0])
484 << "invalid -binutils-version, accepting 'none' or major.minor\n";
485 return 1;
488 TargetOptions Options;
489 auto InitializeOptions = [&](const Triple &TheTriple) {
490 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
492 if (Options.XCOFFReadOnlyPointers) {
493 if (!TheTriple.isOSAIX())
494 reportError("-mxcoff-roptr option is only supported on AIX",
495 InputFilename);
497 // Since the storage mapping class is specified per csect,
498 // without using data sections, it is less effective to use read-only
499 // pointers. Using read-only pointers may cause other RO variables in the
500 // same csect to become RW when the linker acts upon `-bforceimprw`;
501 // therefore, we require that separate data sections are used in the
502 // presence of ReadOnlyPointers. We respect the setting of data-sections
503 // since we have not found reasons to do otherwise that overcome the user
504 // surprise of not respecting the setting.
505 if (!Options.DataSections)
506 reportError("-mxcoff-roptr option must be used with -data-sections",
507 InputFilename);
510 Options.BinutilsVersion =
511 TargetMachine::parseBinutilsVersion(BinutilsVersion);
512 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
513 Options.MCOptions.AsmVerbose = AsmVerbose;
514 Options.MCOptions.PreserveAsmComments = PreserveComments;
515 Options.MCOptions.IASSearchPaths = IncludeDirs;
516 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
517 if (DwarfDirectory.getPosition()) {
518 Options.MCOptions.MCUseDwarfDirectory =
519 DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
520 : MCTargetOptions::DisableDwarfDirectory;
521 } else {
522 // -dwarf-directory is not set explicitly. Some assemblers
523 // (e.g. GNU as or ptxas) do not support `.file directory'
524 // syntax prior to DWARFv5. Let the target decide the default
525 // value.
526 Options.MCOptions.MCUseDwarfDirectory =
527 MCTargetOptions::DefaultDwarfDirectory;
531 std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
532 std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
534 const Target *TheTarget = nullptr;
535 std::unique_ptr<TargetMachine> Target;
537 // If user just wants to list available options, skip module loading
538 if (!SkipModule) {
539 auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,
540 StringRef OldDLStr) -> std::optional<std::string> {
541 // If we are supposed to override the target triple, do so now.
542 std::string IRTargetTriple = DataLayoutTargetTriple.str();
543 if (!TargetTriple.empty())
544 IRTargetTriple = Triple::normalize(TargetTriple);
545 TheTriple = Triple(IRTargetTriple);
546 if (TheTriple.getTriple().empty())
547 TheTriple.setTriple(sys::getDefaultTargetTriple());
549 std::string Error;
550 TheTarget =
551 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
552 if (!TheTarget) {
553 WithColor::error(errs(), argv[0]) << Error;
554 exit(1);
557 InitializeOptions(TheTriple);
558 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
559 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
560 assert(Target && "Could not allocate target machine!");
562 return Target->createDataLayout().getStringRepresentation();
564 if (InputLanguage == "mir" ||
565 (InputLanguage == "" && StringRef(InputFilename).ends_with(".mir"))) {
566 MIR = createMIRParserFromFile(InputFilename, Err, Context,
567 setMIRFunctionAttributes);
568 if (MIR)
569 M = MIR->parseIRModule(SetDataLayout);
570 } else {
571 M = parseIRFile(InputFilename, Err, Context,
572 ParserCallbacks(SetDataLayout));
574 if (!M) {
575 Err.print(argv[0], WithColor::error(errs(), argv[0]));
576 return 1;
578 if (!TargetTriple.empty())
579 M->setTargetTriple(Triple::normalize(TargetTriple));
581 std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
582 if (!CM && CM_IR)
583 Target->setCodeModel(*CM_IR);
584 if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
585 Target->setLargeDataThreshold(*LDT);
586 } else {
587 TheTriple = Triple(Triple::normalize(TargetTriple));
588 if (TheTriple.getTriple().empty())
589 TheTriple.setTriple(sys::getDefaultTargetTriple());
591 // Get the target specific parser.
592 std::string Error;
593 TheTarget =
594 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
595 if (!TheTarget) {
596 WithColor::error(errs(), argv[0]) << Error;
597 return 1;
600 InitializeOptions(TheTriple);
601 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
602 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
603 assert(Target && "Could not allocate target machine!");
605 // If we don't have a module then just exit now. We do this down
606 // here since the CPU/Feature help is underneath the target machine
607 // creation.
608 return 0;
611 assert(M && "Should have exited if we didn't have a module!");
612 if (codegen::getFloatABIForCalls() != FloatABI::Default)
613 Target->Options.FloatABIType = codegen::getFloatABIForCalls();
615 // Figure out where we are going to send the output.
616 std::unique_ptr<ToolOutputFile> Out =
617 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
618 if (!Out) return 1;
620 // Ensure the filename is passed down to CodeViewDebug.
621 Target->Options.ObjectFilenameForDebug = Out->outputFilename();
623 std::unique_ptr<ToolOutputFile> DwoOut;
624 if (!SplitDwarfOutputFile.empty()) {
625 std::error_code EC;
626 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
627 sys::fs::OF_None);
628 if (EC)
629 reportError(EC.message(), SplitDwarfOutputFile);
632 // Add an appropriate TargetLibraryInfo pass for the module's triple.
633 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
635 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
636 if (DisableSimplifyLibCalls)
637 TLII.disableAllFunctions();
639 // Verify module immediately to catch problems before doInitialization() is
640 // called on any passes.
641 if (!NoVerify && verifyModule(*M, &errs()))
642 reportError("input module cannot be verified", InputFilename);
644 // Override function attributes based on CPUStr, FeaturesStr, and command line
645 // flags.
646 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
648 if (mc::getExplicitRelaxAll() &&
649 codegen::getFileType() != CodeGenFileType::ObjectFile)
650 WithColor::warning(errs(), argv[0])
651 << ": warning: ignoring -mc-relax-all because filetype != obj";
653 if (EnableNewPassManager || !PassPipeline.empty()) {
654 return compileModuleWithNewPM(argv[0], std::move(M), std::move(MIR),
655 std::move(Target), std::move(Out),
656 std::move(DwoOut), Context, TLII, NoVerify,
657 PassPipeline, codegen::getFileType());
660 // Build up all of the passes that we want to do to the module.
661 legacy::PassManager PM;
662 PM.add(new TargetLibraryInfoWrapperPass(TLII));
665 raw_pwrite_stream *OS = &Out->os();
667 // Manually do the buffering rather than using buffer_ostream,
668 // so we can memcmp the contents in CompileTwice mode
669 SmallVector<char, 0> Buffer;
670 std::unique_ptr<raw_svector_ostream> BOS;
671 if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
672 !Out->os().supportsSeeking()) ||
673 CompileTwice) {
674 BOS = std::make_unique<raw_svector_ostream>(Buffer);
675 OS = BOS.get();
678 const char *argv0 = argv[0];
679 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
680 MachineModuleInfoWrapperPass *MMIWP =
681 new MachineModuleInfoWrapperPass(&LLVMTM);
683 // Construct a custom pass pipeline that starts after instruction
684 // selection.
685 if (!getRunPassNames().empty()) {
686 if (!MIR) {
687 WithColor::warning(errs(), argv[0])
688 << "run-pass is for .mir file only.\n";
689 delete MMIWP;
690 return 1;
692 TargetPassConfig *PTPC = LLVMTM.createPassConfig(PM);
693 TargetPassConfig &TPC = *PTPC;
694 if (TPC.hasLimitedCodeGenPipeline()) {
695 WithColor::warning(errs(), argv[0])
696 << "run-pass cannot be used with "
697 << TPC.getLimitedCodeGenPipelineReason() << ".\n";
698 delete PTPC;
699 delete MMIWP;
700 return 1;
703 TPC.setDisableVerify(NoVerify);
704 PM.add(&TPC);
705 PM.add(MMIWP);
706 TPC.printAndVerify("");
707 for (const std::string &RunPassName : getRunPassNames()) {
708 if (addPass(PM, argv0, RunPassName, TPC))
709 return 1;
711 TPC.setInitialized();
712 PM.add(createPrintMIRPass(*OS));
713 PM.add(createFreeMachineFunctionPass());
714 } else if (Target->addPassesToEmitFile(
715 PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
716 codegen::getFileType(), NoVerify, MMIWP)) {
717 reportError("target does not support generation of this file type");
720 const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
721 ->Initialize(MMIWP->getMMI().getContext(), *Target);
722 if (MIR) {
723 assert(MMIWP && "Forgot to create MMIWP?");
724 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
725 return 1;
728 // Before executing passes, print the final values of the LLVM options.
729 cl::PrintOptionValues();
731 // If requested, run the pass manager over the same module again,
732 // to catch any bugs due to persistent state in the passes. Note that
733 // opt has the same functionality, so it may be worth abstracting this out
734 // in the future.
735 SmallVector<char, 0> CompileTwiceBuffer;
736 if (CompileTwice) {
737 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
738 PM.run(*M2);
739 CompileTwiceBuffer = Buffer;
740 Buffer.clear();
743 PM.run(*M);
745 if (Context.getDiagHandlerPtr()->HasErrors)
746 return 1;
748 // Compare the two outputs and make sure they're the same
749 if (CompileTwice) {
750 if (Buffer.size() != CompileTwiceBuffer.size() ||
751 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
752 0)) {
753 errs()
754 << "Running the pass manager twice changed the output.\n"
755 "Writing the result of the second run to the specified output\n"
756 "To generate the one-run comparison binary, just run without\n"
757 "the compile-twice option\n";
758 Out->os() << Buffer;
759 Out->keep();
760 return 1;
764 if (BOS) {
765 Out->os() << Buffer;
769 // Declare success.
770 Out->keep();
771 if (DwoOut)
772 DwoOut->keep();
774 return 0;