llc.cpp revision 243830
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/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"
41#include <memory>
42using namespace llvm;
43
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.
47//
48static cl::opt<std::string>
49InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
50
51static cl::opt<std::string>
52OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
53
54// Determine optimization level.
55static cl::opt<char>
56OptLevel("O",
57         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
58                  "(default = '-O2')"),
59         cl::Prefix,
60         cl::ZeroOrMore,
61         cl::init(' '));
62
63static cl::opt<std::string>
64TargetTriple("mtriple", cl::desc("Override target triple for module"));
65
66cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
67                       cl::desc("Do not verify input module"));
68
69cl::opt<bool>
70DisableSimplifyLibCalls("disable-simplify-libcalls",
71                        cl::desc("Disable simplify-libcalls"),
72                        cl::init(false));
73
74// GetFileNameRoot - Helper function to get the basename of a filename.
75static inline std::string
76GetFileNameRoot(const std::string &InputFilename) {
77  std::string IFN = InputFilename;
78  std::string outputFilename;
79  int Len = IFN.length();
80  if ((Len > 2) &&
81      IFN[Len-3] == '.' &&
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/
85  } else {
86    outputFilename = IFN;
87  }
88  return outputFilename;
89}
90
91static tool_output_file *GetOutputStream(const char *TargetName,
92                                         Triple::OSType OS,
93                                         const char *ProgName) {
94  // If we don't yet have an output filename, make one.
95  if (OutputFilename.empty()) {
96    if (InputFilename == "-")
97      OutputFilename = "-";
98    else {
99      OutputFilename = GetFileNameRoot(InputFilename);
100
101      switch (FileType) {
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";
108          else
109            OutputFilename += ".s";
110        } else
111          OutputFilename += ".s";
112        break;
113      case TargetMachine::CGFT_ObjectFile:
114        if (OS == Triple::Win32)
115          OutputFilename += ".obj";
116        else
117          OutputFilename += ".o";
118        break;
119      case TargetMachine::CGFT_Null:
120        OutputFilename += ".null";
121        break;
122      }
123    }
124  }
125
126  // Decide if we need "binary" output.
127  bool Binary = false;
128  switch (FileType) {
129  case TargetMachine::CGFT_AssemblyFile:
130    break;
131  case TargetMachine::CGFT_ObjectFile:
132  case TargetMachine::CGFT_Null:
133    Binary = true;
134    break;
135  }
136
137  // Open the file.
138  std::string error;
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,
142                                                 OpenFlags);
143  if (!error.empty()) {
144    errs() << error << '\n';
145    delete FDOut;
146    return 0;
147  }
148
149  return FDOut;
150}
151
152// main - Entry point for the llc compiler.
153//
154int main(int argc, char **argv) {
155  sys::PrintStackTraceOnErrorSignal();
156  PrettyStackTraceProgram X(argc, argv);
157
158  // Enable debug stream buffering.
159  EnableDebugBuffering = true;
160
161  LLVMContext &Context = getGlobalContext();
162  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
163
164  // Initialize targets first, so that --version shows registered targets.
165  InitializeAllTargets();
166  InitializeAllTargetMCs();
167  InitializeAllAsmPrinters();
168  InitializeAllAsmParsers();
169
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);
178
179  // Register the target printer for --version.
180  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
181
182  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
183
184  // Load the module to be compiled...
185  SMDiagnostic Err;
186  std::auto_ptr<Module> M;
187  Module *mod = 0;
188  Triple TheTriple;
189
190  bool SkipModule = MCPU == "help" ||
191                    (!MAttrs.empty() && MAttrs.front() == "help");
192
193  // If user just wants to list available options, skip module loading
194  if (!SkipModule) {
195    M.reset(ParseIRFile(InputFilename, Err, Context));
196    mod = M.get();
197    if (mod == 0) {
198      Err.print(argv[0], errs());
199      return 1;
200    }
201
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());
206  } else {
207    TheTriple = Triple(Triple::normalize(TargetTriple));
208  }
209
210  if (TheTriple.getTriple().empty())
211    TheTriple.setTriple(sys::getDefaultTargetTriple());
212
213  // Get the target specific parser.
214  std::string Error;
215  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
216                                                         Error);
217  if (!TheTarget) {
218    errs() << argv[0] << ": " << Error;
219    return 1;
220  }
221
222  // Package up features to be passed to target/subtarget
223  std::string FeaturesStr;
224  if (MAttrs.size()) {
225    SubtargetFeatures Features;
226    for (unsigned i = 0; i != MAttrs.size(); ++i)
227      Features.AddFeature(MAttrs[i]);
228    FeaturesStr = Features.getString();
229  }
230
231  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
232  switch (OptLevel) {
233  default:
234    errs() << argv[0] << ": invalid optimization level.\n";
235    return 1;
236  case ' ': break;
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;
241  }
242
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;
266
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();
274
275  if (DisableDotLoc)
276    Target.setMCUseLoc(false);
277
278  if (DisableCFI)
279    Target.setMCUseCFI(false);
280
281  if (EnableDwarfDirectory)
282    Target.setMCUseDwarfDirectory(true);
283
284  if (GenerateSoftFloatCalls)
285    FloatABIForCalls = FloatABI::Soft;
286
287  // Disable .loc support for older OS X versions.
288  if (TheTriple.isMacOSX() &&
289      TheTriple.isMacOSXVersionLT(10, 6))
290    Target.setMCUseLoc(false);
291
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]));
295  if (!Out) return 1;
296
297  // Build up all of the passes that we want to do to the module.
298  PassManager PM;
299
300  // Add an appropriate TargetLibraryInfo pass for the module's triple.
301  TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
302  if (DisableSimplifyLibCalls)
303    TLI->disableAllFunctions();
304  PM.add(TLI);
305
306  if (target.get()) {
307    PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
308                                   target->getVectorTargetTransformInfo()));
309  }
310
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));
314  else
315    PM.add(new DataLayout(mod));
316
317  // Override default to generate verbose assembly.
318  Target.setAsmVerbosityDefault(true);
319
320  if (RelaxAll) {
321    if (FileType != TargetMachine::CGFT_ObjectFile)
322      errs() << argv[0]
323             << ": warning: ignoring -mc-relax-all because filetype != obj";
324    else
325      Target.setMCRelaxAll(true);
326  }
327
328  {
329    formatted_raw_ostream FOS(Out->os());
330
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);
336      if (!PI) {
337        errs() << argv[0] << ": start-after pass is not registered.\n";
338        return 1;
339      }
340      StartAfterID = PI->getTypeInfo();
341    }
342    if (!StopAfter.empty()) {
343      const PassInfo *PI = PR->getPassInfo(StopAfter);
344      if (!PI) {
345        errs() << argv[0] << ": stop-after pass is not registered.\n";
346        return 1;
347      }
348      StopAfterID = PI->getTypeInfo();
349    }
350
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"
355             << " file type!\n";
356      return 1;
357    }
358
359    // Before executing passes, print the final values of the LLVM options.
360    cl::PrintOptionValues();
361
362    PM.run(*mod);
363  }
364
365  // Declare success.
366  Out->keep();
367
368  return 0;
369}
370