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/RemarkStreamer.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/PluginLoader.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/WithColor.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Utils/Cloning.h"
58 // General options for llc. Other pass-specific options are specified
59 // within the corresponding llc passes, and target-specific options
60 // and back-end code generation options are specified with the target machine.
62 static cl::opt
<std::string
>
63 InputFilename(cl::Positional
, cl::desc("<input bitcode>"), cl::init("-"));
65 static cl::opt
<std::string
>
66 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
68 static cl::opt
<std::string
>
69 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
71 static cl::opt
<std::string
>
72 SplitDwarfOutputFile("split-dwarf-output",
73 cl::desc(".dwo output filename"),
74 cl::value_desc("filename"));
76 static cl::opt
<unsigned>
77 TimeCompilations("time-compilations", cl::Hidden
, cl::init(1u),
79 cl::desc("Repeat compilation N times for timing"));
82 NoIntegratedAssembler("no-integrated-as", cl::Hidden
,
83 cl::desc("Disable integrated assembler"));
86 PreserveComments("preserve-as-comments", cl::Hidden
,
87 cl::desc("Preserve Comments in outputted assembly"),
90 // Determine optimization level.
93 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
99 static cl::opt
<std::string
>
100 TargetTriple("mtriple", cl::desc("Override target triple for module"));
102 static cl::opt
<std::string
> SplitDwarfFile(
105 "Specify the name of the .dwo file to encode in the DWARF output"));
107 static cl::opt
<bool> NoVerify("disable-verify", cl::Hidden
,
108 cl::desc("Do not verify input module"));
110 static cl::opt
<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
111 cl::desc("Disable simplify-libcalls"));
113 static cl::opt
<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden
,
114 cl::desc("Show encoding in .s output"));
116 static cl::opt
<bool> EnableDwarfDirectory(
117 "enable-dwarf-directory", cl::Hidden
,
118 cl::desc("Use .file directives with an explicit directory."));
120 static cl::opt
<bool> AsmVerbose("asm-verbose",
121 cl::desc("Add comments to directives."),
125 CompileTwice("compile-twice", cl::Hidden
,
126 cl::desc("Run everything twice, re-using the same pass "
127 "manager and verify the result is the same."),
130 static cl::opt
<bool> DiscardValueNames(
131 "discard-value-names",
132 cl::desc("Discard names from Value (other than GlobalValue)."),
133 cl::init(false), cl::Hidden
);
135 static cl::list
<std::string
> IncludeDirs("I", cl::desc("include search path"));
137 static cl::opt
<bool> RemarksWithHotness(
138 "pass-remarks-with-hotness",
139 cl::desc("With PGO, include profile count in optimization remarks"),
142 static cl::opt
<unsigned>
143 RemarksHotnessThreshold("pass-remarks-hotness-threshold",
144 cl::desc("Minimum profile count required for "
145 "an optimization remark to be output"),
148 static cl::opt
<std::string
>
149 RemarksFilename("pass-remarks-output",
150 cl::desc("Output filename for pass remarks"),
151 cl::value_desc("filename"));
153 static cl::opt
<std::string
>
154 RemarksPasses("pass-remarks-filter",
155 cl::desc("Only record optimization remarks from passes whose "
156 "names match the given regular expression"),
157 cl::value_desc("regex"));
159 static cl::opt
<std::string
> RemarksFormat(
160 "pass-remarks-format",
161 cl::desc("The format used for serializing remarks (default: YAML)"),
162 cl::value_desc("format"), cl::init("yaml"));
165 static ManagedStatic
<std::vector
<std::string
>> RunPassNames
;
167 struct RunPassOption
{
168 void operator=(const std::string
&Val
) const {
171 SmallVector
<StringRef
, 8> PassNames
;
172 StringRef(Val
).split(PassNames
, ',', -1, false);
173 for (auto PassName
: PassNames
)
174 RunPassNames
->push_back(PassName
);
179 static RunPassOption RunPassOpt
;
181 static cl::opt
<RunPassOption
, true, cl::parser
<std::string
>> RunPass(
183 cl::desc("Run compiler only for specified passes (comma separated list)"),
184 cl::value_desc("pass-name"), cl::ZeroOrMore
, cl::location(RunPassOpt
));
186 static int compileModule(char **, LLVMContext
&);
188 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(const char *TargetName
,
190 const char *ProgName
) {
191 // If we don't yet have an output filename, make one.
192 if (OutputFilename
.empty()) {
193 if (InputFilename
== "-")
194 OutputFilename
= "-";
196 // If InputFilename ends in .bc or .ll, remove it.
197 StringRef IFN
= InputFilename
;
198 if (IFN
.endswith(".bc") || IFN
.endswith(".ll"))
199 OutputFilename
= IFN
.drop_back(3);
200 else if (IFN
.endswith(".mir"))
201 OutputFilename
= IFN
.drop_back(4);
203 OutputFilename
= IFN
;
206 case CGFT_AssemblyFile
:
207 if (TargetName
[0] == 'c') {
208 if (TargetName
[1] == 0)
209 OutputFilename
+= ".cbe.c";
210 else if (TargetName
[1] == 'p' && TargetName
[2] == 'p')
211 OutputFilename
+= ".cpp";
213 OutputFilename
+= ".s";
215 OutputFilename
+= ".s";
217 case CGFT_ObjectFile
:
218 if (OS
== Triple::Win32
)
219 OutputFilename
+= ".obj";
221 OutputFilename
+= ".o";
224 OutputFilename
+= ".null";
230 // Decide if we need "binary" output.
233 case CGFT_AssemblyFile
:
235 case CGFT_ObjectFile
:
243 sys::fs::OpenFlags OpenFlags
= sys::fs::OF_None
;
245 OpenFlags
|= sys::fs::OF_Text
;
246 auto FDOut
= std::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, OpenFlags
);
248 WithColor::error() << EC
.message() << '\n';
255 struct LLCDiagnosticHandler
: public DiagnosticHandler
{
257 LLCDiagnosticHandler(bool *HasErrorPtr
) : HasError(HasErrorPtr
) {}
258 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
{
259 if (DI
.getSeverity() == DS_Error
)
262 if (auto *Remark
= dyn_cast
<DiagnosticInfoOptimizationBase
>(&DI
))
263 if (!Remark
->isEnabled())
266 DiagnosticPrinterRawOStream
DP(errs());
267 errs() << LLVMContext::getDiagnosticMessagePrefix(DI
.getSeverity()) << ": ";
274 static void InlineAsmDiagHandler(const SMDiagnostic
&SMD
, void *Context
,
275 unsigned LocCookie
) {
276 bool *HasError
= static_cast<bool *>(Context
);
277 if (SMD
.getKind() == SourceMgr::DK_Error
)
280 SMD
.print(nullptr, errs());
282 // For testing purposes, we print the LocCookie here.
284 WithColor::note() << "!srcloc = " << LocCookie
<< "\n";
287 // main - Entry point for the llc compiler.
289 int main(int argc
, char **argv
) {
290 InitLLVM
X(argc
, argv
);
292 // Enable debug stream buffering.
293 EnableDebugBuffering
= true;
297 // Initialize targets first, so that --version shows registered targets.
298 InitializeAllTargets();
299 InitializeAllTargetMCs();
300 InitializeAllAsmPrinters();
301 InitializeAllAsmParsers();
303 // Initialize codegen and IR passes used by llc so that the -print-after,
304 // -print-before, and -stop-after options work.
305 PassRegistry
*Registry
= PassRegistry::getPassRegistry();
306 initializeCore(*Registry
);
307 initializeCodeGen(*Registry
);
308 initializeLoopStrengthReducePass(*Registry
);
309 initializeLowerIntrinsicsPass(*Registry
);
310 initializeEntryExitInstrumenterPass(*Registry
);
311 initializePostInlineEntryExitInstrumenterPass(*Registry
);
312 initializeUnreachableBlockElimLegacyPassPass(*Registry
);
313 initializeConstantHoistingLegacyPassPass(*Registry
);
314 initializeScalarOpts(*Registry
);
315 initializeVectorization(*Registry
);
316 initializeScalarizeMaskedMemIntrinPass(*Registry
);
317 initializeExpandReductionsPass(*Registry
);
318 initializeHardwareLoopsPass(*Registry
);
320 // Initialize debugging passes.
321 initializeScavengerTestPass(*Registry
);
323 // Register the target printer for --version.
324 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
326 cl::ParseCommandLineOptions(argc
, argv
, "llvm system compiler\n");
328 Context
.setDiscardValueNames(DiscardValueNames
);
330 // Set a diagnostic handler that doesn't exit on the first error
331 bool HasError
= false;
332 Context
.setDiagnosticHandler(
333 std::make_unique
<LLCDiagnosticHandler
>(&HasError
));
334 Context
.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler
, &HasError
);
336 Expected
<std::unique_ptr
<ToolOutputFile
>> RemarksFileOrErr
=
337 setupOptimizationRemarks(Context
, RemarksFilename
, RemarksPasses
,
338 RemarksFormat
, RemarksWithHotness
,
339 RemarksHotnessThreshold
);
340 if (Error E
= RemarksFileOrErr
.takeError()) {
341 WithColor::error(errs(), argv
[0]) << toString(std::move(E
)) << '\n';
344 std::unique_ptr
<ToolOutputFile
> RemarksFile
= std::move(*RemarksFileOrErr
);
346 if (InputLanguage
!= "" && InputLanguage
!= "ir" &&
347 InputLanguage
!= "mir") {
348 WithColor::error(errs(), argv
[0])
349 << "input language must be '', 'IR' or 'MIR'\n";
353 // Compile the module TimeCompilations times to give better compile time
355 for (unsigned I
= TimeCompilations
; I
; --I
)
356 if (int RetVal
= compileModule(argv
, Context
))
364 static bool addPass(PassManagerBase
&PM
, const char *argv0
,
365 StringRef PassName
, TargetPassConfig
&TPC
) {
366 if (PassName
== "none")
369 const PassRegistry
*PR
= PassRegistry::getPassRegistry();
370 const PassInfo
*PI
= PR
->getPassInfo(PassName
);
372 WithColor::error(errs(), argv0
)
373 << "run-pass " << PassName
<< " is not registered.\n";
378 if (PI
->getNormalCtor())
379 P
= PI
->getNormalCtor()();
381 WithColor::error(errs(), argv0
)
382 << "cannot create pass: " << PI
->getPassName() << "\n";
385 std::string Banner
= std::string("After ") + std::string(P
->getPassName());
387 TPC
.printAndVerify(Banner
);
392 static int compileModule(char **argv
, LLVMContext
&Context
) {
393 // Load the module to be compiled...
395 std::unique_ptr
<Module
> M
;
396 std::unique_ptr
<MIRParser
> MIR
;
398 std::string CPUStr
= getCPUStr(), FeaturesStr
= getFeaturesStr();
400 // Set attributes on functions as loaded from MIR from command line arguments.
401 auto setMIRFunctionAttributes
= [&CPUStr
, &FeaturesStr
](Function
&F
) {
402 setFunctionAttributes(CPUStr
, FeaturesStr
, F
);
405 bool SkipModule
= MCPU
== "help" ||
406 (!MAttrs
.empty() && MAttrs
.front() == "help");
408 // If user just wants to list available options, skip module loading
410 if (InputLanguage
== "mir" ||
411 (InputLanguage
== "" && StringRef(InputFilename
).endswith(".mir"))) {
412 MIR
= createMIRParserFromFile(InputFilename
, Err
, Context
,
413 setMIRFunctionAttributes
);
415 M
= MIR
->parseIRModule();
417 M
= parseIRFile(InputFilename
, Err
, Context
, false);
419 Err
.print(argv
[0], WithColor::error(errs(), argv
[0]));
423 // If we are supposed to override the target triple, do so now.
424 if (!TargetTriple
.empty())
425 M
->setTargetTriple(Triple::normalize(TargetTriple
));
426 TheTriple
= Triple(M
->getTargetTriple());
428 TheTriple
= Triple(Triple::normalize(TargetTriple
));
431 if (TheTriple
.getTriple().empty())
432 TheTriple
.setTriple(sys::getDefaultTargetTriple());
434 // Get the target specific parser.
436 const Target
*TheTarget
= TargetRegistry::lookupTarget(MArch
, TheTriple
,
439 WithColor::error(errs(), argv
[0]) << Error
;
443 CodeGenOpt::Level OLvl
= CodeGenOpt::Default
;
446 WithColor::error(errs(), argv
[0]) << "invalid optimization level.\n";
449 case '0': OLvl
= CodeGenOpt::None
; break;
450 case '1': OLvl
= CodeGenOpt::Less
; break;
451 case '2': OLvl
= CodeGenOpt::Default
; break;
452 case '3': OLvl
= CodeGenOpt::Aggressive
; break;
455 TargetOptions Options
= InitTargetOptionsFromCodeGenFlags();
456 Options
.DisableIntegratedAS
= NoIntegratedAssembler
;
457 Options
.MCOptions
.ShowMCEncoding
= ShowMCEncoding
;
458 Options
.MCOptions
.MCUseDwarfDirectory
= EnableDwarfDirectory
;
459 Options
.MCOptions
.AsmVerbose
= AsmVerbose
;
460 Options
.MCOptions
.PreserveAsmComments
= PreserveComments
;
461 Options
.MCOptions
.IASSearchPaths
= IncludeDirs
;
462 Options
.MCOptions
.SplitDwarfFile
= SplitDwarfFile
;
464 // On AIX, setting the relocation model to anything other than PIC is considered
466 Optional
<Reloc::Model
> RM
= getRelocModel();
467 if (TheTriple
.isOSAIX() && RM
.hasValue() && *RM
!= Reloc::PIC_
) {
468 WithColor::error(errs(), argv
[0])
469 << "invalid relocation model, AIX only supports PIC.\n";
473 std::unique_ptr
<TargetMachine
> Target(TheTarget
->createTargetMachine(
474 TheTriple
.getTriple(), CPUStr
, FeaturesStr
, Options
, RM
,
475 getCodeModel(), OLvl
));
477 assert(Target
&& "Could not allocate target machine!");
479 // If we don't have a module then just exit now. We do this down
480 // here since the CPU/Feature help is underneath the target machine
485 assert(M
&& "Should have exited if we didn't have a module!");
486 if (FloatABIForCalls
!= FloatABI::Default
)
487 Options
.FloatABIType
= FloatABIForCalls
;
489 // Figure out where we are going to send the output.
490 std::unique_ptr
<ToolOutputFile
> Out
=
491 GetOutputStream(TheTarget
->getName(), TheTriple
.getOS(), argv
[0]);
494 std::unique_ptr
<ToolOutputFile
> DwoOut
;
495 if (!SplitDwarfOutputFile
.empty()) {
497 DwoOut
= std::make_unique
<ToolOutputFile
>(SplitDwarfOutputFile
, EC
,
500 WithColor::error(errs(), argv
[0]) << EC
.message() << '\n';
505 // Build up all of the passes that we want to do to the module.
506 legacy::PassManager PM
;
508 // Add an appropriate TargetLibraryInfo pass for the module's triple.
509 TargetLibraryInfoImpl
TLII(Triple(M
->getTargetTriple()));
511 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
512 if (DisableSimplifyLibCalls
)
513 TLII
.disableAllFunctions();
514 PM
.add(new TargetLibraryInfoWrapperPass(TLII
));
516 // Add the target data from the target machine, if it exists, or the module.
517 M
->setDataLayout(Target
->createDataLayout());
519 // This needs to be done after setting datalayout since it calls verifier
520 // to check debug info whereas verifier relies on correct datalayout.
521 UpgradeDebugInfo(*M
);
523 // Verify module immediately to catch problems before doInitialization() is
524 // called on any passes.
525 if (!NoVerify
&& verifyModule(*M
, &errs())) {
527 (Twine(argv
[0]) + Twine(": ") + Twine(InputFilename
)).str();
528 WithColor::error(errs(), Prefix
) << "input module is broken!\n";
532 // Override function attributes based on CPUStr, FeaturesStr, and command line
534 setFunctionAttributes(CPUStr
, FeaturesStr
, *M
);
536 if (RelaxAll
.getNumOccurrences() > 0 &&
537 FileType
!= CGFT_ObjectFile
)
538 WithColor::warning(errs(), argv
[0])
539 << ": warning: ignoring -mc-relax-all because filetype != obj";
542 raw_pwrite_stream
*OS
= &Out
->os();
544 // Manually do the buffering rather than using buffer_ostream,
545 // so we can memcmp the contents in CompileTwice mode
546 SmallVector
<char, 0> Buffer
;
547 std::unique_ptr
<raw_svector_ostream
> BOS
;
548 if ((FileType
!= CGFT_AssemblyFile
&&
549 !Out
->os().supportsSeeking()) ||
551 BOS
= std::make_unique
<raw_svector_ostream
>(Buffer
);
555 const char *argv0
= argv
[0];
556 LLVMTargetMachine
&LLVMTM
= static_cast<LLVMTargetMachine
&>(*Target
);
557 MachineModuleInfoWrapperPass
*MMIWP
=
558 new MachineModuleInfoWrapperPass(&LLVMTM
);
560 // Construct a custom pass pipeline that starts after instruction
562 if (!RunPassNames
->empty()) {
564 WithColor::warning(errs(), argv
[0])
565 << "run-pass is for .mir file only.\n";
568 TargetPassConfig
&TPC
= *LLVMTM
.createPassConfig(PM
);
569 if (TPC
.hasLimitedCodeGenPipeline()) {
570 WithColor::warning(errs(), argv
[0])
571 << "run-pass cannot be used with "
572 << TPC
.getLimitedCodeGenPipelineReason(" and ") << ".\n";
576 TPC
.setDisableVerify(NoVerify
);
579 TPC
.printAndVerify("");
580 for (const std::string
&RunPassName
: *RunPassNames
) {
581 if (addPass(PM
, argv0
, RunPassName
, TPC
))
584 TPC
.setInitialized();
585 PM
.add(createPrintMIRPass(*OS
));
586 PM
.add(createFreeMachineFunctionPass());
587 } else if (Target
->addPassesToEmitFile(PM
, *OS
,
588 DwoOut
? &DwoOut
->os() : nullptr,
589 FileType
, NoVerify
, MMIWP
)) {
590 WithColor::warning(errs(), argv
[0])
591 << "target does not support generation of this"
597 assert(MMIWP
&& "Forgot to create MMIWP?");
598 if (MIR
->parseMachineFunctions(*M
, MMIWP
->getMMI()))
602 // Before executing passes, print the final values of the LLVM options.
603 cl::PrintOptionValues();
605 // If requested, run the pass manager over the same module again,
606 // to catch any bugs due to persistent state in the passes. Note that
607 // opt has the same functionality, so it may be worth abstracting this out
609 SmallVector
<char, 0> CompileTwiceBuffer
;
611 std::unique_ptr
<Module
> M2(llvm::CloneModule(*M
));
613 CompileTwiceBuffer
= Buffer
;
620 ((const LLCDiagnosticHandler
*)(Context
.getDiagHandlerPtr()))->HasError
;
624 // Compare the two outputs and make sure they're the same
626 if (Buffer
.size() != CompileTwiceBuffer
.size() ||
627 (memcmp(Buffer
.data(), CompileTwiceBuffer
.data(), Buffer
.size()) !=
630 << "Running the pass manager twice changed the output.\n"
631 "Writing the result of the second run to the specified output\n"
632 "To generate the one-run comparison binary, just run without\n"
633 "the compile-twice option\n";