1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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
7 //===----------------------------------------------------------------------===//
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"
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),
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",
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"));
111 PreserveComments("preserve-as-comments", cl::Hidden
,
112 cl::desc("Preserve Comments in outputted assembly"),
115 // Determine optimization level.
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(
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"));
140 DwarfDirectory("dwarf-directory", cl::Hidden
,
141 cl::desc("Use .file directives with an explicit directory"),
144 static cl::opt
<bool> AsmVerbose("asm-verbose",
145 cl::desc("Add comments to directives."),
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."),
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"),
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
197 static cl::opt
<std::string
> PassPipeline(
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
;
214 std::vector
<std::string
> &getRunPassNames() {
215 static std::vector
<std::string
> RunPassNames
;
219 struct RunPassOption
{
220 void operator=(const std::string
&Val
) const {
223 SmallVector
<StringRef
, 8> PassNames
;
224 StringRef(Val
).split(PassNames
, ',', -1, false);
225 for (auto PassName
: PassNames
)
226 getRunPassNames().push_back(std::string(PassName
));
231 static RunPassOption RunPassOpt
;
233 static cl::opt
<RunPassOption
, true, cl::parser
<std::string
>> RunPass(
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()) {
244 Filename
= "<stdin>";
245 ("'" + Twine(Filename
) + "': ").toStringRef(Prefix
);
247 WithColor::error(errs(), "llc") << Prefix
<< Msg
<< "\n";
251 [[noreturn
]] static void reportError(Error Err
, StringRef Filename
) {
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
,
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
= "-";
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));
273 OutputFilename
= std::string(IFN
);
275 switch (codegen::getFileType()) {
276 case CodeGenFileType::AssemblyFile
:
277 OutputFilename
+= ".s";
279 case CodeGenFileType::ObjectFile
:
280 if (OS
== Triple::Win32
)
281 OutputFilename
+= ".obj";
283 OutputFilename
+= ".o";
285 case CodeGenFileType::Null
:
286 OutputFilename
= "-";
292 // Decide if we need "binary" output.
294 switch (codegen::getFileType()) {
295 case CodeGenFileType::AssemblyFile
:
297 case CodeGenFileType::ObjectFile
:
298 case CodeGenFileType::Null
:
305 sys::fs::OpenFlags OpenFlags
= sys::fs::OF_None
;
307 OpenFlags
|= sys::fs::OF_TextWithCRLF
;
308 auto FDOut
= std::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, OpenFlags
);
310 reportError(EC
.message());
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";
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
373 UseNewDbgInfoFormat
= true;
376 (void)TryUseNewDbgInfoFormat
;
379 timeTraceProfilerInitialize(TimeTraceGranularity
, argv
[0]);
380 auto TimeTraceScopeExit
= make_scope_exit([]() {
382 if (auto E
= timeTraceProfilerWrite(TimeTraceFile
, OutputFilename
)) {
383 handleAllErrors(std::move(E
), [&](const StringError
&SE
) {
384 errs() << SE
.getMessage() << "\n";
388 timeTraceProfilerCleanup();
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
411 for (unsigned I
= TimeCompilations
; I
; --I
)
412 if (int RetVal
= compileModule(argv
, Context
))
420 static bool addPass(PassManagerBase
&PM
, const char *argv0
,
421 StringRef PassName
, TargetPassConfig
&TPC
) {
422 if (PassName
== "none")
425 const PassRegistry
*PR
= PassRegistry::getPassRegistry();
426 const PassInfo
*PI
= PR
->getPassInfo(PassName
);
428 WithColor::error(errs(), argv0
)
429 << "run-pass " << PassName
<< " is not registered.\n";
434 if (PI
->getNormalCtor())
435 P
= PI
->getNormalCtor()();
437 WithColor::error(errs(), argv0
)
438 << "cannot create pass: " << PI
->getPassName() << "\n";
441 std::string Banner
= std::string("After ") + std::string(P
->getPassName());
442 TPC
.addMachinePrePasses();
444 TPC
.addMachinePostPasses(Banner
);
449 static int compileModule(char **argv
, LLVMContext
&Context
) {
450 // Load the module to be compiled...
452 std::unique_ptr
<Module
> M
;
453 std::unique_ptr
<MIRParser
> MIR
;
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();
465 CPUStr
== "help" || (!MAttrs
.empty() && MAttrs
.front() == "help");
467 CodeGenOptLevel OLvl
;
468 if (auto Level
= CodeGenOpt::parseLevel(OptLevel
)) {
471 WithColor::error(errs(), argv
[0]) << "invalid optimization level.\n";
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();
480 if (V
.consumeInteger(10, Num
) || Num
== 0 ||
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";
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",
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",
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
;
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
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
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());
551 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple
, Error
);
553 WithColor::error(errs(), argv
[0]) << Error
;
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
);
569 M
= MIR
->parseIRModule(SetDataLayout
);
571 M
= parseIRFile(InputFilename
, Err
, Context
,
572 ParserCallbacks(SetDataLayout
));
575 Err
.print(argv
[0], WithColor::error(errs(), argv
[0]));
578 if (!TargetTriple
.empty())
579 M
->setTargetTriple(Triple::normalize(TargetTriple
));
581 std::optional
<CodeModel::Model
> CM_IR
= M
->getCodeModel();
583 Target
->setCodeModel(*CM_IR
);
584 if (std::optional
<uint64_t> LDT
= codegen::getExplicitLargeDataThreshold())
585 Target
->setLargeDataThreshold(*LDT
);
587 TheTriple
= Triple(Triple::normalize(TargetTriple
));
588 if (TheTriple
.getTriple().empty())
589 TheTriple
.setTriple(sys::getDefaultTargetTriple());
591 // Get the target specific parser.
594 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple
, Error
);
596 WithColor::error(errs(), argv
[0]) << Error
;
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
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]);
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()) {
626 DwoOut
= std::make_unique
<ToolOutputFile
>(SplitDwarfOutputFile
, 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
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()) ||
674 BOS
= std::make_unique
<raw_svector_ostream
>(Buffer
);
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
685 if (!getRunPassNames().empty()) {
687 WithColor::warning(errs(), argv
[0])
688 << "run-pass is for .mir file only.\n";
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";
703 TPC
.setDisableVerify(NoVerify
);
706 TPC
.printAndVerify("");
707 for (const std::string
&RunPassName
: getRunPassNames()) {
708 if (addPass(PM
, argv0
, RunPassName
, TPC
))
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
);
723 assert(MMIWP
&& "Forgot to create MMIWP?");
724 if (MIR
->parseMachineFunctions(*M
, MMIWP
->getMMI()))
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
735 SmallVector
<char, 0> CompileTwiceBuffer
;
737 std::unique_ptr
<Module
> M2(llvm::CloneModule(*M
));
739 CompileTwiceBuffer
= Buffer
;
745 if (Context
.getDiagHandlerPtr()->HasErrors
)
748 // Compare the two outputs and make sure they're the same
750 if (Buffer
.size() != CompileTwiceBuffer
.size() ||
751 (memcmp(Buffer
.data(), CompileTwiceBuffer
.data(), Buffer
.size()) !=
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";