llc.cpp revision 226584
1193323Sed//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This is the llc code generator driver. It provides a convenient
11193323Sed// command-line interface for generating native assembly-language code
12193323Sed// or C code, given LLVM bitcode.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16195340Sed#include "llvm/LLVMContext.h"
17193323Sed#include "llvm/Module.h"
18193323Sed#include "llvm/PassManager.h"
19193323Sed#include "llvm/Pass.h"
20198090Srdivacky#include "llvm/ADT/Triple.h"
21198090Srdivacky#include "llvm/Support/IRReader.h"
22198090Srdivacky#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23198090Srdivacky#include "llvm/CodeGen/LinkAllCodegenComponents.h"
24198090Srdivacky#include "llvm/Config/config.h"
25224133Sdim#include "llvm/MC/SubtargetFeature.h"
26193323Sed#include "llvm/Support/CommandLine.h"
27202375Srdivacky#include "llvm/Support/Debug.h"
28198090Srdivacky#include "llvm/Support/FormattedStream.h"
29193323Sed#include "llvm/Support/ManagedStatic.h"
30193323Sed#include "llvm/Support/PluginLoader.h"
31193323Sed#include "llvm/Support/PrettyStackTrace.h"
32218885Sdim#include "llvm/Support/ToolOutputFile.h"
33218885Sdim#include "llvm/Support/Host.h"
34218885Sdim#include "llvm/Support/Signals.h"
35226584Sdim#include "llvm/Support/TargetRegistry.h"
36226584Sdim#include "llvm/Support/TargetSelect.h"
37198090Srdivacky#include "llvm/Target/TargetData.h"
38198090Srdivacky#include "llvm/Target/TargetMachine.h"
39193323Sed#include <memory>
40193323Sedusing namespace llvm;
41193323Sed
42193323Sed// General options for llc.  Other pass-specific options are specified
43193323Sed// within the corresponding llc passes, and target-specific options
44193323Sed// and back-end code generation options are specified with the target machine.
45193323Sed//
46193323Sedstatic cl::opt<std::string>
47193323SedInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48193323Sed
49193323Sedstatic cl::opt<std::string>
50193323SedOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51193323Sed
52193323Sed// Determine optimization level.
53193323Sedstatic cl::opt<char>
54193323SedOptLevel("O",
55193323Sed         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56193323Sed                  "(default = '-O2')"),
57193323Sed         cl::Prefix,
58193323Sed         cl::ZeroOrMore,
59193323Sed         cl::init(' '));
60193323Sed
61193323Sedstatic cl::opt<std::string>
62193323SedTargetTriple("mtriple", cl::desc("Override target triple for module"));
63193323Sed
64198090Srdivackystatic cl::opt<std::string>
65198090SrdivackyMArch("march", cl::desc("Architecture to generate code for (see --version)"));
66193323Sed
67193323Sedstatic cl::opt<std::string>
68193323SedMCPU("mcpu",
69193323Sed  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70193323Sed  cl::value_desc("cpu-name"),
71193323Sed  cl::init(""));
72193323Sed
73193323Sedstatic cl::list<std::string>
74193323SedMAttrs("mattr",
75193323Sed  cl::CommaSeparated,
76193323Sed  cl::desc("Target specific attributes (-mattr=help for details)"),
77193323Sed  cl::value_desc("a1,+a2,-a3,..."));
78193323Sed
79226584Sdimstatic cl::opt<Reloc::Model>
80226584SdimRelocModel("relocation-model",
81226584Sdim             cl::desc("Choose relocation model"),
82226584Sdim             cl::init(Reloc::Default),
83226584Sdim             cl::values(
84226584Sdim            clEnumValN(Reloc::Default, "default",
85226584Sdim                       "Target default relocation model"),
86226584Sdim            clEnumValN(Reloc::Static, "static",
87226584Sdim                       "Non-relocatable code"),
88226584Sdim            clEnumValN(Reloc::PIC_, "pic",
89226584Sdim                       "Fully relocatable, position independent code"),
90226584Sdim            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
91226584Sdim                       "Relocatable external references, non-relocatable code"),
92226584Sdim            clEnumValEnd));
93226584Sdim
94226584Sdimstatic cl::opt<llvm::CodeModel::Model>
95226584SdimCMModel("code-model",
96226584Sdim        cl::desc("Choose code model"),
97226584Sdim        cl::init(CodeModel::Default),
98226584Sdim        cl::values(clEnumValN(CodeModel::Default, "default",
99226584Sdim                              "Target default code model"),
100226584Sdim                   clEnumValN(CodeModel::Small, "small",
101226584Sdim                              "Small code model"),
102226584Sdim                   clEnumValN(CodeModel::Kernel, "kernel",
103226584Sdim                              "Kernel code model"),
104226584Sdim                   clEnumValN(CodeModel::Medium, "medium",
105226584Sdim                              "Medium code model"),
106226584Sdim                   clEnumValN(CodeModel::Large, "large",
107226584Sdim                              "Large code model"),
108226584Sdim                   clEnumValEnd));
109226584Sdim
110212793Sdimstatic cl::opt<bool>
111212793SdimRelaxAll("mc-relax-all",
112212793Sdim  cl::desc("When used with filetype=obj, "
113212793Sdim           "relax all fixups in the emitted object file"));
114212793Sdim
115193323Sedcl::opt<TargetMachine::CodeGenFileType>
116203954SrdivackyFileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
117193323Sed  cl::desc("Choose a file type (not all types are supported by all targets):"),
118193323Sed  cl::values(
119203954Srdivacky       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
120193323Sed                  "Emit an assembly ('.s') file"),
121203954Srdivacky       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
122193323Sed                  "Emit a native object ('.o') file [experimental]"),
123203954Srdivacky       clEnumValN(TargetMachine::CGFT_Null, "null",
124203954Srdivacky                  "Emit nothing, for performance testing"),
125193323Sed       clEnumValEnd));
126193323Sed
127193323Sedcl::opt<bool> NoVerify("disable-verify", cl::Hidden,
128193323Sed                       cl::desc("Do not verify input module"));
129193323Sed
130218885Sdimcl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
131218885Sdim                            cl::desc("Do not use .loc entries"));
132193323Sed
133221337Sdimcl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
134221337Sdim                         cl::desc("Do not use .cfi_* directives"));
135221337Sdim
136193574Sedstatic cl::opt<bool>
137193574SedDisableRedZone("disable-red-zone",
138193574Sed  cl::desc("Do not emit code that uses the red zone."),
139193574Sed  cl::init(false));
140193574Sed
141193323Sed// GetFileNameRoot - Helper function to get the basename of a filename.
142193323Sedstatic inline std::string
143193323SedGetFileNameRoot(const std::string &InputFilename) {
144193323Sed  std::string IFN = InputFilename;
145193323Sed  std::string outputFilename;
146193323Sed  int Len = IFN.length();
147193323Sed  if ((Len > 2) &&
148198090Srdivacky      IFN[Len-3] == '.' &&
149198090Srdivacky      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
150198090Srdivacky       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
151193323Sed    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
152193323Sed  } else {
153193323Sed    outputFilename = IFN;
154193323Sed  }
155193323Sed  return outputFilename;
156193323Sed}
157193323Sed
158212793Sdimstatic tool_output_file *GetOutputStream(const char *TargetName,
159212793Sdim                                         Triple::OSType OS,
160212793Sdim                                         const char *ProgName) {
161212793Sdim  // If we don't yet have an output filename, make one.
162212793Sdim  if (OutputFilename.empty()) {
163212793Sdim    if (InputFilename == "-")
164212793Sdim      OutputFilename = "-";
165212793Sdim    else {
166212793Sdim      OutputFilename = GetFileNameRoot(InputFilename);
167193323Sed
168212793Sdim      switch (FileType) {
169212793Sdim      default: assert(0 && "Unknown file type");
170212793Sdim      case TargetMachine::CGFT_AssemblyFile:
171212793Sdim        if (TargetName[0] == 'c') {
172212793Sdim          if (TargetName[1] == 0)
173212793Sdim            OutputFilename += ".cbe.c";
174212793Sdim          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
175212793Sdim            OutputFilename += ".cpp";
176212793Sdim          else
177212793Sdim            OutputFilename += ".s";
178212793Sdim        } else
179212793Sdim          OutputFilename += ".s";
180212793Sdim        break;
181212793Sdim      case TargetMachine::CGFT_ObjectFile:
182212793Sdim        if (OS == Triple::Win32)
183212793Sdim          OutputFilename += ".obj";
184212793Sdim        else
185212793Sdim          OutputFilename += ".o";
186212793Sdim        break;
187212793Sdim      case TargetMachine::CGFT_Null:
188212793Sdim        OutputFilename += ".null";
189212793Sdim        break;
190212793Sdim      }
191193323Sed    }
192193323Sed  }
193193323Sed
194212793Sdim  // Decide if we need "binary" output.
195193323Sed  bool Binary = false;
196193323Sed  switch (FileType) {
197203954Srdivacky  default: assert(0 && "Unknown file type");
198203954Srdivacky  case TargetMachine::CGFT_AssemblyFile:
199193323Sed    break;
200203954Srdivacky  case TargetMachine::CGFT_ObjectFile:
201203954Srdivacky  case TargetMachine::CGFT_Null:
202193323Sed    Binary = true;
203193323Sed    break;
204193323Sed  }
205193323Sed
206212793Sdim  // Open the file.
207193323Sed  std::string error;
208198090Srdivacky  unsigned OpenFlags = 0;
209198090Srdivacky  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
210212793Sdim  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
211212793Sdim                                                 OpenFlags);
212193323Sed  if (!error.empty()) {
213198090Srdivacky    errs() << error << '\n';
214198090Srdivacky    delete FDOut;
215193323Sed    return 0;
216193323Sed  }
217193323Sed
218212793Sdim  return FDOut;
219193323Sed}
220193323Sed
221193323Sed// main - Entry point for the llc compiler.
222193323Sed//
223193323Sedint main(int argc, char **argv) {
224193323Sed  sys::PrintStackTraceOnErrorSignal();
225193323Sed  PrettyStackTraceProgram X(argc, argv);
226202375Srdivacky
227202375Srdivacky  // Enable debug stream buffering.
228202375Srdivacky  EnableDebugBuffering = true;
229202375Srdivacky
230198090Srdivacky  LLVMContext &Context = getGlobalContext();
231193323Sed  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
232193323Sed
233198090Srdivacky  // Initialize targets first, so that --version shows registered targets.
234194612Sed  InitializeAllTargets();
235226584Sdim  InitializeAllTargetMCs();
236194612Sed  InitializeAllAsmPrinters();
237206274Srdivacky  InitializeAllAsmParsers();
238198090Srdivacky
239226584Sdim  // Register the target printer for --version.
240226584Sdim  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
241226584Sdim
242198090Srdivacky  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
243221337Sdim
244193323Sed  // Load the module to be compiled...
245198090Srdivacky  SMDiagnostic Err;
246193323Sed  std::auto_ptr<Module> M;
247193323Sed
248198090Srdivacky  M.reset(ParseIRFile(InputFilename, Err, Context));
249193323Sed  if (M.get() == 0) {
250198090Srdivacky    Err.Print(argv[0], errs());
251193323Sed    return 1;
252193323Sed  }
253193323Sed  Module &mod = *M.get();
254193323Sed
255193323Sed  // If we are supposed to override the target triple, do so now.
256193323Sed  if (!TargetTriple.empty())
257212793Sdim    mod.setTargetTriple(Triple::normalize(TargetTriple));
258193323Sed
259198090Srdivacky  Triple TheTriple(mod.getTargetTriple());
260198090Srdivacky  if (TheTriple.getTriple().empty())
261198090Srdivacky    TheTriple.setTriple(sys::getHostTriple());
262198090Srdivacky
263198090Srdivacky  // Allocate target machine.  First, check whether the user has explicitly
264198090Srdivacky  // specified an architecture to compile for. If so we have to look it up by
265198090Srdivacky  // name, because it might be a backend that has no mapping to a target triple.
266198090Srdivacky  const Target *TheTarget = 0;
267198090Srdivacky  if (!MArch.empty()) {
268198090Srdivacky    for (TargetRegistry::iterator it = TargetRegistry::begin(),
269198090Srdivacky           ie = TargetRegistry::end(); it != ie; ++it) {
270198090Srdivacky      if (MArch == it->getName()) {
271198090Srdivacky        TheTarget = &*it;
272198090Srdivacky        break;
273198090Srdivacky      }
274198090Srdivacky    }
275198090Srdivacky
276198090Srdivacky    if (!TheTarget) {
277198090Srdivacky      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
278198090Srdivacky      return 1;
279198090Srdivacky    }
280198090Srdivacky
281198090Srdivacky    // Adjust the triple to match (if known), otherwise stick with the
282198090Srdivacky    // module/host triple.
283198090Srdivacky    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
284198090Srdivacky    if (Type != Triple::UnknownArch)
285198090Srdivacky      TheTriple.setArch(Type);
286198090Srdivacky  } else {
287193323Sed    std::string Err;
288198090Srdivacky    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
289198090Srdivacky    if (TheTarget == 0) {
290198090Srdivacky      errs() << argv[0] << ": error auto-selecting target for module '"
291198090Srdivacky             << Err << "'.  Please use the -march option to explicitly "
292198090Srdivacky             << "pick a target.\n";
293193323Sed      return 1;
294193323Sed    }
295193323Sed  }
296193323Sed
297193323Sed  // Package up features to be passed to target/subtarget
298193323Sed  std::string FeaturesStr;
299224133Sdim  if (MAttrs.size()) {
300193323Sed    SubtargetFeatures Features;
301193323Sed    for (unsigned i = 0; i != MAttrs.size(); ++i)
302193323Sed      Features.AddFeature(MAttrs[i]);
303193323Sed    FeaturesStr = Features.getString();
304193323Sed  }
305193323Sed
306221337Sdim  std::auto_ptr<TargetMachine>
307226584Sdim    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
308226584Sdim                                          MCPU, FeaturesStr,
309226584Sdim                                          RelocModel, CMModel));
310193323Sed  assert(target.get() && "Could not allocate target machine!");
311193323Sed  TargetMachine &Target = *target.get();
312193323Sed
313218885Sdim  if (DisableDotLoc)
314218885Sdim    Target.setMCUseLoc(false);
315218885Sdim
316221337Sdim  if (DisableCFI)
317221337Sdim    Target.setMCUseCFI(false);
318221337Sdim
319221337Sdim  // Disable .loc support for older OS X versions.
320221337Sdim  if (TheTriple.isMacOSX() &&
321221337Sdim      TheTriple.isMacOSXVersionLT(10, 6))
322221337Sdim    Target.setMCUseLoc(false);
323221337Sdim
324193323Sed  // Figure out where we are going to send the output...
325212793Sdim  OwningPtr<tool_output_file> Out
326212793Sdim    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
327212793Sdim  if (!Out) return 1;
328193323Sed
329193323Sed  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
330193323Sed  switch (OptLevel) {
331193323Sed  default:
332198090Srdivacky    errs() << argv[0] << ": invalid optimization level.\n";
333193323Sed    return 1;
334193323Sed  case ' ': break;
335193323Sed  case '0': OLvl = CodeGenOpt::None; break;
336198396Srdivacky  case '1': OLvl = CodeGenOpt::Less; break;
337193323Sed  case '2': OLvl = CodeGenOpt::Default; break;
338193323Sed  case '3': OLvl = CodeGenOpt::Aggressive; break;
339193323Sed  }
340193323Sed
341208599Srdivacky  // Build up all of the passes that we want to do to the module.
342208599Srdivacky  PassManager PM;
343198090Srdivacky
344208599Srdivacky  // Add the target data from the target machine, if it exists, or the module.
345208599Srdivacky  if (const TargetData *TD = Target.getTargetData())
346208599Srdivacky    PM.add(new TargetData(*TD));
347208599Srdivacky  else
348208599Srdivacky    PM.add(new TargetData(&mod));
349198090Srdivacky
350208599Srdivacky  // Override default to generate verbose assembly.
351208599Srdivacky  Target.setAsmVerbosityDefault(true);
352193323Sed
353212793Sdim  if (RelaxAll) {
354212793Sdim    if (FileType != TargetMachine::CGFT_ObjectFile)
355212793Sdim      errs() << argv[0]
356212793Sdim             << ": warning: ignoring -mc-relax-all because filetype != obj";
357212793Sdim    else
358212793Sdim      Target.setMCRelaxAll(true);
359208599Srdivacky  }
360198090Srdivacky
361212793Sdim  {
362212793Sdim    formatted_raw_ostream FOS(Out->os());
363193323Sed
364212793Sdim    // Ask the target to add backend passes as necessary.
365212793Sdim    if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
366212793Sdim      errs() << argv[0] << ": target does not support generation of this"
367212793Sdim             << " file type!\n";
368212793Sdim      return 1;
369212793Sdim    }
370193323Sed
371221337Sdim    // Before executing passes, print the final values of the LLVM options.
372221337Sdim    cl::PrintOptionValues();
373221337Sdim
374212793Sdim    PM.run(mod);
375212793Sdim  }
376212793Sdim
377212793Sdim  // Declare success.
378212793Sdim  Out->keep();
379212793Sdim
380193323Sed  return 0;
381193323Sed}
382