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/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Support/IRReader.h"
23 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
24 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/ToolOutputFile.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/Signals.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
42 // General options for llc. Other pass-specific options are specified
43 // within the corresponding llc passes, and target-specific options
44 // and back-end code generation options are specified with the target machine.
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52 // Determine optimization level.
55 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
67 static cl::opt<std::string>
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"),
73 static cl::list<std::string>
76 cl::desc("Target specific attributes (-mattr=help for details)"),
77 cl::value_desc("a1,+a2,-a3,..."));
79 static cl::opt<Reloc::Model>
80 RelocModel("relocation-model",
81 cl::desc("Choose relocation model"),
82 cl::init(Reloc::Default),
84 clEnumValN(Reloc::Default, "default",
85 "Target default relocation model"),
86 clEnumValN(Reloc::Static, "static",
87 "Non-relocatable code"),
88 clEnumValN(Reloc::PIC_, "pic",
89 "Fully relocatable, position independent code"),
90 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
91 "Relocatable external references, non-relocatable code"),
94 static cl::opt<llvm::CodeModel::Model>
96 cl::desc("Choose code model"),
97 cl::init(CodeModel::Default),
98 cl::values(clEnumValN(CodeModel::Default, "default",
99 "Target default code model"),
100 clEnumValN(CodeModel::Small, "small",
102 clEnumValN(CodeModel::Kernel, "kernel",
103 "Kernel code model"),
104 clEnumValN(CodeModel::Medium, "medium",
105 "Medium code model"),
106 clEnumValN(CodeModel::Large, "large",
111 RelaxAll("mc-relax-all",
112 cl::desc("When used with filetype=obj, "
113 "relax all fixups in the emitted object file"));
115 cl::opt<TargetMachine::CodeGenFileType>
116 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
117 cl::desc("Choose a file type (not all types are supported by all targets):"),
119 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
120 "Emit an assembly ('.s') file"),
121 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
122 "Emit a native object ('.o') file"),
123 clEnumValN(TargetMachine::CGFT_Null, "null",
124 "Emit nothing, for performance testing"),
127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
128 cl::desc("Do not verify input module"));
130 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
131 cl::desc("Do not use .loc entries"));
133 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
134 cl::desc("Do not use .cfi_* directives"));
136 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
137 cl::desc("Use .file directives with an explicit directory."));
140 DisableRedZone("disable-red-zone",
141 cl::desc("Do not emit code that uses the red zone."),
145 EnableFPMAD("enable-fp-mad",
146 cl::desc("Enable less precise MAD instructions to be generated"),
150 DisableFPElim("disable-fp-elim",
151 cl::desc("Disable frame pointer elimination optimization"),
155 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
156 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
160 EnableUnsafeFPMath("enable-unsafe-fp-math",
161 cl::desc("Enable optimizations that may decrease FP precision"),
165 EnableNoInfsFPMath("enable-no-infs-fp-math",
166 cl::desc("Enable FP math optimizations that assume no +-Infs"),
170 EnableNoNaNsFPMath("enable-no-nans-fp-math",
171 cl::desc("Enable FP math optimizations that assume no NaNs"),
175 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
177 cl::desc("Force codegen to assume rounding mode can change dynamically"),
181 GenerateSoftFloatCalls("soft-float",
182 cl::desc("Generate software floating point library calls"),
185 static cl::opt<llvm::FloatABI::ABIType>
186 FloatABIForCalls("float-abi",
187 cl::desc("Choose float ABI type"),
188 cl::init(FloatABI::Default),
190 clEnumValN(FloatABI::Default, "default",
191 "Target default float ABI type"),
192 clEnumValN(FloatABI::Soft, "soft",
193 "Soft float ABI (implied by -soft-float)"),
194 clEnumValN(FloatABI::Hard, "hard",
195 "Hard float ABI (uses FP registers)"),
198 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
199 FuseFPOps("fp-contract",
200 cl::desc("Enable aggresive formation of fused FP ops"),
201 cl::init(FPOpFusion::Standard),
203 clEnumValN(FPOpFusion::Fast, "fast",
204 "Fuse FP ops whenever profitable"),
205 clEnumValN(FPOpFusion::Standard, "on",
206 "Only fuse 'blessed' FP ops."),
207 clEnumValN(FPOpFusion::Strict, "off",
208 "Only fuse FP ops when the result won't be effected."),
212 DontPlaceZerosInBSS("nozero-initialized-in-bss",
213 cl::desc("Don't place zero-initialized symbols into bss section"),
217 EnableGuaranteedTailCallOpt("tailcallopt",
218 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
222 DisableTailCalls("disable-tail-calls",
223 cl::desc("Never emit tail calls"),
226 static cl::opt<unsigned>
227 OverrideStackAlignment("stack-alignment",
228 cl::desc("Override default stack alignment"),
232 EnableRealignStack("realign-stack",
233 cl::desc("Realign stack if needed"),
237 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
238 cl::desc("Do not generate jump tables."),
241 static cl::opt<std::string>
242 TrapFuncName("trap-func", cl::Hidden,
243 cl::desc("Emit a call to trap function rather than a trap instruction"),
247 EnablePIE("enable-pie",
248 cl::desc("Assume the creation of a position independent executable."),
252 SegmentedStacks("segmented-stacks",
253 cl::desc("Use segmented stacks if possible."),
257 UseInitArray("use-init-array",
258 cl::desc("Use .init_array instead of .ctors."),
261 static cl::opt<std::string> StopAfter("stop-after",
262 cl::desc("Stop compilation after a specific pass"),
263 cl::value_desc("pass-name"),
265 static cl::opt<std::string> StartAfter("start-after",
266 cl::desc("Resume compilation after a specific pass"),
267 cl::value_desc("pass-name"),
270 // GetFileNameRoot - Helper function to get the basename of a filename.
271 static inline std::string
272 GetFileNameRoot(const std::string &InputFilename) {
273 std::string IFN = InputFilename;
274 std::string outputFilename;
275 int Len = IFN.length();
278 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
279 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
280 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
282 outputFilename = IFN;
284 return outputFilename;
287 static tool_output_file *GetOutputStream(const char *TargetName,
289 const char *ProgName) {
290 // If we don't yet have an output filename, make one.
291 if (OutputFilename.empty()) {
292 if (InputFilename == "-")
293 OutputFilename = "-";
295 OutputFilename = GetFileNameRoot(InputFilename);
298 case TargetMachine::CGFT_AssemblyFile:
299 if (TargetName[0] == 'c') {
300 if (TargetName[1] == 0)
301 OutputFilename += ".cbe.c";
302 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
303 OutputFilename += ".cpp";
305 OutputFilename += ".s";
307 OutputFilename += ".s";
309 case TargetMachine::CGFT_ObjectFile:
310 if (OS == Triple::Win32)
311 OutputFilename += ".obj";
313 OutputFilename += ".o";
315 case TargetMachine::CGFT_Null:
316 OutputFilename += ".null";
322 // Decide if we need "binary" output.
325 case TargetMachine::CGFT_AssemblyFile:
327 case TargetMachine::CGFT_ObjectFile:
328 case TargetMachine::CGFT_Null:
335 unsigned OpenFlags = 0;
336 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
337 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
339 if (!error.empty()) {
340 errs() << error << '\n';
348 // main - Entry point for the llc compiler.
350 int main(int argc, char **argv) {
351 sys::PrintStackTraceOnErrorSignal();
352 PrettyStackTraceProgram X(argc, argv);
354 // Enable debug stream buffering.
355 EnableDebugBuffering = true;
357 LLVMContext &Context = getGlobalContext();
358 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
360 // Initialize targets first, so that --version shows registered targets.
361 InitializeAllTargets();
362 InitializeAllTargetMCs();
363 InitializeAllAsmPrinters();
364 InitializeAllAsmParsers();
366 // Initialize codegen and IR passes used by llc so that the -print-after,
367 // -print-before, and -stop-after options work.
368 PassRegistry *Registry = PassRegistry::getPassRegistry();
369 initializeCore(*Registry);
370 initializeCodeGen(*Registry);
371 initializeLoopStrengthReducePass(*Registry);
372 initializeLowerIntrinsicsPass(*Registry);
373 initializeUnreachableBlockElimPass(*Registry);
375 // Register the target printer for --version.
376 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
378 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
380 // Load the module to be compiled...
382 std::auto_ptr<Module> M;
386 bool SkipModule = MCPU == "help" ||
387 (!MAttrs.empty() && MAttrs.front() == "help");
389 // If user just wants to list available options, skip module loading
391 M.reset(ParseIRFile(InputFilename, Err, Context));
394 Err.print(argv[0], errs());
398 // If we are supposed to override the target triple, do so now.
399 if (!TargetTriple.empty())
400 mod->setTargetTriple(Triple::normalize(TargetTriple));
401 TheTriple = Triple(mod->getTargetTriple());
403 TheTriple = Triple(Triple::normalize(TargetTriple));
406 if (TheTriple.getTriple().empty())
407 TheTriple.setTriple(sys::getDefaultTargetTriple());
409 // Get the target specific parser.
411 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
414 errs() << argv[0] << ": " << Error;
418 // Package up features to be passed to target/subtarget
419 std::string FeaturesStr;
421 SubtargetFeatures Features;
422 for (unsigned i = 0; i != MAttrs.size(); ++i)
423 Features.AddFeature(MAttrs[i]);
424 FeaturesStr = Features.getString();
427 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
430 errs() << argv[0] << ": invalid optimization level.\n";
433 case '0': OLvl = CodeGenOpt::None; break;
434 case '1': OLvl = CodeGenOpt::Less; break;
435 case '2': OLvl = CodeGenOpt::Default; break;
436 case '3': OLvl = CodeGenOpt::Aggressive; break;
439 TargetOptions Options;
440 Options.LessPreciseFPMADOption = EnableFPMAD;
441 Options.NoFramePointerElim = DisableFPElim;
442 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
443 Options.AllowFPOpFusion = FuseFPOps;
444 Options.UnsafeFPMath = EnableUnsafeFPMath;
445 Options.NoInfsFPMath = EnableNoInfsFPMath;
446 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
447 Options.HonorSignDependentRoundingFPMathOption =
448 EnableHonorSignDependentRoundingFPMath;
449 Options.UseSoftFloat = GenerateSoftFloatCalls;
450 if (FloatABIForCalls != FloatABI::Default)
451 Options.FloatABIType = FloatABIForCalls;
452 Options.NoZerosInBSS = DontPlaceZerosInBSS;
453 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
454 Options.DisableTailCalls = DisableTailCalls;
455 Options.StackAlignmentOverride = OverrideStackAlignment;
456 Options.RealignStack = EnableRealignStack;
457 Options.DisableJumpTables = DisableSwitchTables;
458 Options.TrapFuncName = TrapFuncName;
459 Options.PositionIndependentExecutable = EnablePIE;
460 Options.EnableSegmentedStacks = SegmentedStacks;
461 Options.UseInitArray = UseInitArray;
463 std::auto_ptr<TargetMachine>
464 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
465 MCPU, FeaturesStr, Options,
466 RelocModel, CMModel, OLvl));
467 assert(target.get() && "Could not allocate target machine!");
468 assert(mod && "Should have exited after outputting help!");
469 TargetMachine &Target = *target.get();
472 Target.setMCUseLoc(false);
475 Target.setMCUseCFI(false);
477 if (EnableDwarfDirectory)
478 Target.setMCUseDwarfDirectory(true);
480 if (GenerateSoftFloatCalls)
481 FloatABIForCalls = FloatABI::Soft;
483 // Disable .loc support for older OS X versions.
484 if (TheTriple.isMacOSX() &&
485 TheTriple.isMacOSXVersionLT(10, 6))
486 Target.setMCUseLoc(false);
488 // Figure out where we are going to send the output...
489 OwningPtr<tool_output_file> Out
490 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
493 // Build up all of the passes that we want to do to the module.
496 // Add the target data from the target machine, if it exists, or the module.
497 if (const TargetData *TD = Target.getTargetData())
498 PM.add(new TargetData(*TD));
500 PM.add(new TargetData(mod));
502 // Override default to generate verbose assembly.
503 Target.setAsmVerbosityDefault(true);
506 if (FileType != TargetMachine::CGFT_ObjectFile)
508 << ": warning: ignoring -mc-relax-all because filetype != obj";
510 Target.setMCRelaxAll(true);
514 formatted_raw_ostream FOS(Out->os());
516 AnalysisID StartAfterID = 0;
517 AnalysisID StopAfterID = 0;
518 const PassRegistry *PR = PassRegistry::getPassRegistry();
519 if (!StartAfter.empty()) {
520 const PassInfo *PI = PR->getPassInfo(StartAfter);
522 errs() << argv[0] << ": start-after pass is not registered.\n";
525 StartAfterID = PI->getTypeInfo();
527 if (!StopAfter.empty()) {
528 const PassInfo *PI = PR->getPassInfo(StopAfter);
530 errs() << argv[0] << ": stop-after pass is not registered.\n";
533 StopAfterID = PI->getTypeInfo();
536 // Ask the target to add backend passes as necessary.
537 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
538 StartAfterID, StopAfterID)) {
539 errs() << argv[0] << ": target does not support generation of this"
544 // Before executing passes, print the final values of the LLVM options.
545 cl::PrintOptionValues();