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/IR/LLVMContext.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/IR/DataLayout.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"));
61 // Determine optimization level.
64 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70 static cl::opt<std::string>
71 TargetTriple("mtriple", cl::desc("Override target triple for module"));
73 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
74 cl::desc("Do not verify input module"));
77 DisableSimplifyLibCalls("disable-simplify-libcalls",
78 cl::desc("Disable simplify-libcalls"),
81 static int compileModule(char**, LLVMContext&);
83 // GetFileNameRoot - Helper function to get the basename of a filename.
84 static inline std::string
85 GetFileNameRoot(const std::string &InputFilename) {
86 std::string IFN = InputFilename;
87 std::string outputFilename;
88 int Len = IFN.length();
91 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
92 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
93 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
97 return outputFilename;
100 static tool_output_file *GetOutputStream(const char *TargetName,
102 const char *ProgName) {
103 // If we don't yet have an output filename, make one.
104 if (OutputFilename.empty()) {
105 if (InputFilename == "-")
106 OutputFilename = "-";
108 OutputFilename = GetFileNameRoot(InputFilename);
111 case TargetMachine::CGFT_AssemblyFile:
112 if (TargetName[0] == 'c') {
113 if (TargetName[1] == 0)
114 OutputFilename += ".cbe.c";
115 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
116 OutputFilename += ".cpp";
118 OutputFilename += ".s";
120 OutputFilename += ".s";
122 case TargetMachine::CGFT_ObjectFile:
123 if (OS == Triple::Win32)
124 OutputFilename += ".obj";
126 OutputFilename += ".o";
128 case TargetMachine::CGFT_Null:
129 OutputFilename += ".null";
135 // Decide if we need "binary" output.
138 case TargetMachine::CGFT_AssemblyFile:
140 case TargetMachine::CGFT_ObjectFile:
141 case TargetMachine::CGFT_Null:
148 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
150 OpenFlags |= sys::fs::F_Binary;
151 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
153 if (!error.empty()) {
154 errs() << error << '\n';
162 // main - Entry point for the llc compiler.
164 int main(int argc, char **argv) {
165 sys::PrintStackTraceOnErrorSignal();
166 PrettyStackTraceProgram X(argc, argv);
168 // Enable debug stream buffering.
169 EnableDebugBuffering = true;
171 LLVMContext &Context = getGlobalContext();
172 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
174 // Initialize targets first, so that --version shows registered targets.
175 InitializeAllTargets();
176 InitializeAllTargetMCs();
177 InitializeAllAsmPrinters();
178 InitializeAllAsmParsers();
180 // Initialize codegen and IR passes used by llc so that the -print-after,
181 // -print-before, and -stop-after options work.
182 PassRegistry *Registry = PassRegistry::getPassRegistry();
183 initializeCore(*Registry);
184 initializeCodeGen(*Registry);
185 initializeLoopStrengthReducePass(*Registry);
186 initializeLowerIntrinsicsPass(*Registry);
187 initializeUnreachableBlockElimPass(*Registry);
189 // Register the target printer for --version.
190 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
192 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
194 // Compile the module TimeCompilations times to give better compile time
196 for (unsigned I = TimeCompilations; I; --I)
197 if (int RetVal = compileModule(argv, Context))
202 static int compileModule(char **argv, LLVMContext &Context) {
203 // Load the module to be compiled...
209 bool SkipModule = MCPU == "help" ||
210 (!MAttrs.empty() && MAttrs.front() == "help");
212 // If user just wants to list available options, skip module loading
214 M.reset(ParseIRFile(InputFilename, Err, Context));
217 Err.print(argv[0], errs());
221 // If we are supposed to override the target triple, do so now.
222 if (!TargetTriple.empty())
223 mod->setTargetTriple(Triple::normalize(TargetTriple));
224 TheTriple = Triple(mod->getTargetTriple());
226 TheTriple = Triple(Triple::normalize(TargetTriple));
229 if (TheTriple.getTriple().empty())
230 TheTriple.setTriple(sys::getDefaultTargetTriple());
232 // Get the target specific parser.
234 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
237 errs() << argv[0] << ": " << Error;
241 // Package up features to be passed to target/subtarget
242 std::string FeaturesStr;
244 SubtargetFeatures Features;
245 for (unsigned i = 0; i != MAttrs.size(); ++i)
246 Features.AddFeature(MAttrs[i]);
247 FeaturesStr = Features.getString();
250 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
253 errs() << argv[0] << ": invalid optimization level.\n";
256 case '0': OLvl = CodeGenOpt::None; break;
257 case '1': OLvl = CodeGenOpt::Less; break;
258 case '2': OLvl = CodeGenOpt::Default; break;
259 case '3': OLvl = CodeGenOpt::Aggressive; break;
262 TargetOptions Options;
263 Options.LessPreciseFPMADOption = EnableFPMAD;
264 Options.NoFramePointerElim = DisableFPElim;
265 Options.AllowFPOpFusion = FuseFPOps;
266 Options.UnsafeFPMath = EnableUnsafeFPMath;
267 Options.NoInfsFPMath = EnableNoInfsFPMath;
268 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
269 Options.HonorSignDependentRoundingFPMathOption =
270 EnableHonorSignDependentRoundingFPMath;
271 Options.UseSoftFloat = GenerateSoftFloatCalls;
272 if (FloatABIForCalls != FloatABI::Default)
273 Options.FloatABIType = FloatABIForCalls;
274 Options.NoZerosInBSS = DontPlaceZerosInBSS;
275 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
276 Options.DisableTailCalls = DisableTailCalls;
277 Options.StackAlignmentOverride = OverrideStackAlignment;
278 Options.TrapFuncName = TrapFuncName;
279 Options.PositionIndependentExecutable = EnablePIE;
280 Options.EnableSegmentedStacks = SegmentedStacks;
281 Options.UseInitArray = UseInitArray;
283 OwningPtr<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();
322 // Add intenal analysis passes from the target machine.
323 Target.addAnalysisPasses(PM);
325 // Add the target data from the target machine, if it exists, or the module.
326 if (const DataLayout *TD = Target.getDataLayout())
327 PM.add(new DataLayout(*TD));
329 PM.add(new DataLayout(mod));
331 // Override default to generate verbose assembly.
332 Target.setAsmVerbosityDefault(true);
335 if (FileType != TargetMachine::CGFT_ObjectFile)
337 << ": warning: ignoring -mc-relax-all because filetype != obj";
339 Target.setMCRelaxAll(true);
343 formatted_raw_ostream FOS(Out->os());
345 AnalysisID StartAfterID = 0;
346 AnalysisID StopAfterID = 0;
347 const PassRegistry *PR = PassRegistry::getPassRegistry();
348 if (!StartAfter.empty()) {
349 const PassInfo *PI = PR->getPassInfo(StartAfter);
351 errs() << argv[0] << ": start-after pass is not registered.\n";
354 StartAfterID = PI->getTypeInfo();
356 if (!StopAfter.empty()) {
357 const PassInfo *PI = PR->getPassInfo(StopAfter);
359 errs() << argv[0] << ": stop-after pass is not registered.\n";
362 StopAfterID = PI->getTypeInfo();
365 // Ask the target to add backend passes as necessary.
366 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
367 StartAfterID, StopAfterID)) {
368 errs() << argv[0] << ": target does not support generation of this"
373 // Before executing passes, print the final values of the LLVM options.
374 cl::PrintOptionValues();