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 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/CodeGen/MIRParser/MIRParser.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/IRPrintingPasses.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/LegacyPassManager.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/PluginLoader.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
51 // General options for llc. Other pass-specific options are specified
52 // within the corresponding llc passes, and target-specific options
53 // and back-end code generation options are specified with the target machine.
55 static cl::opt<std::string>
56 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
58 static cl::opt<std::string>
59 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
61 static cl::opt<unsigned>
62 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
64 cl::desc("Repeat compilation N times for timing"));
67 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
68 cl::desc("Disable integrated assembler"));
70 // Determine optimization level.
73 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
79 static cl::opt<std::string>
80 TargetTriple("mtriple", cl::desc("Override target triple for module"));
82 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
83 cl::desc("Do not verify input module"));
85 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
86 cl::desc("Disable simplify-libcalls"));
88 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
89 cl::desc("Show encoding in .s output"));
91 static cl::opt<bool> EnableDwarfDirectory(
92 "enable-dwarf-directory", cl::Hidden,
93 cl::desc("Use .file directives with an explicit directory."));
95 static cl::opt<bool> AsmVerbose("asm-verbose",
96 cl::desc("Add comments to directives."),
99 static int compileModule(char **, LLVMContext &);
101 static std::unique_ptr<tool_output_file>
102 GetOutputStream(const char *TargetName, Triple::OSType OS,
103 const char *ProgName) {
104 // If we don't yet have an output filename, make one.
105 if (OutputFilename.empty()) {
106 if (InputFilename == "-")
107 OutputFilename = "-";
109 // If InputFilename ends in .bc or .ll, remove it.
110 StringRef IFN = InputFilename;
111 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
112 OutputFilename = IFN.drop_back(3);
113 else if (IFN.endswith(".mir"))
114 OutputFilename = IFN.drop_back(4);
116 OutputFilename = IFN;
119 case TargetMachine::CGFT_AssemblyFile:
120 if (TargetName[0] == 'c') {
121 if (TargetName[1] == 0)
122 OutputFilename += ".cbe.c";
123 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
124 OutputFilename += ".cpp";
126 OutputFilename += ".s";
128 OutputFilename += ".s";
130 case TargetMachine::CGFT_ObjectFile:
131 if (OS == Triple::Win32)
132 OutputFilename += ".obj";
134 OutputFilename += ".o";
136 case TargetMachine::CGFT_Null:
137 OutputFilename += ".null";
143 // Decide if we need "binary" output.
146 case TargetMachine::CGFT_AssemblyFile:
148 case TargetMachine::CGFT_ObjectFile:
149 case TargetMachine::CGFT_Null:
156 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
158 OpenFlags |= sys::fs::F_Text;
159 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
162 errs() << EC.message() << '\n';
169 // main - Entry point for the llc compiler.
171 int main(int argc, char **argv) {
172 sys::PrintStackTraceOnErrorSignal();
173 PrettyStackTraceProgram X(argc, argv);
175 // Enable debug stream buffering.
176 EnableDebugBuffering = true;
178 LLVMContext &Context = getGlobalContext();
179 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
181 // Initialize targets first, so that --version shows registered targets.
182 InitializeAllTargets();
183 InitializeAllTargetMCs();
184 InitializeAllAsmPrinters();
185 InitializeAllAsmParsers();
187 // Initialize codegen and IR passes used by llc so that the -print-after,
188 // -print-before, and -stop-after options work.
189 PassRegistry *Registry = PassRegistry::getPassRegistry();
190 initializeCore(*Registry);
191 initializeCodeGen(*Registry);
192 initializeLoopStrengthReducePass(*Registry);
193 initializeLowerIntrinsicsPass(*Registry);
194 initializeUnreachableBlockElimPass(*Registry);
196 // Register the target printer for --version.
197 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
199 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
201 // Compile the module TimeCompilations times to give better compile time
203 for (unsigned I = TimeCompilations; I; --I)
204 if (int RetVal = compileModule(argv, Context))
209 static int compileModule(char **argv, LLVMContext &Context) {
210 // Load the module to be compiled...
212 std::unique_ptr<Module> M;
213 std::unique_ptr<MIRParser> MIR;
216 bool SkipModule = MCPU == "help" ||
217 (!MAttrs.empty() && MAttrs.front() == "help");
219 // If user just wants to list available options, skip module loading
221 if (StringRef(InputFilename).endswith_lower(".mir")) {
222 MIR = createMIRParserFromFile(InputFilename, Err, Context);
224 M = MIR->parseLLVMModule();
225 assert(M && "parseLLVMModule should exit on failure");
228 M = parseIRFile(InputFilename, Err, Context);
230 Err.print(argv[0], errs());
234 // Verify module immediately to catch problems before doInitialization() is
235 // called on any passes.
236 if (!NoVerify && verifyModule(*M, &errs())) {
237 errs() << argv[0] << ": " << InputFilename
238 << ": error: input module is broken!\n";
242 // If we are supposed to override the target triple, do so now.
243 if (!TargetTriple.empty())
244 M->setTargetTriple(Triple::normalize(TargetTriple));
245 TheTriple = Triple(M->getTargetTriple());
247 TheTriple = Triple(Triple::normalize(TargetTriple));
250 if (TheTriple.getTriple().empty())
251 TheTriple.setTriple(sys::getDefaultTargetTriple());
253 // Get the target specific parser.
255 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
258 errs() << argv[0] << ": " << Error;
262 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
264 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
267 errs() << argv[0] << ": invalid optimization level.\n";
270 case '0': OLvl = CodeGenOpt::None; break;
271 case '1': OLvl = CodeGenOpt::Less; break;
272 case '2': OLvl = CodeGenOpt::Default; break;
273 case '3': OLvl = CodeGenOpt::Aggressive; break;
276 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
277 Options.DisableIntegratedAS = NoIntegratedAssembler;
278 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
279 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
280 Options.MCOptions.AsmVerbose = AsmVerbose;
282 std::unique_ptr<TargetMachine> Target(
283 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
284 Options, RelocModel, CMModel, OLvl));
286 assert(Target && "Could not allocate target machine!");
288 // If we don't have a module then just exit now. We do this down
289 // here since the CPU/Feature help is underneath the target machine
294 assert(M && "Should have exited if we didn't have a module!");
295 if (FloatABIForCalls != FloatABI::Default)
296 Options.FloatABIType = FloatABIForCalls;
298 // Figure out where we are going to send the output.
299 std::unique_ptr<tool_output_file> Out =
300 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
303 // Build up all of the passes that we want to do to the module.
304 legacy::PassManager PM;
306 // Add an appropriate TargetLibraryInfo pass for the module's triple.
307 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
309 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
310 if (DisableSimplifyLibCalls)
311 TLII.disableAllFunctions();
312 PM.add(new TargetLibraryInfoWrapperPass(TLII));
314 // Add the target data from the target machine, if it exists, or the module.
315 M->setDataLayout(Target->createDataLayout());
317 // Override function attributes based on CPUStr, FeaturesStr, and command line
319 setFunctionAttributes(CPUStr, FeaturesStr, *M);
321 if (RelaxAll.getNumOccurrences() > 0 &&
322 FileType != TargetMachine::CGFT_ObjectFile)
324 << ": warning: ignoring -mc-relax-all because filetype != obj";
327 raw_pwrite_stream *OS = &Out->os();
328 std::unique_ptr<buffer_ostream> BOS;
329 if (FileType != TargetMachine::CGFT_AssemblyFile &&
330 !Out->os().supportsSeeking()) {
331 BOS = make_unique<buffer_ostream>(*OS);
335 AnalysisID StartBeforeID = nullptr;
336 AnalysisID StartAfterID = nullptr;
337 AnalysisID StopAfterID = nullptr;
338 const PassRegistry *PR = PassRegistry::getPassRegistry();
339 if (!RunPass.empty()) {
340 if (!StartAfter.empty() || !StopAfter.empty()) {
341 errs() << argv[0] << ": start-after and/or stop-after passes are "
342 "redundant when run-pass is specified.\n";
345 const PassInfo *PI = PR->getPassInfo(RunPass);
347 errs() << argv[0] << ": run-pass pass is not registered.\n";
350 StopAfterID = StartBeforeID = PI->getTypeInfo();
352 if (!StartAfter.empty()) {
353 const PassInfo *PI = PR->getPassInfo(StartAfter);
355 errs() << argv[0] << ": start-after pass is not registered.\n";
358 StartAfterID = PI->getTypeInfo();
360 if (!StopAfter.empty()) {
361 const PassInfo *PI = PR->getPassInfo(StopAfter);
363 errs() << argv[0] << ": stop-after pass is not registered.\n";
366 StopAfterID = PI->getTypeInfo();
370 // Ask the target to add backend passes as necessary.
371 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartBeforeID,
372 StartAfterID, StopAfterID, MIR.get())) {
373 errs() << argv[0] << ": target does not support generation of this"
378 // Before executing passes, print the final values of the LLVM options.
379 cl::PrintOptionValues();