llc.cpp revision 9421406aada374f79ce2f8e576824463f7830981
1//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
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/Support/IRReader.h"
22#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23#include "llvm/CodeGen/LinkAllCodegenComponents.h"
24#include "llvm/MC/SubtargetFeature.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/FormattedStream.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/PluginLoader.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/ToolOutputFile.h"
32#include "llvm/Support/Host.h"
33#include "llvm/Support/Signals.h"
34#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/TargetSelect.h"
36#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetMachine.h"
38#include <memory>
39using namespace llvm;
40
41// General options for llc.  Other pass-specific options are specified
42// within the corresponding llc passes, and target-specific options
43// and back-end code generation options are specified with the target machine.
44//
45static cl::opt<std::string>
46InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
47
48static cl::opt<std::string>
49OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50
51// Determine optimization level.
52static cl::opt<char>
53OptLevel("O",
54         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
55                  "(default = '-O2')"),
56         cl::Prefix,
57         cl::ZeroOrMore,
58         cl::init(' '));
59
60static cl::opt<std::string>
61TargetTriple("mtriple", cl::desc("Override target triple for module"));
62
63static cl::opt<std::string>
64MArch("march", cl::desc("Architecture to generate code for (see --version)"));
65
66static cl::opt<std::string>
67MCPU("mcpu",
68  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
69  cl::value_desc("cpu-name"),
70  cl::init(""));
71
72static cl::list<std::string>
73MAttrs("mattr",
74  cl::CommaSeparated,
75  cl::desc("Target specific attributes (-mattr=help for details)"),
76  cl::value_desc("a1,+a2,-a3,..."));
77
78static cl::opt<Reloc::Model>
79RelocModel("relocation-model",
80             cl::desc("Choose relocation model"),
81             cl::init(Reloc::Default),
82             cl::values(
83            clEnumValN(Reloc::Default, "default",
84                       "Target default relocation model"),
85            clEnumValN(Reloc::Static, "static",
86                       "Non-relocatable code"),
87            clEnumValN(Reloc::PIC_, "pic",
88                       "Fully relocatable, position independent code"),
89            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
90                       "Relocatable external references, non-relocatable code"),
91            clEnumValEnd));
92
93static cl::opt<llvm::CodeModel::Model>
94CMModel("code-model",
95        cl::desc("Choose code model"),
96        cl::init(CodeModel::Default),
97        cl::values(clEnumValN(CodeModel::Default, "default",
98                              "Target default code model"),
99                   clEnumValN(CodeModel::Small, "small",
100                              "Small code model"),
101                   clEnumValN(CodeModel::Kernel, "kernel",
102                              "Kernel code model"),
103                   clEnumValN(CodeModel::Medium, "medium",
104                              "Medium code model"),
105                   clEnumValN(CodeModel::Large, "large",
106                              "Large code model"),
107                   clEnumValEnd));
108
109static cl::opt<bool>
110RelaxAll("mc-relax-all",
111  cl::desc("When used with filetype=obj, "
112           "relax all fixups in the emitted object file"));
113
114cl::opt<TargetMachine::CodeGenFileType>
115FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
116  cl::desc("Choose a file type (not all types are supported by all targets):"),
117  cl::values(
118       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
119                  "Emit an assembly ('.s') file"),
120       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
121                  "Emit a native object ('.o') file [experimental]"),
122       clEnumValN(TargetMachine::CGFT_Null, "null",
123                  "Emit nothing, for performance testing"),
124       clEnumValEnd));
125
126cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
127                       cl::desc("Do not verify input module"));
128
129cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
130                            cl::desc("Do not use .loc entries"));
131
132cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
133                         cl::desc("Do not use .cfi_* directives"));
134
135cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
136    cl::desc("Use .file directives with an explicit directory."));
137
138static cl::opt<bool>
139DisableRedZone("disable-red-zone",
140  cl::desc("Do not emit code that uses the red zone."),
141  cl::init(false));
142
143static cl::opt<bool>
144EnableFPMAD("enable-fp-mad",
145  cl::desc("Enable less precise MAD instructions to be generated"),
146  cl::init(false));
147
148static cl::opt<bool>
149PrintCode("print-machineinstrs",
150  cl::desc("Print generated machine code"),
151  cl::init(false));
152
153static cl::opt<bool>
154DisableFPElim("disable-fp-elim",
155  cl::desc("Disable frame pointer elimination optimization"),
156  cl::init(false));
157
158static cl::opt<bool>
159DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
160  cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
161  cl::init(false));
162
163static cl::opt<bool>
164DisableExcessPrecision("disable-excess-fp-precision",
165  cl::desc("Disable optimizations that may increase FP precision"),
166  cl::init(false));
167
168static cl::opt<bool>
169EnableUnsafeFPMath("enable-unsafe-fp-math",
170  cl::desc("Enable optimizations that may decrease FP precision"),
171  cl::init(false));
172
173static cl::opt<bool>
174EnableNoInfsFPMath("enable-no-infs-fp-math",
175  cl::desc("Enable FP math optimizations that assume no +-Infs"),
176  cl::init(false));
177
178static cl::opt<bool>
179EnableNoNaNsFPMath("enable-no-nans-fp-math",
180  cl::desc("Enable FP math optimizations that assume no NaNs"),
181  cl::init(false));
182
183static cl::opt<bool>
184EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
185  cl::Hidden,
186  cl::desc("Force codegen to assume rounding mode can change dynamically"),
187  cl::init(false));
188
189static cl::opt<bool>
190GenerateSoftFloatCalls("soft-float",
191  cl::desc("Generate software floating point library calls"),
192  cl::init(false));
193
194static cl::opt<llvm::FloatABI::ABIType>
195FloatABIForCalls("float-abi",
196  cl::desc("Choose float ABI type"),
197  cl::init(FloatABI::Default),
198  cl::values(
199    clEnumValN(FloatABI::Default, "default",
200               "Target default float ABI type"),
201    clEnumValN(FloatABI::Soft, "soft",
202               "Soft float ABI (implied by -soft-float)"),
203    clEnumValN(FloatABI::Hard, "hard",
204               "Hard float ABI (uses FP registers)"),
205    clEnumValEnd));
206
207static cl::opt<bool>
208DontPlaceZerosInBSS("nozero-initialized-in-bss",
209  cl::desc("Don't place zero-initialized symbols into bss section"),
210  cl::init(false));
211
212static cl::opt<bool>
213EnableJITExceptionHandling("jit-enable-eh",
214  cl::desc("Emit exception handling information"),
215  cl::init(false));
216
217// In debug builds, make this default to true.
218#ifdef NDEBUG
219#define EMIT_DEBUG false
220#else
221#define EMIT_DEBUG true
222#endif
223static cl::opt<bool>
224EmitJitDebugInfo("jit-emit-debug",
225  cl::desc("Emit debug information to debugger"),
226  cl::init(EMIT_DEBUG));
227#undef EMIT_DEBUG
228
229static cl::opt<bool>
230EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
231  cl::Hidden,
232  cl::desc("Emit debug info objfiles to disk"),
233  cl::init(false));
234
235static cl::opt<bool>
236EnableGuaranteedTailCallOpt("tailcallopt",
237  cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
238  cl::init(false));
239
240static cl::opt<unsigned>
241OverrideStackAlignment("stack-alignment",
242  cl::desc("Override default stack alignment"),
243  cl::init(0));
244
245static cl::opt<bool>
246EnableRealignStack("realign-stack",
247  cl::desc("Realign stack if needed"),
248  cl::init(true));
249
250static cl::opt<bool>
251DisableSwitchTables(cl::Hidden, "disable-jump-tables",
252  cl::desc("Do not generate jump tables."),
253  cl::init(false));
254
255static cl::opt<bool>
256EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
257  cl::desc("Use strong PHI elimination."),
258  cl::init(false));
259
260static cl::opt<std::string>
261TrapFuncName("trap-func", cl::Hidden,
262  cl::desc("Emit a call to trap function rather than a trap instruction"),
263  cl::init(""));
264
265static cl::opt<bool>
266SegmentedStacks("segmented-stacks",
267  cl::desc("Use segmented stacks if possible."),
268  cl::init(false));
269
270
271// GetFileNameRoot - Helper function to get the basename of a filename.
272static inline std::string
273GetFileNameRoot(const std::string &InputFilename) {
274  std::string IFN = InputFilename;
275  std::string outputFilename;
276  int Len = IFN.length();
277  if ((Len > 2) &&
278      IFN[Len-3] == '.' &&
279      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
280       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
281    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
282  } else {
283    outputFilename = IFN;
284  }
285  return outputFilename;
286}
287
288static tool_output_file *GetOutputStream(const char *TargetName,
289                                         Triple::OSType OS,
290                                         const char *ProgName) {
291  // If we don't yet have an output filename, make one.
292  if (OutputFilename.empty()) {
293    if (InputFilename == "-")
294      OutputFilename = "-";
295    else {
296      OutputFilename = GetFileNameRoot(InputFilename);
297
298      switch (FileType) {
299      default: assert(0 && "Unknown file type");
300      case TargetMachine::CGFT_AssemblyFile:
301        if (TargetName[0] == 'c') {
302          if (TargetName[1] == 0)
303            OutputFilename += ".cbe.c";
304          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
305            OutputFilename += ".cpp";
306          else
307            OutputFilename += ".s";
308        } else
309          OutputFilename += ".s";
310        break;
311      case TargetMachine::CGFT_ObjectFile:
312        if (OS == Triple::Win32)
313          OutputFilename += ".obj";
314        else
315          OutputFilename += ".o";
316        break;
317      case TargetMachine::CGFT_Null:
318        OutputFilename += ".null";
319        break;
320      }
321    }
322  }
323
324  // Decide if we need "binary" output.
325  bool Binary = false;
326  switch (FileType) {
327  default: assert(0 && "Unknown file type");
328  case TargetMachine::CGFT_AssemblyFile:
329    break;
330  case TargetMachine::CGFT_ObjectFile:
331  case TargetMachine::CGFT_Null:
332    Binary = true;
333    break;
334  }
335
336  // Open the file.
337  std::string error;
338  unsigned OpenFlags = 0;
339  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
340  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
341                                                 OpenFlags);
342  if (!error.empty()) {
343    errs() << error << '\n';
344    delete FDOut;
345    return 0;
346  }
347
348  return FDOut;
349}
350
351// main - Entry point for the llc compiler.
352//
353int main(int argc, char **argv) {
354  sys::PrintStackTraceOnErrorSignal();
355  PrettyStackTraceProgram X(argc, argv);
356
357  // Enable debug stream buffering.
358  EnableDebugBuffering = true;
359
360  LLVMContext &Context = getGlobalContext();
361  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
362
363  // Initialize targets first, so that --version shows registered targets.
364  InitializeAllTargets();
365  InitializeAllTargetMCs();
366  InitializeAllAsmPrinters();
367  InitializeAllAsmParsers();
368
369  // Register the target printer for --version.
370  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
371
372  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
373
374  // Load the module to be compiled...
375  SMDiagnostic Err;
376  std::auto_ptr<Module> M;
377
378  M.reset(ParseIRFile(InputFilename, Err, Context));
379  if (M.get() == 0) {
380    Err.print(argv[0], errs());
381    return 1;
382  }
383  Module &mod = *M.get();
384
385  // If we are supposed to override the target triple, do so now.
386  if (!TargetTriple.empty())
387    mod.setTargetTriple(Triple::normalize(TargetTriple));
388
389  Triple TheTriple(mod.getTargetTriple());
390  if (TheTriple.getTriple().empty())
391    TheTriple.setTriple(sys::getDefaultTargetTriple());
392
393  // Allocate target machine.  First, check whether the user has explicitly
394  // specified an architecture to compile for. If so we have to look it up by
395  // name, because it might be a backend that has no mapping to a target triple.
396  const Target *TheTarget = 0;
397  if (!MArch.empty()) {
398    for (TargetRegistry::iterator it = TargetRegistry::begin(),
399           ie = TargetRegistry::end(); it != ie; ++it) {
400      if (MArch == it->getName()) {
401        TheTarget = &*it;
402        break;
403      }
404    }
405
406    if (!TheTarget) {
407      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
408      return 1;
409    }
410
411    // Adjust the triple to match (if known), otherwise stick with the
412    // module/host triple.
413    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
414    if (Type != Triple::UnknownArch)
415      TheTriple.setArch(Type);
416  } else {
417    std::string Err;
418    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
419    if (TheTarget == 0) {
420      errs() << argv[0] << ": error auto-selecting target for module '"
421             << Err << "'.  Please use the -march option to explicitly "
422             << "pick a target.\n";
423      return 1;
424    }
425  }
426
427  // Package up features to be passed to target/subtarget
428  std::string FeaturesStr;
429  if (MAttrs.size()) {
430    SubtargetFeatures Features;
431    for (unsigned i = 0; i != MAttrs.size(); ++i)
432      Features.AddFeature(MAttrs[i]);
433    FeaturesStr = Features.getString();
434  }
435
436  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
437  switch (OptLevel) {
438  default:
439    errs() << argv[0] << ": invalid optimization level.\n";
440    return 1;
441  case ' ': break;
442  case '0': OLvl = CodeGenOpt::None; break;
443  case '1': OLvl = CodeGenOpt::Less; break;
444  case '2': OLvl = CodeGenOpt::Default; break;
445  case '3': OLvl = CodeGenOpt::Aggressive; break;
446  }
447
448  TargetOptions Options;
449  Options.LessPreciseFPMADOption = EnableFPMAD;
450  Options.PrintMachineCode = PrintCode;
451  Options.NoFramePointerElim = DisableFPElim;
452  Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
453  Options.NoExcessFPPrecision = DisableExcessPrecision;
454  Options.UnsafeFPMath = EnableUnsafeFPMath;
455  Options.NoInfsFPMath = EnableNoInfsFPMath;
456  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
457  Options.HonorSignDependentRoundingFPMathOption =
458      EnableHonorSignDependentRoundingFPMath;
459  Options.UseSoftFloat = GenerateSoftFloatCalls;
460  if (FloatABIForCalls != FloatABI::Default)
461    Options.FloatABIType = FloatABIForCalls;
462  Options.NoZerosInBSS = DontPlaceZerosInBSS;
463  Options.JITExceptionHandling = EnableJITExceptionHandling;
464  Options.JITEmitDebugInfo = EmitJitDebugInfo;
465  Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
466  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
467  Options.StackAlignmentOverride = OverrideStackAlignment;
468  Options.RealignStack = EnableRealignStack;
469  Options.DisableJumpTables = DisableSwitchTables;
470  Options.TrapFuncName = TrapFuncName;
471  Options.EnableSegmentedStacks = SegmentedStacks;
472
473  std::auto_ptr<TargetMachine>
474    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
475                                          MCPU, FeaturesStr, Options,
476                                          RelocModel, CMModel, OLvl));
477  assert(target.get() && "Could not allocate target machine!");
478  TargetMachine &Target = *target.get();
479
480  if (DisableDotLoc)
481    Target.setMCUseLoc(false);
482
483  if (DisableCFI)
484    Target.setMCUseCFI(false);
485
486  if (EnableDwarfDirectory)
487    Target.setMCUseDwarfDirectory(true);
488
489  if (GenerateSoftFloatCalls)
490    FloatABIForCalls = FloatABI::Soft;
491
492  // Disable .loc support for older OS X versions.
493  if (TheTriple.isMacOSX() &&
494      TheTriple.isMacOSXVersionLT(10, 6))
495    Target.setMCUseLoc(false);
496
497  // Figure out where we are going to send the output...
498  OwningPtr<tool_output_file> Out
499    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
500  if (!Out) return 1;
501
502  // Build up all of the passes that we want to do to the module.
503  PassManager PM;
504
505  // Add the target data from the target machine, if it exists, or the module.
506  if (const TargetData *TD = Target.getTargetData())
507    PM.add(new TargetData(*TD));
508  else
509    PM.add(new TargetData(&mod));
510
511  // Override default to generate verbose assembly.
512  Target.setAsmVerbosityDefault(true);
513
514  if (RelaxAll) {
515    if (FileType != TargetMachine::CGFT_ObjectFile)
516      errs() << argv[0]
517             << ": warning: ignoring -mc-relax-all because filetype != obj";
518    else
519      Target.setMCRelaxAll(true);
520  }
521
522  {
523    formatted_raw_ostream FOS(Out->os());
524
525    // Ask the target to add backend passes as necessary.
526    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
527      errs() << argv[0] << ": target does not support generation of this"
528             << " file type!\n";
529      return 1;
530    }
531
532    // Before executing passes, print the final values of the LLVM options.
533    cl::PrintOptionValues();
534
535    PM.run(mod);
536  }
537
538  // Declare success.
539  Out->keep();
540
541  return 0;
542}
543