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/LinkAllAsmWriterComponents.h"
25 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Target/TargetLibraryInfo.h"
39 #include "llvm/Target/TargetMachine.h"
43 // General options for llc. Other pass-specific options are specified
44 // within the corresponding llc passes, and target-specific options
45 // and back-end code generation options are specified with the target machine.
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
50 static cl::opt<std::string>
51 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
53 // Determine optimization level.
56 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
62 static cl::opt<std::string>
63 TargetTriple("mtriple", cl::desc("Override target triple for module"));
65 static cl::opt<std::string>
66 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
68 static cl::opt<std::string>
70 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
71 cl::value_desc("cpu-name"),
74 static cl::list<std::string>
77 cl::desc("Target specific attributes (-mattr=help for details)"),
78 cl::value_desc("a1,+a2,-a3,..."));
80 static cl::opt<Reloc::Model>
81 RelocModel("relocation-model",
82 cl::desc("Choose relocation model"),
83 cl::init(Reloc::Default),
85 clEnumValN(Reloc::Default, "default",
86 "Target default relocation model"),
87 clEnumValN(Reloc::Static, "static",
88 "Non-relocatable code"),
89 clEnumValN(Reloc::PIC_, "pic",
90 "Fully relocatable, position independent code"),
91 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
92 "Relocatable external references, non-relocatable code"),
95 static cl::opt<llvm::CodeModel::Model>
97 cl::desc("Choose code model"),
98 cl::init(CodeModel::Default),
99 cl::values(clEnumValN(CodeModel::Default, "default",
100 "Target default code model"),
101 clEnumValN(CodeModel::Small, "small",
103 clEnumValN(CodeModel::Kernel, "kernel",
104 "Kernel code model"),
105 clEnumValN(CodeModel::Medium, "medium",
106 "Medium code model"),
107 clEnumValN(CodeModel::Large, "large",
112 RelaxAll("mc-relax-all",
113 cl::desc("When used with filetype=obj, "
114 "relax all fixups in the emitted object file"));
116 cl::opt<TargetMachine::CodeGenFileType>
117 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
118 cl::desc("Choose a file type (not all types are supported by all targets):"),
120 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
121 "Emit an assembly ('.s') file"),
122 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
123 "Emit a native object ('.o') file"),
124 clEnumValN(TargetMachine::CGFT_Null, "null",
125 "Emit nothing, for performance testing"),
128 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
129 cl::desc("Do not verify input module"));
131 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
132 cl::desc("Do not use .loc entries"));
134 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
135 cl::desc("Do not use .cfi_* directives"));
137 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
138 cl::desc("Use .file directives with an explicit directory."));
141 DisableRedZone("disable-red-zone",
142 cl::desc("Do not emit code that uses the red zone."),
146 EnableFPMAD("enable-fp-mad",
147 cl::desc("Enable less precise MAD instructions to be generated"),
151 DisableFPElim("disable-fp-elim",
152 cl::desc("Disable frame pointer elimination optimization"),
156 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
157 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
161 EnableUnsafeFPMath("enable-unsafe-fp-math",
162 cl::desc("Enable optimizations that may decrease FP precision"),
166 EnableNoInfsFPMath("enable-no-infs-fp-math",
167 cl::desc("Enable FP math optimizations that assume no +-Infs"),
171 EnableNoNaNsFPMath("enable-no-nans-fp-math",
172 cl::desc("Enable FP math optimizations that assume no NaNs"),
176 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
178 cl::desc("Force codegen to assume rounding mode can change dynamically"),
182 GenerateSoftFloatCalls("soft-float",
183 cl::desc("Generate software floating point library calls"),
186 static cl::opt<llvm::FloatABI::ABIType>
187 FloatABIForCalls("float-abi",
188 cl::desc("Choose float ABI type"),
189 cl::init(FloatABI::Default),
191 clEnumValN(FloatABI::Default, "default",
192 "Target default float ABI type"),
193 clEnumValN(FloatABI::Soft, "soft",
194 "Soft float ABI (implied by -soft-float)"),
195 clEnumValN(FloatABI::Hard, "hard",
196 "Hard float ABI (uses FP registers)"),
199 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
200 FuseFPOps("fp-contract",
201 cl::desc("Enable aggresive formation of fused FP ops"),
202 cl::init(FPOpFusion::Standard),
204 clEnumValN(FPOpFusion::Fast, "fast",
205 "Fuse FP ops whenever profitable"),
206 clEnumValN(FPOpFusion::Standard, "on",
207 "Only fuse 'blessed' FP ops."),
208 clEnumValN(FPOpFusion::Strict, "off",
209 "Only fuse FP ops when the result won't be effected."),
213 DontPlaceZerosInBSS("nozero-initialized-in-bss",
214 cl::desc("Don't place zero-initialized symbols into bss section"),
218 DisableSimplifyLibCalls("disable-simplify-libcalls",
219 cl::desc("Disable simplify-libcalls"),
223 EnableGuaranteedTailCallOpt("tailcallopt",
224 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
228 DisableTailCalls("disable-tail-calls",
229 cl::desc("Never emit tail calls"),
232 static cl::opt<unsigned>
233 OverrideStackAlignment("stack-alignment",
234 cl::desc("Override default stack alignment"),
238 EnableRealignStack("realign-stack",
239 cl::desc("Realign stack if needed"),
242 static cl::opt<std::string>
243 TrapFuncName("trap-func", cl::Hidden,
244 cl::desc("Emit a call to trap function rather than a trap instruction"),
248 EnablePIE("enable-pie",
249 cl::desc("Assume the creation of a position independent executable."),
253 SegmentedStacks("segmented-stacks",
254 cl::desc("Use segmented stacks if possible."),
258 UseInitArray("use-init-array",
259 cl::desc("Use .init_array instead of .ctors."),
262 static cl::opt<std::string> StopAfter("stop-after",
263 cl::desc("Stop compilation after a specific pass"),
264 cl::value_desc("pass-name"),
266 static cl::opt<std::string> StartAfter("start-after",
267 cl::desc("Resume compilation after a specific pass"),
268 cl::value_desc("pass-name"),
271 static cl::opt<unsigned>
272 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
273 cl::desc("Lower bound for a buffer to be considered for "
274 "stack protection"));
276 // GetFileNameRoot - Helper function to get the basename of a filename.
277 static inline std::string
278 GetFileNameRoot(const std::string &InputFilename) {
279 std::string IFN = InputFilename;
280 std::string outputFilename;
281 int Len = IFN.length();
284 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
285 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
286 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
288 outputFilename = IFN;
290 return outputFilename;
293 static tool_output_file *GetOutputStream(const char *TargetName,
295 const char *ProgName) {
296 // If we don't yet have an output filename, make one.
297 if (OutputFilename.empty()) {
298 if (InputFilename == "-")
299 OutputFilename = "-";
301 OutputFilename = GetFileNameRoot(InputFilename);
304 case TargetMachine::CGFT_AssemblyFile:
305 if (TargetName[0] == 'c') {
306 if (TargetName[1] == 0)
307 OutputFilename += ".cbe.c";
308 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
309 OutputFilename += ".cpp";
311 OutputFilename += ".s";
313 OutputFilename += ".s";
315 case TargetMachine::CGFT_ObjectFile:
316 if (OS == Triple::Win32)
317 OutputFilename += ".obj";
319 OutputFilename += ".o";
321 case TargetMachine::CGFT_Null:
322 OutputFilename += ".null";
328 // Decide if we need "binary" output.
331 case TargetMachine::CGFT_AssemblyFile:
333 case TargetMachine::CGFT_ObjectFile:
334 case TargetMachine::CGFT_Null:
341 unsigned OpenFlags = 0;
342 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
343 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
345 if (!error.empty()) {
346 errs() << error << '\n';
354 // main - Entry point for the llc compiler.
356 int main(int argc, char **argv) {
357 sys::PrintStackTraceOnErrorSignal();
358 PrettyStackTraceProgram X(argc, argv);
360 // Enable debug stream buffering.
361 EnableDebugBuffering = true;
363 LLVMContext &Context = getGlobalContext();
364 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
366 // Initialize targets first, so that --version shows registered targets.
367 InitializeAllTargets();
368 InitializeAllTargetMCs();
369 InitializeAllAsmPrinters();
370 InitializeAllAsmParsers();
372 // Initialize codegen and IR passes used by llc so that the -print-after,
373 // -print-before, and -stop-after options work.
374 PassRegistry *Registry = PassRegistry::getPassRegistry();
375 initializeCore(*Registry);
376 initializeCodeGen(*Registry);
377 initializeLoopStrengthReducePass(*Registry);
378 initializeLowerIntrinsicsPass(*Registry);
379 initializeUnreachableBlockElimPass(*Registry);
381 // Register the target printer for --version.
382 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
384 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
386 // Load the module to be compiled...
388 std::auto_ptr<Module> M;
392 bool SkipModule = MCPU == "help" ||
393 (!MAttrs.empty() && MAttrs.front() == "help");
395 // If user just wants to list available options, skip module loading
397 M.reset(ParseIRFile(InputFilename, Err, Context));
400 Err.print(argv[0], errs());
404 // If we are supposed to override the target triple, do so now.
405 if (!TargetTriple.empty())
406 mod->setTargetTriple(Triple::normalize(TargetTriple));
407 TheTriple = Triple(mod->getTargetTriple());
409 TheTriple = Triple(Triple::normalize(TargetTriple));
412 if (TheTriple.getTriple().empty())
413 TheTriple.setTriple(sys::getDefaultTargetTriple());
415 // Get the target specific parser.
417 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
420 errs() << argv[0] << ": " << Error;
424 // Package up features to be passed to target/subtarget
425 std::string FeaturesStr;
427 SubtargetFeatures Features;
428 for (unsigned i = 0; i != MAttrs.size(); ++i)
429 Features.AddFeature(MAttrs[i]);
430 FeaturesStr = Features.getString();
433 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
436 errs() << argv[0] << ": invalid optimization level.\n";
439 case '0': OLvl = CodeGenOpt::None; break;
440 case '1': OLvl = CodeGenOpt::Less; break;
441 case '2': OLvl = CodeGenOpt::Default; break;
442 case '3': OLvl = CodeGenOpt::Aggressive; break;
445 TargetOptions Options;
446 Options.LessPreciseFPMADOption = EnableFPMAD;
447 Options.NoFramePointerElim = DisableFPElim;
448 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
449 Options.AllowFPOpFusion = FuseFPOps;
450 Options.UnsafeFPMath = EnableUnsafeFPMath;
451 Options.NoInfsFPMath = EnableNoInfsFPMath;
452 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
453 Options.HonorSignDependentRoundingFPMathOption =
454 EnableHonorSignDependentRoundingFPMath;
455 Options.UseSoftFloat = GenerateSoftFloatCalls;
456 if (FloatABIForCalls != FloatABI::Default)
457 Options.FloatABIType = FloatABIForCalls;
458 Options.NoZerosInBSS = DontPlaceZerosInBSS;
459 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
460 Options.DisableTailCalls = DisableTailCalls;
461 Options.StackAlignmentOverride = OverrideStackAlignment;
462 Options.RealignStack = EnableRealignStack;
463 Options.TrapFuncName = TrapFuncName;
464 Options.PositionIndependentExecutable = EnablePIE;
465 Options.EnableSegmentedStacks = SegmentedStacks;
466 Options.UseInitArray = UseInitArray;
467 Options.SSPBufferSize = SSPBufferSize;
469 std::auto_ptr<TargetMachine>
470 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
471 MCPU, FeaturesStr, Options,
472 RelocModel, CMModel, OLvl));
473 assert(target.get() && "Could not allocate target machine!");
474 assert(mod && "Should have exited after outputting help!");
475 TargetMachine &Target = *target.get();
478 Target.setMCUseLoc(false);
481 Target.setMCUseCFI(false);
483 if (EnableDwarfDirectory)
484 Target.setMCUseDwarfDirectory(true);
486 if (GenerateSoftFloatCalls)
487 FloatABIForCalls = FloatABI::Soft;
489 // Disable .loc support for older OS X versions.
490 if (TheTriple.isMacOSX() &&
491 TheTriple.isMacOSXVersionLT(10, 6))
492 Target.setMCUseLoc(false);
494 // Figure out where we are going to send the output.
495 OwningPtr<tool_output_file> Out
496 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
499 // Build up all of the passes that we want to do to the module.
502 // Add an appropriate TargetLibraryInfo pass for the module's triple.
503 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
504 if (DisableSimplifyLibCalls)
505 TLI->disableAllFunctions();
508 // Add the target data from the target machine, if it exists, or the module.
509 if (const DataLayout *TD = Target.getDataLayout())
510 PM.add(new DataLayout(*TD));
512 PM.add(new DataLayout(mod));
514 // Override default to generate verbose assembly.
515 Target.setAsmVerbosityDefault(true);
518 if (FileType != TargetMachine::CGFT_ObjectFile)
520 << ": warning: ignoring -mc-relax-all because filetype != obj";
522 Target.setMCRelaxAll(true);
526 formatted_raw_ostream FOS(Out->os());
528 AnalysisID StartAfterID = 0;
529 AnalysisID StopAfterID = 0;
530 const PassRegistry *PR = PassRegistry::getPassRegistry();
531 if (!StartAfter.empty()) {
532 const PassInfo *PI = PR->getPassInfo(StartAfter);
534 errs() << argv[0] << ": start-after pass is not registered.\n";
537 StartAfterID = PI->getTypeInfo();
539 if (!StopAfter.empty()) {
540 const PassInfo *PI = PR->getPassInfo(StopAfter);
542 errs() << argv[0] << ": stop-after pass is not registered.\n";
545 StopAfterID = PI->getTypeInfo();
548 // Ask the target to add backend passes as necessary.
549 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
550 StartAfterID, StopAfterID)) {
551 errs() << argv[0] << ": target does not support generation of this"
556 // Before executing passes, print the final values of the LLVM options.
557 cl::PrintOptionValues();