1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/CodeGen/CommandFlags.inc"
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/IRPrintingPasses.h"
32 #include "llvm/IR/LLVMContext.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/MC/SubtargetFeature.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/InitLLVM.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/WithColor.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
57 // General options for llc. Other pass-specific options are specified
58 // within the corresponding llc passes, and target-specific options
59 // and back-end code generation options are specified with the target machine.
61 static cl::opt
<std::string
>
62 InputFilename(cl::Positional
, cl::desc("<input bitcode>"), cl::init("-"));
64 static cl::opt
<std::string
>
65 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
67 static cl::opt
<std::string
>
68 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
70 static cl::opt
<std::string
>
71 SplitDwarfOutputFile("split-dwarf-output",
72 cl::desc(".dwo output filename"),
73 cl::value_desc("filename"));
75 static cl::opt
<unsigned>
76 TimeCompilations("time-compilations", cl::Hidden
, cl::init(1u),
78 cl::desc("Repeat compilation N times for timing"));
81 NoIntegratedAssembler("no-integrated-as", cl::Hidden
,
82 cl::desc("Disable integrated assembler"));
85 PreserveComments("preserve-as-comments", cl::Hidden
,
86 cl::desc("Preserve Comments in outputted assembly"),
89 // Determine optimization level.
92 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
98 static cl::opt
<std::string
>
99 TargetTriple("mtriple", cl::desc("Override target triple for module"));
101 static cl::opt
<std::string
> SplitDwarfFile(
104 "Specify the name of the .dwo file to encode in the DWARF output"));
106 static cl::opt
<bool> NoVerify("disable-verify", cl::Hidden
,
107 cl::desc("Do not verify input module"));
109 static cl::opt
<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
110 cl::desc("Disable simplify-libcalls"));
112 static cl::opt
<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden
,
113 cl::desc("Show encoding in .s output"));
115 static cl::opt
<bool> EnableDwarfDirectory(
116 "enable-dwarf-directory", cl::Hidden
,
117 cl::desc("Use .file directives with an explicit directory."));
119 static cl::opt
<bool> AsmVerbose("asm-verbose",
120 cl::desc("Add comments to directives."),
124 CompileTwice("compile-twice", cl::Hidden
,
125 cl::desc("Run everything twice, re-using the same pass "
126 "manager and verify the result is the same."),
129 static cl::opt
<bool> DiscardValueNames(
130 "discard-value-names",
131 cl::desc("Discard names from Value (other than GlobalValue)."),
132 cl::init(false), cl::Hidden
);
134 static cl::list
<std::string
> IncludeDirs("I", cl::desc("include search path"));
136 static cl::opt
<bool> PassRemarksWithHotness(
137 "pass-remarks-with-hotness",
138 cl::desc("With PGO, include profile count in optimization remarks"),
141 static cl::opt
<unsigned> PassRemarksHotnessThreshold(
142 "pass-remarks-hotness-threshold",
143 cl::desc("Minimum profile count required for an optimization remark to be output"),
146 static cl::opt
<std::string
>
147 RemarksFilename("pass-remarks-output",
148 cl::desc("YAML output filename for pass remarks"),
149 cl::value_desc("filename"));
152 static ManagedStatic
<std::vector
<std::string
>> RunPassNames
;
154 struct RunPassOption
{
155 void operator=(const std::string
&Val
) const {
158 SmallVector
<StringRef
, 8> PassNames
;
159 StringRef(Val
).split(PassNames
, ',', -1, false);
160 for (auto PassName
: PassNames
)
161 RunPassNames
->push_back(PassName
);
166 static RunPassOption RunPassOpt
;
168 static cl::opt
<RunPassOption
, true, cl::parser
<std::string
>> RunPass(
170 cl::desc("Run compiler only for specified passes (comma separated list)"),
171 cl::value_desc("pass-name"), cl::ZeroOrMore
, cl::location(RunPassOpt
));
173 static int compileModule(char **, LLVMContext
&);
175 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(const char *TargetName
,
177 const char *ProgName
) {
178 // If we don't yet have an output filename, make one.
179 if (OutputFilename
.empty()) {
180 if (InputFilename
== "-")
181 OutputFilename
= "-";
183 // If InputFilename ends in .bc or .ll, remove it.
184 StringRef IFN
= InputFilename
;
185 if (IFN
.endswith(".bc") || IFN
.endswith(".ll"))
186 OutputFilename
= IFN
.drop_back(3);
187 else if (IFN
.endswith(".mir"))
188 OutputFilename
= IFN
.drop_back(4);
190 OutputFilename
= IFN
;
193 case TargetMachine::CGFT_AssemblyFile
:
194 if (TargetName
[0] == 'c') {
195 if (TargetName
[1] == 0)
196 OutputFilename
+= ".cbe.c";
197 else if (TargetName
[1] == 'p' && TargetName
[2] == 'p')
198 OutputFilename
+= ".cpp";
200 OutputFilename
+= ".s";
202 OutputFilename
+= ".s";
204 case TargetMachine::CGFT_ObjectFile
:
205 if (OS
== Triple::Win32
)
206 OutputFilename
+= ".obj";
208 OutputFilename
+= ".o";
210 case TargetMachine::CGFT_Null
:
211 OutputFilename
+= ".null";
217 // Decide if we need "binary" output.
220 case TargetMachine::CGFT_AssemblyFile
:
222 case TargetMachine::CGFT_ObjectFile
:
223 case TargetMachine::CGFT_Null
:
230 sys::fs::OpenFlags OpenFlags
= sys::fs::F_None
;
232 OpenFlags
|= sys::fs::F_Text
;
233 auto FDOut
= llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, OpenFlags
);
235 WithColor::error() << EC
.message() << '\n';
242 struct LLCDiagnosticHandler
: public DiagnosticHandler
{
244 LLCDiagnosticHandler(bool *HasErrorPtr
) : HasError(HasErrorPtr
) {}
245 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
{
246 if (DI
.getSeverity() == DS_Error
)
249 if (auto *Remark
= dyn_cast
<DiagnosticInfoOptimizationBase
>(&DI
))
250 if (!Remark
->isEnabled())
253 DiagnosticPrinterRawOStream
DP(errs());
254 errs() << LLVMContext::getDiagnosticMessagePrefix(DI
.getSeverity()) << ": ";
261 static void InlineAsmDiagHandler(const SMDiagnostic
&SMD
, void *Context
,
262 unsigned LocCookie
) {
263 bool *HasError
= static_cast<bool *>(Context
);
264 if (SMD
.getKind() == SourceMgr::DK_Error
)
267 SMD
.print(nullptr, errs());
269 // For testing purposes, we print the LocCookie here.
271 WithColor::note() << "!srcloc = " << LocCookie
<< "\n";
274 // main - Entry point for the llc compiler.
276 int main(int argc
, char **argv
) {
277 InitLLVM
X(argc
, argv
);
279 // Enable debug stream buffering.
280 EnableDebugBuffering
= true;
284 // Initialize targets first, so that --version shows registered targets.
285 InitializeAllTargets();
286 InitializeAllTargetMCs();
287 InitializeAllAsmPrinters();
288 InitializeAllAsmParsers();
290 // Initialize codegen and IR passes used by llc so that the -print-after,
291 // -print-before, and -stop-after options work.
292 PassRegistry
*Registry
= PassRegistry::getPassRegistry();
293 initializeCore(*Registry
);
294 initializeCodeGen(*Registry
);
295 initializeLoopStrengthReducePass(*Registry
);
296 initializeLowerIntrinsicsPass(*Registry
);
297 initializeEntryExitInstrumenterPass(*Registry
);
298 initializePostInlineEntryExitInstrumenterPass(*Registry
);
299 initializeUnreachableBlockElimLegacyPassPass(*Registry
);
300 initializeConstantHoistingLegacyPassPass(*Registry
);
301 initializeScalarOpts(*Registry
);
302 initializeVectorization(*Registry
);
303 initializeScalarizeMaskedMemIntrinPass(*Registry
);
304 initializeExpandReductionsPass(*Registry
);
306 // Initialize debugging passes.
307 initializeScavengerTestPass(*Registry
);
309 // Register the target printer for --version.
310 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
312 cl::ParseCommandLineOptions(argc
, argv
, "llvm system compiler\n");
314 Context
.setDiscardValueNames(DiscardValueNames
);
316 // Set a diagnostic handler that doesn't exit on the first error
317 bool HasError
= false;
318 Context
.setDiagnosticHandler(
319 llvm::make_unique
<LLCDiagnosticHandler
>(&HasError
));
320 Context
.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler
, &HasError
);
322 if (PassRemarksWithHotness
)
323 Context
.setDiagnosticsHotnessRequested(true);
325 if (PassRemarksHotnessThreshold
)
326 Context
.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold
);
328 std::unique_ptr
<ToolOutputFile
> YamlFile
;
329 if (RemarksFilename
!= "") {
332 llvm::make_unique
<ToolOutputFile
>(RemarksFilename
, EC
, sys::fs::F_None
);
334 WithColor::error(errs(), argv
[0]) << EC
.message() << '\n';
337 Context
.setDiagnosticsOutputFile(
338 llvm::make_unique
<yaml::Output
>(YamlFile
->os()));
341 if (InputLanguage
!= "" && InputLanguage
!= "ir" &&
342 InputLanguage
!= "mir") {
343 WithColor::error(errs(), argv
[0])
344 << "input language must be '', 'IR' or 'MIR'\n";
348 // Compile the module TimeCompilations times to give better compile time
350 for (unsigned I
= TimeCompilations
; I
; --I
)
351 if (int RetVal
= compileModule(argv
, Context
))
359 static bool addPass(PassManagerBase
&PM
, const char *argv0
,
360 StringRef PassName
, TargetPassConfig
&TPC
) {
361 if (PassName
== "none")
364 const PassRegistry
*PR
= PassRegistry::getPassRegistry();
365 const PassInfo
*PI
= PR
->getPassInfo(PassName
);
367 WithColor::error(errs(), argv0
)
368 << "run-pass " << PassName
<< " is not registered.\n";
373 if (PI
->getNormalCtor())
374 P
= PI
->getNormalCtor()();
376 WithColor::error(errs(), argv0
)
377 << "cannot create pass: " << PI
->getPassName() << "\n";
380 std::string Banner
= std::string("After ") + std::string(P
->getPassName());
382 TPC
.printAndVerify(Banner
);
387 static int compileModule(char **argv
, LLVMContext
&Context
) {
388 // Load the module to be compiled...
390 std::unique_ptr
<Module
> M
;
391 std::unique_ptr
<MIRParser
> MIR
;
394 bool SkipModule
= MCPU
== "help" ||
395 (!MAttrs
.empty() && MAttrs
.front() == "help");
397 // If user just wants to list available options, skip module loading
399 if (InputLanguage
== "mir" ||
400 (InputLanguage
== "" && StringRef(InputFilename
).endswith(".mir"))) {
401 MIR
= createMIRParserFromFile(InputFilename
, Err
, Context
);
403 M
= MIR
->parseIRModule();
405 M
= parseIRFile(InputFilename
, Err
, Context
, false);
407 Err
.print(argv
[0], WithColor::error(errs(), argv
[0]));
411 // If we are supposed to override the target triple, do so now.
412 if (!TargetTriple
.empty())
413 M
->setTargetTriple(Triple::normalize(TargetTriple
));
414 TheTriple
= Triple(M
->getTargetTriple());
416 TheTriple
= Triple(Triple::normalize(TargetTriple
));
419 if (TheTriple
.getTriple().empty())
420 TheTriple
.setTriple(sys::getDefaultTargetTriple());
422 // Get the target specific parser.
424 const Target
*TheTarget
= TargetRegistry::lookupTarget(MArch
, TheTriple
,
427 WithColor::error(errs(), argv
[0]) << Error
;
431 std::string CPUStr
= getCPUStr(), FeaturesStr
= getFeaturesStr();
433 CodeGenOpt::Level OLvl
= CodeGenOpt::Default
;
436 WithColor::error(errs(), argv
[0]) << "invalid optimization level.\n";
439 case '0': OLvl
= CodeGenOpt::None
; break;
440 case '1': OLvl
= CodeGenOpt::Less
; break;
441 case '2': OLvl
= CodeGenOpt::Default
; break;
442 case '3': OLvl
= CodeGenOpt::Aggressive
; break;
445 TargetOptions Options
= InitTargetOptionsFromCodeGenFlags();
446 Options
.DisableIntegratedAS
= NoIntegratedAssembler
;
447 Options
.MCOptions
.ShowMCEncoding
= ShowMCEncoding
;
448 Options
.MCOptions
.MCUseDwarfDirectory
= EnableDwarfDirectory
;
449 Options
.MCOptions
.AsmVerbose
= AsmVerbose
;
450 Options
.MCOptions
.PreserveAsmComments
= PreserveComments
;
451 Options
.MCOptions
.IASSearchPaths
= IncludeDirs
;
452 Options
.MCOptions
.SplitDwarfFile
= SplitDwarfFile
;
454 std::unique_ptr
<TargetMachine
> Target(TheTarget
->createTargetMachine(
455 TheTriple
.getTriple(), CPUStr
, FeaturesStr
, Options
, getRelocModel(),
456 getCodeModel(), OLvl
));
458 assert(Target
&& "Could not allocate target machine!");
460 // If we don't have a module then just exit now. We do this down
461 // here since the CPU/Feature help is underneath the target machine
466 assert(M
&& "Should have exited if we didn't have a module!");
467 if (FloatABIForCalls
!= FloatABI::Default
)
468 Options
.FloatABIType
= FloatABIForCalls
;
470 // Figure out where we are going to send the output.
471 std::unique_ptr
<ToolOutputFile
> Out
=
472 GetOutputStream(TheTarget
->getName(), TheTriple
.getOS(), argv
[0]);
475 std::unique_ptr
<ToolOutputFile
> DwoOut
;
476 if (!SplitDwarfOutputFile
.empty()) {
478 DwoOut
= llvm::make_unique
<ToolOutputFile
>(SplitDwarfOutputFile
, EC
,
481 WithColor::error(errs(), argv
[0]) << EC
.message() << '\n';
486 // Build up all of the passes that we want to do to the module.
487 legacy::PassManager PM
;
489 // Add an appropriate TargetLibraryInfo pass for the module's triple.
490 TargetLibraryInfoImpl
TLII(Triple(M
->getTargetTriple()));
492 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
493 if (DisableSimplifyLibCalls
)
494 TLII
.disableAllFunctions();
495 PM
.add(new TargetLibraryInfoWrapperPass(TLII
));
497 // Add the target data from the target machine, if it exists, or the module.
498 M
->setDataLayout(Target
->createDataLayout());
500 // This needs to be done after setting datalayout since it calls verifier
501 // to check debug info whereas verifier relies on correct datalayout.
502 UpgradeDebugInfo(*M
);
504 // Verify module immediately to catch problems before doInitialization() is
505 // called on any passes.
506 if (!NoVerify
&& verifyModule(*M
, &errs())) {
508 (Twine(argv
[0]) + Twine(": ") + Twine(InputFilename
)).str();
509 WithColor::error(errs(), Prefix
) << "input module is broken!\n";
513 // Override function attributes based on CPUStr, FeaturesStr, and command line
515 setFunctionAttributes(CPUStr
, FeaturesStr
, *M
);
517 if (RelaxAll
.getNumOccurrences() > 0 &&
518 FileType
!= TargetMachine::CGFT_ObjectFile
)
519 WithColor::warning(errs(), argv
[0])
520 << ": warning: ignoring -mc-relax-all because filetype != obj";
523 raw_pwrite_stream
*OS
= &Out
->os();
525 // Manually do the buffering rather than using buffer_ostream,
526 // so we can memcmp the contents in CompileTwice mode
527 SmallVector
<char, 0> Buffer
;
528 std::unique_ptr
<raw_svector_ostream
> BOS
;
529 if ((FileType
!= TargetMachine::CGFT_AssemblyFile
&&
530 !Out
->os().supportsSeeking()) ||
532 BOS
= make_unique
<raw_svector_ostream
>(Buffer
);
536 const char *argv0
= argv
[0];
537 LLVMTargetMachine
&LLVMTM
= static_cast<LLVMTargetMachine
&>(*Target
);
538 MachineModuleInfo
*MMI
= new MachineModuleInfo(&LLVMTM
);
540 // Construct a custom pass pipeline that starts after instruction
542 if (!RunPassNames
->empty()) {
544 WithColor::warning(errs(), argv
[0])
545 << "run-pass is for .mir file only.\n";
548 TargetPassConfig
&TPC
= *LLVMTM
.createPassConfig(PM
);
549 if (TPC
.hasLimitedCodeGenPipeline()) {
550 WithColor::warning(errs(), argv
[0])
551 << "run-pass cannot be used with "
552 << TPC
.getLimitedCodeGenPipelineReason(" and ") << ".\n";
556 TPC
.setDisableVerify(NoVerify
);
559 TPC
.printAndVerify("");
560 for (const std::string
&RunPassName
: *RunPassNames
) {
561 if (addPass(PM
, argv0
, RunPassName
, TPC
))
564 TPC
.setInitialized();
565 PM
.add(createPrintMIRPass(*OS
));
566 PM
.add(createFreeMachineFunctionPass());
567 } else if (Target
->addPassesToEmitFile(PM
, *OS
,
568 DwoOut
? &DwoOut
->os() : nullptr,
569 FileType
, NoVerify
, MMI
)) {
570 WithColor::warning(errs(), argv
[0])
571 << "target does not support generation of this"
577 assert(MMI
&& "Forgot to create MMI?");
578 if (MIR
->parseMachineFunctions(*M
, *MMI
))
582 // Before executing passes, print the final values of the LLVM options.
583 cl::PrintOptionValues();
585 // If requested, run the pass manager over the same module again,
586 // to catch any bugs due to persistent state in the passes. Note that
587 // opt has the same functionality, so it may be worth abstracting this out
589 SmallVector
<char, 0> CompileTwiceBuffer
;
591 std::unique_ptr
<Module
> M2(llvm::CloneModule(*M
));
593 CompileTwiceBuffer
= Buffer
;
600 ((const LLCDiagnosticHandler
*)(Context
.getDiagHandlerPtr()))->HasError
;
604 // Compare the two outputs and make sure they're the same
606 if (Buffer
.size() != CompileTwiceBuffer
.size() ||
607 (memcmp(Buffer
.data(), CompileTwiceBuffer
.data(), Buffer
.size()) !=
610 << "Running the pass manager twice changed the output.\n"
611 "Writing the result of the second run to the specified output\n"
612 "To generate the one-run comparison binary, just run without\n"
613 "the compile-twice option\n";