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/Triple.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
48 // General options for llc. Other pass-specific options are specified
49 // within the corresponding llc passes, and target-specific options
50 // and back-end code generation options are specified with the target machine.
52 static cl::opt<std::string>
53 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
58 static cl::opt<unsigned>
59 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
61 cl::desc("Repeat compilation N times for timing"));
64 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
65 cl::desc("Disable integrated assembler"));
67 // Determine optimization level.
70 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
76 static cl::opt<std::string>
77 TargetTriple("mtriple", cl::desc("Override target triple for module"));
79 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
80 cl::desc("Do not verify input module"));
82 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
83 cl::desc("Disable simplify-libcalls"));
85 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
86 cl::desc("Show encoding in .s output"));
88 static cl::opt<bool> EnableDwarfDirectory(
89 "enable-dwarf-directory", cl::Hidden,
90 cl::desc("Use .file directives with an explicit directory."));
92 static cl::opt<bool> AsmVerbose("asm-verbose",
93 cl::desc("Add comments to directives."),
96 static int compileModule(char **, LLVMContext &);
98 // GetFileNameRoot - Helper function to get the basename of a filename.
99 static inline std::string
100 GetFileNameRoot(const std::string &InputFilename) {
101 std::string IFN = InputFilename;
102 std::string outputFilename;
103 int Len = IFN.length();
106 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
107 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
108 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
110 outputFilename = IFN;
112 return outputFilename;
115 static tool_output_file *GetOutputStream(const char *TargetName,
117 const char *ProgName) {
118 // If we don't yet have an output filename, make one.
119 if (OutputFilename.empty()) {
120 if (InputFilename == "-")
121 OutputFilename = "-";
123 OutputFilename = GetFileNameRoot(InputFilename);
126 case TargetMachine::CGFT_AssemblyFile:
127 if (TargetName[0] == 'c') {
128 if (TargetName[1] == 0)
129 OutputFilename += ".cbe.c";
130 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
131 OutputFilename += ".cpp";
133 OutputFilename += ".s";
135 OutputFilename += ".s";
137 case TargetMachine::CGFT_ObjectFile:
138 if (OS == Triple::Win32)
139 OutputFilename += ".obj";
141 OutputFilename += ".o";
143 case TargetMachine::CGFT_Null:
144 OutputFilename += ".null";
150 // Decide if we need "binary" output.
153 case TargetMachine::CGFT_AssemblyFile:
155 case TargetMachine::CGFT_ObjectFile:
156 case TargetMachine::CGFT_Null:
163 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
165 OpenFlags |= sys::fs::F_Text;
166 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
168 if (!error.empty()) {
169 errs() << error << '\n';
177 // main - Entry point for the llc compiler.
179 int main(int argc, char **argv) {
180 sys::PrintStackTraceOnErrorSignal();
181 PrettyStackTraceProgram X(argc, argv);
183 // Enable debug stream buffering.
184 EnableDebugBuffering = true;
186 LLVMContext &Context = getGlobalContext();
187 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
189 // Initialize targets first, so that --version shows registered targets.
190 InitializeAllTargets();
191 InitializeAllTargetMCs();
192 InitializeAllAsmPrinters();
193 InitializeAllAsmParsers();
195 // Initialize codegen and IR passes used by llc so that the -print-after,
196 // -print-before, and -stop-after options work.
197 PassRegistry *Registry = PassRegistry::getPassRegistry();
198 initializeCore(*Registry);
199 initializeCodeGen(*Registry);
200 initializeLoopStrengthReducePass(*Registry);
201 initializeLowerIntrinsicsPass(*Registry);
202 initializeUnreachableBlockElimPass(*Registry);
204 // Register the target printer for --version.
205 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
207 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
209 // Compile the module TimeCompilations times to give better compile time
211 for (unsigned I = TimeCompilations; I; --I)
212 if (int RetVal = compileModule(argv, Context))
217 static int compileModule(char **argv, LLVMContext &Context) {
218 // Load the module to be compiled...
220 std::unique_ptr<Module> M;
221 Module *mod = nullptr;
224 bool SkipModule = MCPU == "help" ||
225 (!MAttrs.empty() && MAttrs.front() == "help");
227 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
228 // this will set the CPU to an empty string which tells the target to
229 // pick a basic default.
230 if (MCPU == "native")
231 MCPU = sys::getHostCPUName();
233 // If user just wants to list available options, skip module loading
235 M.reset(ParseIRFile(InputFilename, Err, Context));
237 if (mod == nullptr) {
238 Err.print(argv[0], errs());
242 // If we are supposed to override the target triple, do so now.
243 if (!TargetTriple.empty())
244 mod->setTargetTriple(Triple::normalize(TargetTriple));
245 TheTriple = Triple(mod->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 // Package up features to be passed to target/subtarget
263 std::string FeaturesStr;
265 SubtargetFeatures Features;
266 for (unsigned i = 0; i != MAttrs.size(); ++i)
267 Features.AddFeature(MAttrs[i]);
268 FeaturesStr = Features.getString();
271 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
274 errs() << argv[0] << ": invalid optimization level.\n";
277 case '0': OLvl = CodeGenOpt::None; break;
278 case '1': OLvl = CodeGenOpt::Less; break;
279 case '2': OLvl = CodeGenOpt::Default; break;
280 case '3': OLvl = CodeGenOpt::Aggressive; break;
283 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
284 Options.DisableIntegratedAS = NoIntegratedAssembler;
285 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
286 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
287 Options.MCOptions.AsmVerbose = AsmVerbose;
289 std::unique_ptr<TargetMachine> target(
290 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
291 Options, RelocModel, CMModel, OLvl));
292 assert(target.get() && "Could not allocate target machine!");
294 // If we don't have a module then just exit now. We do this down
295 // here since the CPU/Feature help is underneath the target machine
300 assert(mod && "Should have exited if we didn't have a module!");
301 TargetMachine &Target = *target.get();
303 if (GenerateSoftFloatCalls)
304 FloatABIForCalls = FloatABI::Soft;
306 // Figure out where we are going to send the output.
307 std::unique_ptr<tool_output_file> Out(
308 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
311 // Build up all of the passes that we want to do to the module.
314 // Add an appropriate TargetLibraryInfo pass for the module's triple.
315 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
316 if (DisableSimplifyLibCalls)
317 TLI->disableAllFunctions();
320 // Add the target data from the target machine, if it exists, or the module.
321 if (const DataLayout *DL = Target.getSubtargetImpl()->getDataLayout())
322 mod->setDataLayout(DL);
323 PM.add(new DataLayoutPass(mod));
325 if (RelaxAll.getNumOccurrences() > 0 &&
326 FileType != TargetMachine::CGFT_ObjectFile)
328 << ": warning: ignoring -mc-relax-all because filetype != obj";
331 formatted_raw_ostream FOS(Out->os());
333 AnalysisID StartAfterID = nullptr;
334 AnalysisID StopAfterID = nullptr;
335 const PassRegistry *PR = PassRegistry::getPassRegistry();
336 if (!StartAfter.empty()) {
337 const PassInfo *PI = PR->getPassInfo(StartAfter);
339 errs() << argv[0] << ": start-after pass is not registered.\n";
342 StartAfterID = PI->getTypeInfo();
344 if (!StopAfter.empty()) {
345 const PassInfo *PI = PR->getPassInfo(StopAfter);
347 errs() << argv[0] << ": stop-after pass is not registered.\n";
350 StopAfterID = PI->getTypeInfo();
353 // Ask the target to add backend passes as necessary.
354 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
355 StartAfterID, StopAfterID)) {
356 errs() << argv[0] << ": target does not support generation of this"
361 // Before executing passes, print the final values of the LLVM options.
362 cl::PrintOptionValues();