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/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/DataLayout.h"
23 #include "llvm/MC/SubtargetFeature.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/IRReader.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/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Target/TargetLibraryInfo.h"
40 #include "llvm/Target/TargetMachine.h"
44 // General options for llc. Other pass-specific options are specified
45 // within the corresponding llc passes, and target-specific options
46 // and back-end code generation options are specified with the target machine.
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
54 static cl::opt<unsigned>
55 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
57 cl::desc("Repeat compilation N times for timing"));
59 // Determine optimization level.
62 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
68 static cl::opt<std::string>
69 TargetTriple("mtriple", cl::desc("Override target triple for module"));
71 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
72 cl::desc("Do not verify input module"));
75 DisableSimplifyLibCalls("disable-simplify-libcalls",
76 cl::desc("Disable simplify-libcalls"),
79 static int compileModule(char**, LLVMContext&);
81 // GetFileNameRoot - Helper function to get the basename of a filename.
82 static inline std::string
83 GetFileNameRoot(const std::string &InputFilename) {
84 std::string IFN = InputFilename;
85 std::string outputFilename;
86 int Len = IFN.length();
89 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
90 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
91 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
95 return outputFilename;
98 static tool_output_file *GetOutputStream(const char *TargetName,
100 const char *ProgName) {
101 // If we don't yet have an output filename, make one.
102 if (OutputFilename.empty()) {
103 if (InputFilename == "-")
104 OutputFilename = "-";
106 OutputFilename = GetFileNameRoot(InputFilename);
109 case TargetMachine::CGFT_AssemblyFile:
110 if (TargetName[0] == 'c') {
111 if (TargetName[1] == 0)
112 OutputFilename += ".cbe.c";
113 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
114 OutputFilename += ".cpp";
116 OutputFilename += ".s";
118 OutputFilename += ".s";
120 case TargetMachine::CGFT_ObjectFile:
121 if (OS == Triple::Win32)
122 OutputFilename += ".obj";
124 OutputFilename += ".o";
126 case TargetMachine::CGFT_Null:
127 OutputFilename += ".null";
133 // Decide if we need "binary" output.
136 case TargetMachine::CGFT_AssemblyFile:
138 case TargetMachine::CGFT_ObjectFile:
139 case TargetMachine::CGFT_Null:
146 unsigned OpenFlags = 0;
147 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
148 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
150 if (!error.empty()) {
151 errs() << error << '\n';
159 // main - Entry point for the llc compiler.
161 int main(int argc, char **argv) {
162 sys::PrintStackTraceOnErrorSignal();
163 PrettyStackTraceProgram X(argc, argv);
165 // Enable debug stream buffering.
166 EnableDebugBuffering = true;
168 LLVMContext &Context = getGlobalContext();
169 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
171 // Initialize targets first, so that --version shows registered targets.
172 InitializeAllTargets();
173 InitializeAllTargetMCs();
174 InitializeAllAsmPrinters();
175 InitializeAllAsmParsers();
177 // Initialize codegen and IR passes used by llc so that the -print-after,
178 // -print-before, and -stop-after options work.
179 PassRegistry *Registry = PassRegistry::getPassRegistry();
180 initializeCore(*Registry);
181 initializeCodeGen(*Registry);
182 initializeLoopStrengthReducePass(*Registry);
183 initializeLowerIntrinsicsPass(*Registry);
184 initializeUnreachableBlockElimPass(*Registry);
186 // Register the target printer for --version.
187 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
189 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
191 // Compile the module TimeCompilations times to give better compile time
193 for (unsigned I = TimeCompilations; I; --I)
194 if (int RetVal = compileModule(argv, Context))
199 static int compileModule(char **argv, LLVMContext &Context) {
200 // Load the module to be compiled...
202 std::auto_ptr<Module> M;
206 bool SkipModule = MCPU == "help" ||
207 (!MAttrs.empty() && MAttrs.front() == "help");
209 // If user just wants to list available options, skip module loading
211 M.reset(ParseIRFile(InputFilename, Err, Context));
214 Err.print(argv[0], errs());
218 // If we are supposed to override the target triple, do so now.
219 if (!TargetTriple.empty())
220 mod->setTargetTriple(Triple::normalize(TargetTriple));
221 TheTriple = Triple(mod->getTargetTriple());
223 TheTriple = Triple(Triple::normalize(TargetTriple));
226 if (TheTriple.getTriple().empty())
227 TheTriple.setTriple(sys::getDefaultTargetTriple());
229 // Get the target specific parser.
231 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
234 errs() << argv[0] << ": " << Error;
238 // Package up features to be passed to target/subtarget
239 std::string FeaturesStr;
241 SubtargetFeatures Features;
242 for (unsigned i = 0; i != MAttrs.size(); ++i)
243 Features.AddFeature(MAttrs[i]);
244 FeaturesStr = Features.getString();
247 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
250 errs() << argv[0] << ": invalid optimization level.\n";
253 case '0': OLvl = CodeGenOpt::None; break;
254 case '1': OLvl = CodeGenOpt::Less; break;
255 case '2': OLvl = CodeGenOpt::Default; break;
256 case '3': OLvl = CodeGenOpt::Aggressive; break;
259 TargetOptions Options;
260 Options.LessPreciseFPMADOption = EnableFPMAD;
261 Options.NoFramePointerElim = DisableFPElim;
262 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
263 Options.AllowFPOpFusion = FuseFPOps;
264 Options.UnsafeFPMath = EnableUnsafeFPMath;
265 Options.NoInfsFPMath = EnableNoInfsFPMath;
266 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
267 Options.HonorSignDependentRoundingFPMathOption =
268 EnableHonorSignDependentRoundingFPMath;
269 Options.UseSoftFloat = GenerateSoftFloatCalls;
270 if (FloatABIForCalls != FloatABI::Default)
271 Options.FloatABIType = FloatABIForCalls;
272 Options.NoZerosInBSS = DontPlaceZerosInBSS;
273 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
274 Options.DisableTailCalls = DisableTailCalls;
275 Options.StackAlignmentOverride = OverrideStackAlignment;
276 Options.RealignStack = EnableRealignStack;
277 Options.TrapFuncName = TrapFuncName;
278 Options.PositionIndependentExecutable = EnablePIE;
279 Options.EnableSegmentedStacks = SegmentedStacks;
280 Options.UseInitArray = UseInitArray;
281 Options.SSPBufferSize = SSPBufferSize;
283 std::auto_ptr<TargetMachine>
284 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
285 MCPU, FeaturesStr, Options,
286 RelocModel, CMModel, OLvl));
287 assert(target.get() && "Could not allocate target machine!");
288 assert(mod && "Should have exited after outputting help!");
289 TargetMachine &Target = *target.get();
292 Target.setMCUseLoc(false);
295 Target.setMCUseCFI(false);
297 if (EnableDwarfDirectory)
298 Target.setMCUseDwarfDirectory(true);
300 if (GenerateSoftFloatCalls)
301 FloatABIForCalls = FloatABI::Soft;
303 // Disable .loc support for older OS X versions.
304 if (TheTriple.isMacOSX() &&
305 TheTriple.isMacOSXVersionLT(10, 6))
306 Target.setMCUseLoc(false);
308 // Figure out where we are going to send the output.
309 OwningPtr<tool_output_file> Out
310 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
313 // Build up all of the passes that we want to do to the module.
316 // Add an appropriate TargetLibraryInfo pass for the module's triple.
317 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
318 if (DisableSimplifyLibCalls)
319 TLI->disableAllFunctions();
323 PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
324 target->getVectorTargetTransformInfo()));
327 // Add the target data from the target machine, if it exists, or the module.
328 if (const DataLayout *TD = Target.getDataLayout())
329 PM.add(new DataLayout(*TD));
331 PM.add(new DataLayout(mod));
333 // Override default to generate verbose assembly.
334 Target.setAsmVerbosityDefault(true);
337 if (FileType != TargetMachine::CGFT_ObjectFile)
339 << ": warning: ignoring -mc-relax-all because filetype != obj";
341 Target.setMCRelaxAll(true);
345 formatted_raw_ostream FOS(Out->os());
347 AnalysisID StartAfterID = 0;
348 AnalysisID StopAfterID = 0;
349 const PassRegistry *PR = PassRegistry::getPassRegistry();
350 if (!StartAfter.empty()) {
351 const PassInfo *PI = PR->getPassInfo(StartAfter);
353 errs() << argv[0] << ": start-after pass is not registered.\n";
356 StartAfterID = PI->getTypeInfo();
358 if (!StopAfter.empty()) {
359 const PassInfo *PI = PR->getPassInfo(StopAfter);
361 errs() << argv[0] << ": stop-after pass is not registered.\n";
364 StopAfterID = PI->getTypeInfo();
367 // Ask the target to add backend passes as necessary.
368 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
369 StartAfterID, StopAfterID)) {
370 errs() << argv[0] << ": target does not support generation of this"
375 // Before executing passes, print the final values of the LLVM options.
376 cl::PrintOptionValues();