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