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 native assembly-language code
11 // or C code, given LLVM bitcode.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/CodeGen/CommandFlags.inc"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/CodeGen/MIRParser/MIRParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/InitLLVM.h"
44 #include "llvm/Support/ManagedStatic.h"
45 #include "llvm/Support/PluginLoader.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/WithColor.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
56 // General options for llc. Other pass-specific options are specified
57 // within the corresponding llc passes, and target-specific options
58 // and back-end code generation options are specified with the target machine.
60 static cl::opt
<std::string
>
61 InputFilename(cl::Positional
, cl::desc("<input bitcode>"), cl::init("-"));
63 static cl::opt
<std::string
>
64 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
66 static cl::opt
<std::string
>
67 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
69 static cl::opt
<std::string
>
70 SplitDwarfOutputFile("split-dwarf-output",
71 cl::desc(".dwo output filename"),
72 cl::value_desc("filename"));
74 static cl::opt
<unsigned>
75 TimeCompilations("time-compilations", cl::Hidden
, cl::init(1u),
77 cl::desc("Repeat compilation N times for timing"));
80 NoIntegratedAssembler("no-integrated-as", cl::Hidden
,
81 cl::desc("Disable integrated assembler"));
84 PreserveComments("preserve-as-comments", cl::Hidden
,
85 cl::desc("Preserve Comments in outputted assembly"),
88 // Determine optimization level.
91 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
97 static cl::opt
<std::string
>
98 TargetTriple("mtriple", cl::desc("Override target triple for module"));
100 static cl::opt
<std::string
> SplitDwarfFile(
103 "Specify the name of the .dwo file to encode in the DWARF output"));
105 static cl::opt
<bool> NoVerify("disable-verify", cl::Hidden
,
106 cl::desc("Do not verify input module"));
108 static cl::opt
<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
109 cl::desc("Disable simplify-libcalls"));
111 static cl::opt
<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden
,
112 cl::desc("Show encoding in .s output"));
114 static cl::opt
<bool> EnableDwarfDirectory(
115 "enable-dwarf-directory", cl::Hidden
,
116 cl::desc("Use .file directives with an explicit directory."));
118 static cl::opt
<bool> AsmVerbose("asm-verbose",
119 cl::desc("Add comments to directives."),
123 CompileTwice("compile-twice", cl::Hidden
,
124 cl::desc("Run everything twice, re-using the same pass "
125 "manager and verify the result is the same."),
128 static cl::opt
<bool> DiscardValueNames(
129 "discard-value-names",
130 cl::desc("Discard names from Value (other than GlobalValue)."),
131 cl::init(false), cl::Hidden
);
133 static cl::list
<std::string
> IncludeDirs("I", cl::desc("include search path"));
135 static cl::opt
<bool> PassRemarksWithHotness(
136 "pass-remarks-with-hotness",
137 cl::desc("With PGO, include profile count in optimization remarks"),
140 static cl::opt
<unsigned> PassRemarksHotnessThreshold(
141 "pass-remarks-hotness-threshold",
142 cl::desc("Minimum profile count required for an optimization remark to be output"),
145 static cl::opt
<std::string
>
146 RemarksFilename("pass-remarks-output",
147 cl::desc("YAML output filename for pass remarks"),
148 cl::value_desc("filename"));
151 static ManagedStatic
<std::vector
<std::string
>> RunPassNames
;
153 struct RunPassOption
{
154 void operator=(const std::string
&Val
) const {
157 SmallVector
<StringRef
, 8> PassNames
;
158 StringRef(Val
).split(PassNames
, ',', -1, false);
159 for (auto PassName
: PassNames
)
160 RunPassNames
->push_back(PassName
);
165 static RunPassOption RunPassOpt
;
167 static cl::opt
<RunPassOption
, true, cl::parser
<std::string
>> RunPass(
169 cl::desc("Run compiler only for specified passes (comma separated list)"),
170 cl::value_desc("pass-name"), cl::ZeroOrMore
, cl::location(RunPassOpt
));
172 static int compileModule(char **, LLVMContext
&);
174 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(const char *TargetName
,
176 const char *ProgName
) {
177 // If we don't yet have an output filename, make one.
178 if (OutputFilename
.empty()) {
179 if (InputFilename
== "-")
180 OutputFilename
= "-";
182 // If InputFilename ends in .bc or .ll, remove it.
183 StringRef IFN
= InputFilename
;
184 if (IFN
.endswith(".bc") || IFN
.endswith(".ll"))
185 OutputFilename
= IFN
.drop_back(3);
186 else if (IFN
.endswith(".mir"))
187 OutputFilename
= IFN
.drop_back(4);
189 OutputFilename
= IFN
;
192 case TargetMachine::CGFT_AssemblyFile
:
193 if (TargetName
[0] == 'c') {
194 if (TargetName
[1] == 0)
195 OutputFilename
+= ".cbe.c";
196 else if (TargetName
[1] == 'p' && TargetName
[2] == 'p')
197 OutputFilename
+= ".cpp";
199 OutputFilename
+= ".s";
201 OutputFilename
+= ".s";
203 case TargetMachine::CGFT_ObjectFile
:
204 if (OS
== Triple::Win32
)
205 OutputFilename
+= ".obj";
207 OutputFilename
+= ".o";
209 case TargetMachine::CGFT_Null
:
210 OutputFilename
+= ".null";
216 // Decide if we need "binary" output.
219 case TargetMachine::CGFT_AssemblyFile
:
221 case TargetMachine::CGFT_ObjectFile
:
222 case TargetMachine::CGFT_Null
:
229 sys::fs::OpenFlags OpenFlags
= sys::fs::F_None
;
231 OpenFlags
|= sys::fs::F_Text
;
232 auto FDOut
= llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, OpenFlags
);
234 WithColor::error() << EC
.message() << '\n';
241 struct LLCDiagnosticHandler
: public DiagnosticHandler
{
243 LLCDiagnosticHandler(bool *HasErrorPtr
) : HasError(HasErrorPtr
) {}
244 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
{
245 if (DI
.getSeverity() == DS_Error
)
248 if (auto *Remark
= dyn_cast
<DiagnosticInfoOptimizationBase
>(&DI
))
249 if (!Remark
->isEnabled())
252 DiagnosticPrinterRawOStream
DP(errs());
253 errs() << LLVMContext::getDiagnosticMessagePrefix(DI
.getSeverity()) << ": ";
260 static void InlineAsmDiagHandler(const SMDiagnostic
&SMD
, void *Context
,
261 unsigned LocCookie
) {
262 bool *HasError
= static_cast<bool *>(Context
);
263 if (SMD
.getKind() == SourceMgr::DK_Error
)
266 SMD
.print(nullptr, errs());
268 // For testing purposes, we print the LocCookie here.
270 WithColor::note() << "!srcloc = " << LocCookie
<< "\n";
273 // main - Entry point for the llc compiler.
275 int main(int argc
, char **argv
) {
276 InitLLVM
X(argc
, argv
);
278 // Enable debug stream buffering.
279 EnableDebugBuffering
= true;
283 // Initialize targets first, so that --version shows registered targets.
284 InitializeAllTargets();
285 InitializeAllTargetMCs();
286 InitializeAllAsmPrinters();
287 InitializeAllAsmParsers();
289 // Initialize codegen and IR passes used by llc so that the -print-after,
290 // -print-before, and -stop-after options work.
291 PassRegistry
*Registry
= PassRegistry::getPassRegistry();
292 initializeCore(*Registry
);
293 initializeCodeGen(*Registry
);
294 initializeLoopStrengthReducePass(*Registry
);
295 initializeLowerIntrinsicsPass(*Registry
);
296 initializeEntryExitInstrumenterPass(*Registry
);
297 initializePostInlineEntryExitInstrumenterPass(*Registry
);
298 initializeUnreachableBlockElimLegacyPassPass(*Registry
);
299 initializeConstantHoistingLegacyPassPass(*Registry
);
300 initializeScalarOpts(*Registry
);
301 initializeVectorization(*Registry
);
302 initializeScalarizeMaskedMemIntrinPass(*Registry
);
303 initializeExpandReductionsPass(*Registry
);
305 // Initialize debugging passes.
306 initializeScavengerTestPass(*Registry
);
308 // Register the target printer for --version.
309 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
311 cl::ParseCommandLineOptions(argc
, argv
, "llvm system compiler\n");
313 Context
.setDiscardValueNames(DiscardValueNames
);
315 // Set a diagnostic handler that doesn't exit on the first error
316 bool HasError
= false;
317 Context
.setDiagnosticHandler(
318 llvm::make_unique
<LLCDiagnosticHandler
>(&HasError
));
319 Context
.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler
, &HasError
);
321 if (PassRemarksWithHotness
)
322 Context
.setDiagnosticsHotnessRequested(true);
324 if (PassRemarksHotnessThreshold
)
325 Context
.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold
);
327 std::unique_ptr
<ToolOutputFile
> YamlFile
;
328 if (RemarksFilename
!= "") {
331 llvm::make_unique
<ToolOutputFile
>(RemarksFilename
, EC
, sys::fs::F_None
);
333 WithColor::error(errs(), argv
[0]) << EC
.message() << '\n';
336 Context
.setDiagnosticsOutputFile(
337 llvm::make_unique
<yaml::Output
>(YamlFile
->os()));
340 if (InputLanguage
!= "" && InputLanguage
!= "ir" &&
341 InputLanguage
!= "mir") {
342 WithColor::error(errs(), argv
[0])
343 << "input language must be '', 'IR' or 'MIR'\n";
347 // Compile the module TimeCompilations times to give better compile time
349 for (unsigned I
= TimeCompilations
; I
; --I
)
350 if (int RetVal
= compileModule(argv
, Context
))
358 static bool addPass(PassManagerBase
&PM
, const char *argv0
,
359 StringRef PassName
, TargetPassConfig
&TPC
) {
360 if (PassName
== "none")
363 const PassRegistry
*PR
= PassRegistry::getPassRegistry();
364 const PassInfo
*PI
= PR
->getPassInfo(PassName
);
366 WithColor::error(errs(), argv0
)
367 << "run-pass " << PassName
<< " is not registered.\n";
372 if (PI
->getNormalCtor())
373 P
= PI
->getNormalCtor()();
375 WithColor::error(errs(), argv0
)
376 << "cannot create pass: " << PI
->getPassName() << "\n";
379 std::string Banner
= std::string("After ") + std::string(P
->getPassName());
381 TPC
.printAndVerify(Banner
);
386 static int compileModule(char **argv
, LLVMContext
&Context
) {
387 // Load the module to be compiled...
389 std::unique_ptr
<Module
> M
;
390 std::unique_ptr
<MIRParser
> MIR
;
393 bool SkipModule
= MCPU
== "help" ||
394 (!MAttrs
.empty() && MAttrs
.front() == "help");
396 // If user just wants to list available options, skip module loading
398 if (InputLanguage
== "mir" ||
399 (InputLanguage
== "" && StringRef(InputFilename
).endswith(".mir"))) {
400 MIR
= createMIRParserFromFile(InputFilename
, Err
, Context
);
402 M
= MIR
->parseIRModule();
404 M
= parseIRFile(InputFilename
, Err
, Context
, false);
406 Err
.print(argv
[0], WithColor::error(errs(), argv
[0]));
410 // If we are supposed to override the target triple, do so now.
411 if (!TargetTriple
.empty())
412 M
->setTargetTriple(Triple::normalize(TargetTriple
));
413 TheTriple
= Triple(M
->getTargetTriple());
415 TheTriple
= Triple(Triple::normalize(TargetTriple
));
418 if (TheTriple
.getTriple().empty())
419 TheTriple
.setTriple(sys::getDefaultTargetTriple());
421 // Get the target specific parser.
423 const Target
*TheTarget
= TargetRegistry::lookupTarget(MArch
, TheTriple
,
426 WithColor::error(errs(), argv
[0]) << Error
;
430 std::string CPUStr
= getCPUStr(), FeaturesStr
= getFeaturesStr();
432 CodeGenOpt::Level OLvl
= CodeGenOpt::Default
;
435 WithColor::error(errs(), argv
[0]) << "invalid optimization level.\n";
438 case '0': OLvl
= CodeGenOpt::None
; break;
439 case '1': OLvl
= CodeGenOpt::Less
; break;
440 case '2': OLvl
= CodeGenOpt::Default
; break;
441 case '3': OLvl
= CodeGenOpt::Aggressive
; break;
444 TargetOptions Options
= InitTargetOptionsFromCodeGenFlags();
445 Options
.DisableIntegratedAS
= NoIntegratedAssembler
;
446 Options
.MCOptions
.ShowMCEncoding
= ShowMCEncoding
;
447 Options
.MCOptions
.MCUseDwarfDirectory
= EnableDwarfDirectory
;
448 Options
.MCOptions
.AsmVerbose
= AsmVerbose
;
449 Options
.MCOptions
.PreserveAsmComments
= PreserveComments
;
450 Options
.MCOptions
.IASSearchPaths
= IncludeDirs
;
451 Options
.MCOptions
.SplitDwarfFile
= SplitDwarfFile
;
453 std::unique_ptr
<TargetMachine
> Target(TheTarget
->createTargetMachine(
454 TheTriple
.getTriple(), CPUStr
, FeaturesStr
, Options
, getRelocModel(),
455 getCodeModel(), OLvl
));
457 assert(Target
&& "Could not allocate target machine!");
459 // If we don't have a module then just exit now. We do this down
460 // here since the CPU/Feature help is underneath the target machine
465 assert(M
&& "Should have exited if we didn't have a module!");
466 if (FloatABIForCalls
!= FloatABI::Default
)
467 Options
.FloatABIType
= FloatABIForCalls
;
469 // Figure out where we are going to send the output.
470 std::unique_ptr
<ToolOutputFile
> Out
=
471 GetOutputStream(TheTarget
->getName(), TheTriple
.getOS(), argv
[0]);
474 std::unique_ptr
<ToolOutputFile
> DwoOut
;
475 if (!SplitDwarfOutputFile
.empty()) {
477 DwoOut
= llvm::make_unique
<ToolOutputFile
>(SplitDwarfOutputFile
, EC
,
480 WithColor::error(errs(), argv
[0]) << EC
.message() << '\n';
485 // Build up all of the passes that we want to do to the module.
486 legacy::PassManager PM
;
488 // Add an appropriate TargetLibraryInfo pass for the module's triple.
489 TargetLibraryInfoImpl
TLII(Triple(M
->getTargetTriple()));
491 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
492 if (DisableSimplifyLibCalls
)
493 TLII
.disableAllFunctions();
494 PM
.add(new TargetLibraryInfoWrapperPass(TLII
));
496 // Add the target data from the target machine, if it exists, or the module.
497 M
->setDataLayout(Target
->createDataLayout());
499 // This needs to be done after setting datalayout since it calls verifier
500 // to check debug info whereas verifier relies on correct datalayout.
501 UpgradeDebugInfo(*M
);
503 // Verify module immediately to catch problems before doInitialization() is
504 // called on any passes.
505 if (!NoVerify
&& verifyModule(*M
, &errs())) {
507 (Twine(argv
[0]) + Twine(": ") + Twine(InputFilename
)).str();
508 WithColor::error(errs(), Prefix
) << "input module is broken!\n";
512 // Override function attributes based on CPUStr, FeaturesStr, and command line
514 setFunctionAttributes(CPUStr
, FeaturesStr
, *M
);
516 if (RelaxAll
.getNumOccurrences() > 0 &&
517 FileType
!= TargetMachine::CGFT_ObjectFile
)
518 WithColor::warning(errs(), argv
[0])
519 << ": warning: ignoring -mc-relax-all because filetype != obj";
522 raw_pwrite_stream
*OS
= &Out
->os();
524 // Manually do the buffering rather than using buffer_ostream,
525 // so we can memcmp the contents in CompileTwice mode
526 SmallVector
<char, 0> Buffer
;
527 std::unique_ptr
<raw_svector_ostream
> BOS
;
528 if ((FileType
!= TargetMachine::CGFT_AssemblyFile
&&
529 !Out
->os().supportsSeeking()) ||
531 BOS
= make_unique
<raw_svector_ostream
>(Buffer
);
535 const char *argv0
= argv
[0];
536 LLVMTargetMachine
&LLVMTM
= static_cast<LLVMTargetMachine
&>(*Target
);
537 MachineModuleInfo
*MMI
= new MachineModuleInfo(&LLVMTM
);
539 // Construct a custom pass pipeline that starts after instruction
541 if (!RunPassNames
->empty()) {
543 WithColor::warning(errs(), argv
[0])
544 << "run-pass is for .mir file only.\n";
547 TargetPassConfig
&TPC
= *LLVMTM
.createPassConfig(PM
);
548 if (TPC
.hasLimitedCodeGenPipeline()) {
549 WithColor::warning(errs(), argv
[0])
550 << "run-pass cannot be used with "
551 << TPC
.getLimitedCodeGenPipelineReason(" and ") << ".\n";
555 TPC
.setDisableVerify(NoVerify
);
558 TPC
.printAndVerify("");
559 for (const std::string
&RunPassName
: *RunPassNames
) {
560 if (addPass(PM
, argv0
, RunPassName
, TPC
))
563 TPC
.setInitialized();
564 PM
.add(createPrintMIRPass(*OS
));
565 PM
.add(createFreeMachineFunctionPass());
566 } else if (Target
->addPassesToEmitFile(PM
, *OS
,
567 DwoOut
? &DwoOut
->os() : nullptr,
568 FileType
, NoVerify
, MMI
)) {
569 WithColor::warning(errs(), argv
[0])
570 << "target does not support generation of this"
576 assert(MMI
&& "Forgot to create MMI?");
577 if (MIR
->parseMachineFunctions(*M
, *MMI
))
581 // Before executing passes, print the final values of the LLVM options.
582 cl::PrintOptionValues();
584 // If requested, run the pass manager over the same module again,
585 // to catch any bugs due to persistent state in the passes. Note that
586 // opt has the same functionality, so it may be worth abstracting this out
588 SmallVector
<char, 0> CompileTwiceBuffer
;
590 std::unique_ptr
<Module
> M2(llvm::CloneModule(*M
));
592 CompileTwiceBuffer
= Buffer
;
599 ((const LLCDiagnosticHandler
*)(Context
.getDiagHandlerPtr()))->HasError
;
603 // Compare the two outputs and make sure they're the same
605 if (Buffer
.size() != CompileTwiceBuffer
.size() ||
606 (memcmp(Buffer
.data(), CompileTwiceBuffer
.data(), Buffer
.size()) !=
609 << "Running the pass manager twice changed the output.\n"
610 "Writing the result of the second run to the specified output\n"
611 "To generate the one-run comparison binary, just run without\n"
612 "the compile-twice option\n";