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/DataLayout.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Assembly/PrintModulePass.h"
23 #include "llvm/Support/IRReader.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
26 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
27 #include "llvm/MC/SubtargetFeature.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.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 // Determine optimization level.
57 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
63 static cl::opt<std::string>
64 TargetTriple("mtriple", cl::desc("Override target triple for module"));
66 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
67 cl::desc("Do not verify input module"));
70 DisableSimplifyLibCalls("disable-simplify-libcalls",
71 cl::desc("Disable simplify-libcalls"),
74 // GetFileNameRoot - Helper function to get the basename of a filename.
75 static inline std::string
76 GetFileNameRoot(const std::string &InputFilename) {
77 std::string IFN = InputFilename;
78 std::string outputFilename;
79 int Len = IFN.length();
82 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
83 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
84 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
88 return outputFilename;
91 static tool_output_file *GetOutputStream(const char *TargetName,
93 const char *ProgName) {
94 // If we don't yet have an output filename, make one.
95 if (OutputFilename.empty()) {
96 if (InputFilename == "-")
99 OutputFilename = GetFileNameRoot(InputFilename);
102 case TargetMachine::CGFT_AssemblyFile:
103 if (TargetName[0] == 'c') {
104 if (TargetName[1] == 0)
105 OutputFilename += ".cbe.c";
106 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
107 OutputFilename += ".cpp";
109 OutputFilename += ".s";
111 OutputFilename += ".s";
113 case TargetMachine::CGFT_ObjectFile:
114 if (OS == Triple::Win32)
115 OutputFilename += ".obj";
117 OutputFilename += ".o";
119 case TargetMachine::CGFT_Null:
120 OutputFilename += ".null";
126 // Decide if we need "binary" output.
129 case TargetMachine::CGFT_AssemblyFile:
131 case TargetMachine::CGFT_ObjectFile:
132 case TargetMachine::CGFT_Null:
139 unsigned OpenFlags = 0;
140 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
141 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
143 if (!error.empty()) {
144 errs() << error << '\n';
152 // main - Entry point for the llc compiler.
154 int main(int argc, char **argv) {
155 sys::PrintStackTraceOnErrorSignal();
156 PrettyStackTraceProgram X(argc, argv);
158 // Enable debug stream buffering.
159 EnableDebugBuffering = true;
161 LLVMContext &Context = getGlobalContext();
162 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
164 // Initialize targets first, so that --version shows registered targets.
165 InitializeAllTargets();
166 InitializeAllTargetMCs();
167 InitializeAllAsmPrinters();
168 InitializeAllAsmParsers();
170 // Initialize codegen and IR passes used by llc so that the -print-after,
171 // -print-before, and -stop-after options work.
172 PassRegistry *Registry = PassRegistry::getPassRegistry();
173 initializeCore(*Registry);
174 initializeCodeGen(*Registry);
175 initializeLoopStrengthReducePass(*Registry);
176 initializeLowerIntrinsicsPass(*Registry);
177 initializeUnreachableBlockElimPass(*Registry);
179 // Register the target printer for --version.
180 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
182 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
184 // Load the module to be compiled...
186 std::auto_ptr<Module> M;
190 bool SkipModule = MCPU == "help" ||
191 (!MAttrs.empty() && MAttrs.front() == "help");
193 // If user just wants to list available options, skip module loading
195 M.reset(ParseIRFile(InputFilename, Err, Context));
198 Err.print(argv[0], errs());
202 // If we are supposed to override the target triple, do so now.
203 if (!TargetTriple.empty())
204 mod->setTargetTriple(Triple::normalize(TargetTriple));
205 TheTriple = Triple(mod->getTargetTriple());
207 TheTriple = Triple(Triple::normalize(TargetTriple));
210 if (TheTriple.getTriple().empty())
211 TheTriple.setTriple(sys::getDefaultTargetTriple());
213 // Get the target specific parser.
215 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
218 errs() << argv[0] << ": " << Error;
222 // Package up features to be passed to target/subtarget
223 std::string FeaturesStr;
225 SubtargetFeatures Features;
226 for (unsigned i = 0; i != MAttrs.size(); ++i)
227 Features.AddFeature(MAttrs[i]);
228 FeaturesStr = Features.getString();
231 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
234 errs() << argv[0] << ": invalid optimization level.\n";
237 case '0': OLvl = CodeGenOpt::None; break;
238 case '1': OLvl = CodeGenOpt::Less; break;
239 case '2': OLvl = CodeGenOpt::Default; break;
240 case '3': OLvl = CodeGenOpt::Aggressive; break;
243 TargetOptions Options;
244 Options.LessPreciseFPMADOption = EnableFPMAD;
245 Options.NoFramePointerElim = DisableFPElim;
246 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
247 Options.AllowFPOpFusion = FuseFPOps;
248 Options.UnsafeFPMath = EnableUnsafeFPMath;
249 Options.NoInfsFPMath = EnableNoInfsFPMath;
250 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
251 Options.HonorSignDependentRoundingFPMathOption =
252 EnableHonorSignDependentRoundingFPMath;
253 Options.UseSoftFloat = GenerateSoftFloatCalls;
254 if (FloatABIForCalls != FloatABI::Default)
255 Options.FloatABIType = FloatABIForCalls;
256 Options.NoZerosInBSS = DontPlaceZerosInBSS;
257 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
258 Options.DisableTailCalls = DisableTailCalls;
259 Options.StackAlignmentOverride = OverrideStackAlignment;
260 Options.RealignStack = EnableRealignStack;
261 Options.TrapFuncName = TrapFuncName;
262 Options.PositionIndependentExecutable = EnablePIE;
263 Options.EnableSegmentedStacks = SegmentedStacks;
264 Options.UseInitArray = UseInitArray;
265 Options.SSPBufferSize = SSPBufferSize;
267 std::auto_ptr<TargetMachine>
268 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
269 MCPU, FeaturesStr, Options,
270 RelocModel, CMModel, OLvl));
271 assert(target.get() && "Could not allocate target machine!");
272 assert(mod && "Should have exited after outputting help!");
273 TargetMachine &Target = *target.get();
276 Target.setMCUseLoc(false);
279 Target.setMCUseCFI(false);
281 if (EnableDwarfDirectory)
282 Target.setMCUseDwarfDirectory(true);
284 if (GenerateSoftFloatCalls)
285 FloatABIForCalls = FloatABI::Soft;
287 // Disable .loc support for older OS X versions.
288 if (TheTriple.isMacOSX() &&
289 TheTriple.isMacOSXVersionLT(10, 6))
290 Target.setMCUseLoc(false);
292 // Figure out where we are going to send the output.
293 OwningPtr<tool_output_file> Out
294 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
297 // Build up all of the passes that we want to do to the module.
300 // Add an appropriate TargetLibraryInfo pass for the module's triple.
301 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
302 if (DisableSimplifyLibCalls)
303 TLI->disableAllFunctions();
307 PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
308 target->getVectorTargetTransformInfo()));
311 // Add the target data from the target machine, if it exists, or the module.
312 if (const DataLayout *TD = Target.getDataLayout())
313 PM.add(new DataLayout(*TD));
315 PM.add(new DataLayout(mod));
317 // Override default to generate verbose assembly.
318 Target.setAsmVerbosityDefault(true);
321 if (FileType != TargetMachine::CGFT_ObjectFile)
323 << ": warning: ignoring -mc-relax-all because filetype != obj";
325 Target.setMCRelaxAll(true);
329 formatted_raw_ostream FOS(Out->os());
331 AnalysisID StartAfterID = 0;
332 AnalysisID StopAfterID = 0;
333 const PassRegistry *PR = PassRegistry::getPassRegistry();
334 if (!StartAfter.empty()) {
335 const PassInfo *PI = PR->getPassInfo(StartAfter);
337 errs() << argv[0] << ": start-after pass is not registered.\n";
340 StartAfterID = PI->getTypeInfo();
342 if (!StopAfter.empty()) {
343 const PassInfo *PI = PR->getPassInfo(StopAfter);
345 errs() << argv[0] << ": stop-after pass is not registered.\n";
348 StopAfterID = PI->getTypeInfo();
351 // Ask the target to add backend passes as necessary.
352 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
353 StartAfterID, StopAfterID)) {
354 errs() << argv[0] << ": target does not support generation of this"
359 // Before executing passes, print the final values of the LLVM options.
360 cl::PrintOptionValues();
362 PM.doInitialization();