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/IR/LLVMContext.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/Pass.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetMachine.h"
45 // General options for llc. Other pass-specific options are specified
46 // within the corresponding llc passes, and target-specific options
47 // and back-end code generation options are specified with the target machine.
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
55 static cl::opt<unsigned>
56 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
58 cl::desc("Repeat compilation N times for timing"));
60 // Determine optimization level.
63 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
69 static cl::opt<std::string>
70 TargetTriple("mtriple", cl::desc("Override target triple for module"));
72 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
73 cl::desc("Do not verify input module"));
76 DisableSimplifyLibCalls("disable-simplify-libcalls",
77 cl::desc("Disable simplify-libcalls"),
80 static int compileModule(char**, LLVMContext&);
82 // GetFileNameRoot - Helper function to get the basename of a filename.
83 static inline std::string
84 GetFileNameRoot(const std::string &InputFilename) {
85 std::string IFN = InputFilename;
86 std::string outputFilename;
87 int Len = IFN.length();
90 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
91 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
92 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
96 return outputFilename;
99 static tool_output_file *GetOutputStream(const char *TargetName,
101 const char *ProgName) {
102 // If we don't yet have an output filename, make one.
103 if (OutputFilename.empty()) {
104 if (InputFilename == "-")
105 OutputFilename = "-";
107 OutputFilename = GetFileNameRoot(InputFilename);
110 case TargetMachine::CGFT_AssemblyFile:
111 if (TargetName[0] == 'c') {
112 if (TargetName[1] == 0)
113 OutputFilename += ".cbe.c";
114 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
115 OutputFilename += ".cpp";
117 OutputFilename += ".s";
119 OutputFilename += ".s";
121 case TargetMachine::CGFT_ObjectFile:
122 if (OS == Triple::Win32)
123 OutputFilename += ".obj";
125 OutputFilename += ".o";
127 case TargetMachine::CGFT_Null:
128 OutputFilename += ".null";
134 // Decide if we need "binary" output.
137 case TargetMachine::CGFT_AssemblyFile:
139 case TargetMachine::CGFT_ObjectFile:
140 case TargetMachine::CGFT_Null:
147 unsigned OpenFlags = 0;
148 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
149 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
151 if (!error.empty()) {
152 errs() << error << '\n';
160 // main - Entry point for the llc compiler.
162 int main(int argc, char **argv) {
163 sys::PrintStackTraceOnErrorSignal();
164 PrettyStackTraceProgram X(argc, argv);
166 // Enable debug stream buffering.
167 EnableDebugBuffering = true;
169 LLVMContext &Context = getGlobalContext();
170 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
172 // Initialize targets first, so that --version shows registered targets.
173 InitializeAllTargets();
174 InitializeAllTargetMCs();
175 InitializeAllAsmPrinters();
176 InitializeAllAsmParsers();
178 // Initialize codegen and IR passes used by llc so that the -print-after,
179 // -print-before, and -stop-after options work.
180 PassRegistry *Registry = PassRegistry::getPassRegistry();
181 initializeCore(*Registry);
182 initializeCodeGen(*Registry);
183 initializeLoopStrengthReducePass(*Registry);
184 initializeLowerIntrinsicsPass(*Registry);
185 initializeUnreachableBlockElimPass(*Registry);
187 // Register the target printer for --version.
188 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
190 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
192 // Compile the module TimeCompilations times to give better compile time
194 for (unsigned I = TimeCompilations; I; --I)
195 if (int RetVal = compileModule(argv, Context))
200 static int compileModule(char **argv, LLVMContext &Context) {
201 // Load the module to be compiled...
207 bool SkipModule = MCPU == "help" ||
208 (!MAttrs.empty() && MAttrs.front() == "help");
210 // If user just wants to list available options, skip module loading
212 M.reset(ParseIRFile(InputFilename, Err, Context));
215 Err.print(argv[0], errs());
219 // If we are supposed to override the target triple, do so now.
220 if (!TargetTriple.empty())
221 mod->setTargetTriple(Triple::normalize(TargetTriple));
222 TheTriple = Triple(mod->getTargetTriple());
224 TheTriple = Triple(Triple::normalize(TargetTriple));
227 if (TheTriple.getTriple().empty())
228 TheTriple.setTriple(sys::getDefaultTargetTriple());
230 // Get the target specific parser.
232 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
235 errs() << argv[0] << ": " << Error;
239 // Package up features to be passed to target/subtarget
240 std::string FeaturesStr;
242 SubtargetFeatures Features;
243 for (unsigned i = 0; i != MAttrs.size(); ++i)
244 Features.AddFeature(MAttrs[i]);
245 FeaturesStr = Features.getString();
248 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
251 errs() << argv[0] << ": invalid optimization level.\n";
254 case '0': OLvl = CodeGenOpt::None; break;
255 case '1': OLvl = CodeGenOpt::Less; break;
256 case '2': OLvl = CodeGenOpt::Default; break;
257 case '3': OLvl = CodeGenOpt::Aggressive; break;
260 TargetOptions Options;
261 Options.LessPreciseFPMADOption = EnableFPMAD;
262 Options.NoFramePointerElim = DisableFPElim;
263 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
264 Options.AllowFPOpFusion = FuseFPOps;
265 Options.UnsafeFPMath = EnableUnsafeFPMath;
266 Options.NoInfsFPMath = EnableNoInfsFPMath;
267 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
268 Options.HonorSignDependentRoundingFPMathOption =
269 EnableHonorSignDependentRoundingFPMath;
270 Options.UseSoftFloat = GenerateSoftFloatCalls;
271 if (FloatABIForCalls != FloatABI::Default)
272 Options.FloatABIType = FloatABIForCalls;
273 Options.NoZerosInBSS = DontPlaceZerosInBSS;
274 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
275 Options.DisableTailCalls = DisableTailCalls;
276 Options.StackAlignmentOverride = OverrideStackAlignment;
277 Options.RealignStack = EnableRealignStack;
278 Options.TrapFuncName = TrapFuncName;
279 Options.PositionIndependentExecutable = EnablePIE;
280 Options.EnableSegmentedStacks = SegmentedStacks;
281 Options.UseInitArray = UseInitArray;
282 Options.SSPBufferSize = SSPBufferSize;
284 OwningPtr<TargetMachine>
285 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
286 MCPU, FeaturesStr, Options,
287 RelocModel, CMModel, OLvl));
288 assert(target.get() && "Could not allocate target machine!");
289 assert(mod && "Should have exited after outputting help!");
290 TargetMachine &Target = *target.get();
293 Target.setMCUseLoc(false);
296 Target.setMCUseCFI(false);
298 if (EnableDwarfDirectory)
299 Target.setMCUseDwarfDirectory(true);
301 if (GenerateSoftFloatCalls)
302 FloatABIForCalls = FloatABI::Soft;
304 // Disable .loc support for older OS X versions.
305 if (TheTriple.isMacOSX() &&
306 TheTriple.isMacOSXVersionLT(10, 6))
307 Target.setMCUseLoc(false);
309 // Figure out where we are going to send the output.
310 OwningPtr<tool_output_file> Out
311 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
314 // Build up all of the passes that we want to do to the module.
317 // Add an appropriate TargetLibraryInfo pass for the module's triple.
318 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
319 if (DisableSimplifyLibCalls)
320 TLI->disableAllFunctions();
323 // Add intenal analysis passes from the target machine.
324 Target.addAnalysisPasses(PM);
326 // Add the target data from the target machine, if it exists, or the module.
327 if (const DataLayout *TD = Target.getDataLayout())
328 PM.add(new DataLayout(*TD));
330 PM.add(new DataLayout(mod));
332 // Override default to generate verbose assembly.
333 Target.setAsmVerbosityDefault(true);
336 if (FileType != TargetMachine::CGFT_ObjectFile)
338 << ": warning: ignoring -mc-relax-all because filetype != obj";
340 Target.setMCRelaxAll(true);
344 formatted_raw_ostream FOS(Out->os());
346 AnalysisID StartAfterID = 0;
347 AnalysisID StopAfterID = 0;
348 const PassRegistry *PR = PassRegistry::getPassRegistry();
349 if (!StartAfter.empty()) {
350 const PassInfo *PI = PR->getPassInfo(StartAfter);
352 errs() << argv[0] << ": start-after pass is not registered.\n";
355 StartAfterID = PI->getTypeInfo();
357 if (!StopAfter.empty()) {
358 const PassInfo *PI = PR->getPassInfo(StopAfter);
360 errs() << argv[0] << ": stop-after pass is not registered.\n";
363 StopAfterID = PI->getTypeInfo();
366 // Ask the target to add backend passes as necessary.
367 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
368 StartAfterID, StopAfterID)) {
369 errs() << argv[0] << ": target does not support generation of this"
374 // Before executing passes, print the final values of the LLVM options.
375 cl::PrintOptionValues();