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/MIR/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;
215 bool SkipModule = MCPU == "help" ||
216 (!MAttrs.empty() && MAttrs.front() == "help");
218 // If user just wants to list available options, skip module loading
220 if (StringRef(InputFilename).endswith_lower(".mir"))
221 M = parseMIRFile(InputFilename, Err, Context);
223 M = parseIRFile(InputFilename, Err, Context);
225 Err.print(argv[0], errs());
229 // Verify module immediately to catch problems before doInitialization() is
230 // called on any passes.
231 if (!NoVerify && verifyModule(*M, &errs())) {
232 errs() << argv[0] << ": " << InputFilename
233 << ": error: input module is broken!\n";
237 // If we are supposed to override the target triple, do so now.
238 if (!TargetTriple.empty())
239 M->setTargetTriple(Triple::normalize(TargetTriple));
240 TheTriple = Triple(M->getTargetTriple());
242 TheTriple = Triple(Triple::normalize(TargetTriple));
245 if (TheTriple.getTriple().empty())
246 TheTriple.setTriple(sys::getDefaultTargetTriple());
248 // Get the target specific parser.
250 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
253 errs() << argv[0] << ": " << Error;
257 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
259 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
262 errs() << argv[0] << ": invalid optimization level.\n";
265 case '0': OLvl = CodeGenOpt::None; break;
266 case '1': OLvl = CodeGenOpt::Less; break;
267 case '2': OLvl = CodeGenOpt::Default; break;
268 case '3': OLvl = CodeGenOpt::Aggressive; break;
271 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
272 Options.DisableIntegratedAS = NoIntegratedAssembler;
273 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
274 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
275 Options.MCOptions.AsmVerbose = AsmVerbose;
277 std::unique_ptr<TargetMachine> Target(
278 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
279 Options, RelocModel, CMModel, OLvl));
281 assert(Target && "Could not allocate target machine!");
283 // If we don't have a module then just exit now. We do this down
284 // here since the CPU/Feature help is underneath the target machine
289 assert(M && "Should have exited if we didn't have a module!");
290 if (FloatABIForCalls != FloatABI::Default)
291 Options.FloatABIType = FloatABIForCalls;
293 // Figure out where we are going to send the output.
294 std::unique_ptr<tool_output_file> Out =
295 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
298 // Build up all of the passes that we want to do to the module.
299 legacy::PassManager PM;
301 // Add an appropriate TargetLibraryInfo pass for the module's triple.
302 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
304 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
305 if (DisableSimplifyLibCalls)
306 TLII.disableAllFunctions();
307 PM.add(new TargetLibraryInfoWrapperPass(TLII));
309 // Add the target data from the target machine, if it exists, or the module.
310 if (const DataLayout *DL = Target->getDataLayout())
311 M->setDataLayout(*DL);
313 // Override function attributes.
314 overrideFunctionAttributes(CPUStr, FeaturesStr, *M);
316 if (RelaxAll.getNumOccurrences() > 0 &&
317 FileType != TargetMachine::CGFT_ObjectFile)
319 << ": warning: ignoring -mc-relax-all because filetype != obj";
322 raw_pwrite_stream *OS = &Out->os();
323 std::unique_ptr<buffer_ostream> BOS;
324 if (FileType != TargetMachine::CGFT_AssemblyFile &&
325 !Out->os().supportsSeeking()) {
326 BOS = make_unique<buffer_ostream>(*OS);
330 AnalysisID StartAfterID = nullptr;
331 AnalysisID StopAfterID = nullptr;
332 const PassRegistry *PR = PassRegistry::getPassRegistry();
333 if (!StartAfter.empty()) {
334 const PassInfo *PI = PR->getPassInfo(StartAfter);
336 errs() << argv[0] << ": start-after pass is not registered.\n";
339 StartAfterID = PI->getTypeInfo();
341 if (!StopAfter.empty()) {
342 const PassInfo *PI = PR->getPassInfo(StopAfter);
344 errs() << argv[0] << ": stop-after pass is not registered.\n";
347 StopAfterID = PI->getTypeInfo();
350 // Ask the target to add backend passes as necessary.
351 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartAfterID,
353 errs() << argv[0] << ": target does not support generation of this"
358 // Before executing passes, print the final values of the LLVM options.
359 cl::PrintOptionValues();