llc.cpp revision f2e292ce58ca07d9bbe3cad75f8baa35bd85964a
1//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 bytecode.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Bytecode/Reader.h"
17#include "llvm/CodeGen/LinkAllCodegenComponents.h"
18#include "llvm/Target/SubtargetFeature.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetMachineRegistry.h"
22#include "llvm/Transforms/Scalar.h"
23#include "llvm/Module.h"
24#include "llvm/PassManager.h"
25#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Compressor.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/PluginLoader.h"
30#include "llvm/Support/FileUtilities.h"
31#include "llvm/Analysis/Verifier.h"
32#include "llvm/System/Signals.h"
33#include "llvm/Config/config.h"
34#include "llvm/LinkAllVMCore.h"
35#include <fstream>
36#include <iostream>
37#include <memory>
38
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 bytecode>"), cl::init("-"));
47
48static cl::opt<std::string>
49OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50
51static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
52
53static cl::opt<bool> Fast("fast",
54      cl::desc("Generate code quickly, potentially sacrificing code quality"));
55
56static cl::opt<std::string>
57TargetTriple("mtriple", cl::desc("Override target triple for module"));
58
59static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
60MArch("march", cl::desc("Architecture to generate code for:"));
61
62static cl::opt<std::string>
63MCPU("mcpu",
64  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
65  cl::value_desc("cpu-name"),
66  cl::init(""));
67
68static cl::list<std::string>
69MAttrs("mattr",
70  cl::CommaSeparated,
71  cl::desc("Target specific attributes (-mattr=help for details)"),
72  cl::value_desc("a1,+a2,-a3,..."));
73
74cl::opt<TargetMachine::CodeGenFileType>
75FileType("filetype", cl::init(TargetMachine::AssemblyFile),
76  cl::desc("Choose a file type (not all types are supported by all targets):"),
77  cl::values(
78       clEnumValN(TargetMachine::AssemblyFile,    "asm",
79                  "  Emit an assembly ('.s') file"),
80       clEnumValN(TargetMachine::ObjectFile,    "obj",
81                  "  Emit a native object ('.o') file [experimental]"),
82       clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
83                  "  Emit a native dynamic library ('.so') file"
84                  " [experimental]"),
85       clEnumValEnd));
86
87cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
88                       cl::desc("Do not verify input module"));
89
90
91// GetFileNameRoot - Helper function to get the basename of a filename.
92static inline std::string
93GetFileNameRoot(const std::string &InputFilename) {
94  std::string IFN = InputFilename;
95  std::string outputFilename;
96  int Len = IFN.length();
97  if ((Len > 2) &&
98      IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
99    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
100  } else {
101    outputFilename = IFN;
102  }
103  return outputFilename;
104}
105
106static std::ostream *GetOutputStream(const char *ProgName) {
107  if (OutputFilename != "") {
108    if (OutputFilename == "-")
109      return &std::cout;
110
111    // Specified an output filename?
112    if (!Force && std::ifstream(OutputFilename.c_str())) {
113      // If force is not specified, make sure not to overwrite a file!
114      std::cerr << ProgName << ": error opening '" << OutputFilename
115                << "': file exists!\n"
116                << "Use -f command line argument to force output\n";
117      return 0;
118    }
119    // Make sure that the Out file gets unlinked from the disk if we get a
120    // SIGINT
121    sys::RemoveFileOnSignal(sys::Path(OutputFilename));
122
123    return new std::ofstream(OutputFilename.c_str());
124  }
125
126  if (InputFilename == "-") {
127    OutputFilename = "-";
128    return &std::cout;
129  }
130
131  OutputFilename = GetFileNameRoot(InputFilename);
132
133  switch (FileType) {
134  case TargetMachine::AssemblyFile:
135    if (MArch->Name[0] != 'c' || MArch->Name[1] != 0)  // not CBE
136      OutputFilename += ".s";
137    else
138      OutputFilename += ".cbe.c";
139    break;
140  case TargetMachine::ObjectFile:
141    OutputFilename += ".o";
142    break;
143  case TargetMachine::DynamicLibrary:
144    OutputFilename += LTDL_SHLIB_EXT;
145    break;
146  }
147
148  if (!Force && std::ifstream(OutputFilename.c_str())) {
149    // If force is not specified, make sure not to overwrite a file!
150    std::cerr << ProgName << ": error opening '" << OutputFilename
151                          << "': file exists!\n"
152                          << "Use -f command line argument to force output\n";
153    return 0;
154  }
155
156  // Make sure that the Out file gets unlinked from the disk if we get a
157  // SIGINT
158  sys::RemoveFileOnSignal(sys::Path(OutputFilename));
159
160  std::ostream *Out = new std::ofstream(OutputFilename.c_str());
161  if (!Out->good()) {
162    std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
163    delete Out;
164    return 0;
165  }
166
167  return Out;
168}
169
170// main - Entry point for the llc compiler.
171//
172int main(int argc, char **argv) {
173  llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
174  try {
175    cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
176    sys::PrintStackTraceOnErrorSignal();
177
178    // Load the module to be compiled...
179    std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename,
180                                            Compressor::decompressToNewBuffer));
181    if (M.get() == 0) {
182      std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
183      return 1;
184    }
185    Module &mod = *M.get();
186
187    // If we are supposed to override the target triple, do so now.
188    if (!TargetTriple.empty())
189      mod.setTargetTriple(TargetTriple);
190
191    // Allocate target machine.  First, check whether the user has
192    // explicitly specified an architecture to compile for.
193    if (MArch == 0) {
194      std::string Err;
195      MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
196      if (MArch == 0) {
197        std::cerr << argv[0] << ": error auto-selecting target for module '"
198                  << Err << "'.  Please use the -march option to explicitly "
199                  << "pick a target.\n";
200        return 1;
201      }
202    }
203
204    // Package up features to be passed to target/subtarget
205    std::string FeaturesStr;
206    if (MCPU.size() || MAttrs.size()) {
207      SubtargetFeatures Features;
208      Features.setCPU(MCPU);
209      for (unsigned i = 0; i != MAttrs.size(); ++i)
210        Features.AddFeature(MAttrs[i]);
211      FeaturesStr = Features.getString();
212    }
213
214    std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
215    assert(target.get() && "Could not allocate target machine!");
216    TargetMachine &Target = *target.get();
217
218    // Figure out where we are going to send the output...
219    std::ostream *Out = GetOutputStream(argv[0]);
220    if (Out == 0) return 1;
221
222    // If this target requires addPassesToEmitWholeFile, do it now.  This is
223    // used by strange things like the C backend.
224    if (Target.WantsWholeFile()) {
225      PassManager PM;
226      PM.add(new TargetData(*Target.getTargetData()));
227      if (!NoVerify)
228        PM.add(createVerifierPass());
229
230      // Ask the target to add backend passes as necessary.
231      if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
232        std::cerr << argv[0] << ": target does not support generation of this"
233                  << " file type!\n";
234        if (Out != &std::cout) delete Out;
235        // And the Out file is empty and useless, so remove it now.
236        sys::Path(OutputFilename).eraseFromDisk();
237        return 1;
238      }
239      PM.run(mod);
240    } else {
241      // Build up all of the passes that we want to do to the module.
242      FunctionPassManager Passes(new ExistingModuleProvider(M.get()));
243      Passes.add(new TargetData(*Target.getTargetData()));
244
245#ifndef NDEBUG
246      if (!NoVerify)
247        Passes.add(createVerifierPass());
248#endif
249
250      // Ask the target to add backend passes as necessary.
251      if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
252        std::cerr << argv[0] << ": target does not support generation of this"
253                  << " file type!\n";
254        if (Out != &std::cout) delete Out;
255        // And the Out file is empty and useless, so remove it now.
256        sys::Path(OutputFilename).eraseFromDisk();
257        return 1;
258      }
259
260      Passes.doInitialization();
261
262      // Run our queue of passes all at once now, efficiently.
263      // TODO: this could lazily stream functions out of the module.
264      for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
265        if (!I->isDeclaration())
266          Passes.run(*I);
267
268      Passes.doFinalization();
269    }
270
271    // Delete the ostream if it's not a stdout stream
272    if (Out != &std::cout) delete Out;
273
274    return 0;
275  } catch (const std::string& msg) {
276    std::cerr << argv[0] << ": " << msg << "\n";
277  } catch (...) {
278    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
279  }
280  return 1;
281}
282