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/FormattedStream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/PluginLoader.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetMachine.h"
46 // General options for llc. Other pass-specific options are specified
47 // within the corresponding llc passes, and target-specific options
48 // and back-end code generation options are specified with the target machine.
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
56 static cl::opt<unsigned>
57 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
59 cl::desc("Repeat compilation N times for timing"));
62 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
63 cl::desc("Disable integrated assembler"));
65 // Determine optimization level.
68 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
74 static cl::opt<std::string>
75 TargetTriple("mtriple", cl::desc("Override target triple for module"));
77 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
78 cl::desc("Do not verify input module"));
81 DisableSimplifyLibCalls("disable-simplify-libcalls",
82 cl::desc("Disable simplify-libcalls"),
85 static int compileModule(char**, LLVMContext&);
87 // GetFileNameRoot - Helper function to get the basename of a filename.
88 static inline std::string
89 GetFileNameRoot(const std::string &InputFilename) {
90 std::string IFN = InputFilename;
91 std::string outputFilename;
92 int Len = IFN.length();
95 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
96 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
97 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
101 return outputFilename;
104 static tool_output_file *GetOutputStream(const char *TargetName,
106 const char *ProgName) {
107 // If we don't yet have an output filename, make one.
108 if (OutputFilename.empty()) {
109 if (InputFilename == "-")
110 OutputFilename = "-";
112 OutputFilename = GetFileNameRoot(InputFilename);
115 case TargetMachine::CGFT_AssemblyFile:
116 if (TargetName[0] == 'c') {
117 if (TargetName[1] == 0)
118 OutputFilename += ".cbe.c";
119 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
120 OutputFilename += ".cpp";
122 OutputFilename += ".s";
124 OutputFilename += ".s";
126 case TargetMachine::CGFT_ObjectFile:
127 if (OS == Triple::Win32)
128 OutputFilename += ".obj";
130 OutputFilename += ".o";
132 case TargetMachine::CGFT_Null:
133 OutputFilename += ".null";
139 // Decide if we need "binary" output.
142 case TargetMachine::CGFT_AssemblyFile:
144 case TargetMachine::CGFT_ObjectFile:
145 case TargetMachine::CGFT_Null:
152 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
154 OpenFlags |= sys::fs::F_Text;
155 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
157 if (!error.empty()) {
158 errs() << error << '\n';
166 // main - Entry point for the llc compiler.
168 int main(int argc, char **argv) {
169 sys::PrintStackTraceOnErrorSignal();
170 PrettyStackTraceProgram X(argc, argv);
172 // Enable debug stream buffering.
173 EnableDebugBuffering = true;
175 LLVMContext &Context = getGlobalContext();
176 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
178 // Initialize targets first, so that --version shows registered targets.
179 InitializeAllTargets();
180 InitializeAllTargetMCs();
181 InitializeAllAsmPrinters();
182 InitializeAllAsmParsers();
184 // Initialize codegen and IR passes used by llc so that the -print-after,
185 // -print-before, and -stop-after options work.
186 PassRegistry *Registry = PassRegistry::getPassRegistry();
187 initializeCore(*Registry);
188 initializeCodeGen(*Registry);
189 initializeLoopStrengthReducePass(*Registry);
190 initializeLowerIntrinsicsPass(*Registry);
191 initializeUnreachableBlockElimPass(*Registry);
193 // Register the target printer for --version.
194 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
198 // Compile the module TimeCompilations times to give better compile time
200 for (unsigned I = TimeCompilations; I; --I)
201 if (int RetVal = compileModule(argv, Context))
206 static int compileModule(char **argv, LLVMContext &Context) {
207 // Load the module to be compiled...
213 bool SkipModule = MCPU == "help" ||
214 (!MAttrs.empty() && MAttrs.front() == "help");
216 // If user just wants to list available options, skip module loading
218 M.reset(ParseIRFile(InputFilename, Err, Context));
221 Err.print(argv[0], errs());
225 // If we are supposed to override the target triple, do so now.
226 if (!TargetTriple.empty())
227 mod->setTargetTriple(Triple::normalize(TargetTriple));
228 TheTriple = Triple(mod->getTargetTriple());
230 TheTriple = Triple(Triple::normalize(TargetTriple));
233 if (TheTriple.getTriple().empty())
234 TheTriple.setTriple(sys::getDefaultTargetTriple());
236 // Get the target specific parser.
238 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
241 errs() << argv[0] << ": " << Error;
245 // Package up features to be passed to target/subtarget
246 std::string FeaturesStr;
248 SubtargetFeatures Features;
249 for (unsigned i = 0; i != MAttrs.size(); ++i)
250 Features.AddFeature(MAttrs[i]);
251 FeaturesStr = Features.getString();
254 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
257 errs() << argv[0] << ": invalid optimization level.\n";
260 case '0': OLvl = CodeGenOpt::None; break;
261 case '1': OLvl = CodeGenOpt::Less; break;
262 case '2': OLvl = CodeGenOpt::Default; break;
263 case '3': OLvl = CodeGenOpt::Aggressive; break;
266 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
267 Options.DisableIntegratedAS = NoIntegratedAssembler;
269 OwningPtr<TargetMachine>
270 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
271 MCPU, FeaturesStr, Options,
272 RelocModel, CMModel, OLvl));
273 assert(target.get() && "Could not allocate target machine!");
274 assert(mod && "Should have exited after outputting help!");
275 TargetMachine &Target = *target.get();
278 Target.setMCUseCFI(false);
280 if (EnableDwarfDirectory)
281 Target.setMCUseDwarfDirectory(true);
283 if (GenerateSoftFloatCalls)
284 FloatABIForCalls = FloatABI::Soft;
286 // Figure out where we are going to send the output.
287 OwningPtr<tool_output_file> Out
288 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
291 // Build up all of the passes that we want to do to the module.
294 // Add an appropriate TargetLibraryInfo pass for the module's triple.
295 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
296 if (DisableSimplifyLibCalls)
297 TLI->disableAllFunctions();
300 // Add the target data from the target machine, if it exists, or the module.
301 if (const DataLayout *DL = Target.getDataLayout())
302 mod->setDataLayout(DL);
303 PM.add(new DataLayoutPass(mod));
305 // Override default to generate verbose assembly.
306 Target.setAsmVerbosityDefault(true);
309 if (FileType != TargetMachine::CGFT_ObjectFile)
311 << ": warning: ignoring -mc-relax-all because filetype != obj";
313 Target.setMCRelaxAll(true);
317 formatted_raw_ostream FOS(Out->os());
319 AnalysisID StartAfterID = 0;
320 AnalysisID StopAfterID = 0;
321 const PassRegistry *PR = PassRegistry::getPassRegistry();
322 if (!StartAfter.empty()) {
323 const PassInfo *PI = PR->getPassInfo(StartAfter);
325 errs() << argv[0] << ": start-after pass is not registered.\n";
328 StartAfterID = PI->getTypeInfo();
330 if (!StopAfter.empty()) {
331 const PassInfo *PI = PR->getPassInfo(StopAfter);
333 errs() << argv[0] << ": stop-after pass is not registered.\n";
336 StopAfterID = PI->getTypeInfo();
339 // Ask the target to add backend passes as necessary.
340 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
341 StartAfterID, StopAfterID)) {
342 errs() << argv[0] << ": target does not support generation of this"
347 // Before executing passes, print the final values of the LLVM options.
348 cl::PrintOptionValues();