llc.cpp revision 7ac534f2343c033f7f583502b10b5d2a1639faf2
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/Target/SubtargetFeature.h"
18#include "llvm/Target/TargetMachine.h"
19#include "llvm/Target/TargetMachineRegistry.h"
20#include "llvm/Transforms/Scalar.h"
21#include "llvm/Module.h"
22#include "llvm/PassManager.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/PluginLoader.h"
26#include "llvm/Support/PassNameParser.h"
27#include "llvm/Support/FileUtilities.h"
28#include "llvm/Analysis/Verifier.h"
29#include "llvm/System/Signals.h"
30#include "llvm/Config/config.h"
31#include <fstream>
32#include <iostream>
33#include <memory>
34
35using namespace llvm;
36
37// General options for llc.  Other pass-specific options are specified
38// within the corresponding llc passes, and target-specific options
39// and back-end code generation options are specified with the target machine.
40//
41static cl::opt<std::string>
42InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
43
44static cl::opt<std::string>
45OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
46
47static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
48
49static cl::opt<bool> Fast("fast",
50      cl::desc("Generate code quickly, potentially sacrificing code quality"));
51
52static cl::opt<std::string>
53TargetTriple("mtriple", cl::desc("Override target triple for module"));
54
55static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
56MArch("march", cl::desc("Architecture to generate code for:"));
57
58static cl::opt<std::string>
59MCPU("mcpu",
60  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
61  cl::value_desc("cpu-name"),
62  cl::init(""));
63
64static cl::list<std::string>
65MAttrs("mattr",
66  cl::CommaSeparated,
67  cl::desc("Target specific attributes (-mattr=help for details)"),
68  cl::value_desc("a1,+a2,-a3,..."));
69
70cl::opt<TargetMachine::CodeGenFileType>
71FileType("filetype", cl::init(TargetMachine::AssemblyFile),
72  cl::desc("Choose a file type (not all types are supported by all targets):"),
73  cl::values(
74       clEnumValN(TargetMachine::AssemblyFile,    "asm",
75                  "  Emit an assembly ('.s') file"),
76       clEnumValN(TargetMachine::ObjectFile,    "obj",
77                  "  Emit a native object ('.o') file [experimental]"),
78       clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
79                  "  Emit a native dynamic library ('.so') file"),
80       clEnumValEnd));
81
82// The LLCPassList is populated with passes that were registered using
83//  PassInfo::LLC by the FilteredPassNameParser:
84cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::LLC> >
85LLCPassList(cl::desc("Passes Available"));
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
106
107// main - Entry point for the llc compiler.
108//
109int main(int argc, char **argv) {
110  try {
111    cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
112    sys::PrintStackTraceOnErrorSignal();
113
114    // Load the module to be compiled...
115    std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
116    if (M.get() == 0) {
117      std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
118      return 1;
119    }
120    Module &mod = *M.get();
121
122    // If we are supposed to override the target triple, do so now.
123    if (!TargetTriple.empty())
124      mod.setTargetTriple(TargetTriple);
125
126    // Allocate target machine.  First, check whether the user has
127    // explicitly specified an architecture to compile for.
128    TargetMachine* (*TargetMachineAllocator)(const Module&,
129                                             IntrinsicLowering *) = 0;
130    if (MArch == 0) {
131      std::string Err;
132      MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
133      if (MArch == 0) {
134        std::cerr << argv[0] << ": error auto-selecting target for module '"
135                  << Err << "'.  Please use the -march option to explicitly "
136                  << "pick a target.\n";
137        return 1;
138      }
139    }
140
141    // Package up features to be passed to target/subtarget
142    std::string FeaturesStr;
143    if (MCPU.size() || MAttrs.size()) {
144      SubtargetFeatures Features;
145      Features.setCPU(MCPU);
146      for (unsigned i = 0; i != MAttrs.size(); ++i)
147        Features.AddFeature(MAttrs[i]);
148      FeaturesStr = Features.getString();
149    }
150
151    std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, 0, FeaturesStr));
152    assert(target.get() && "Could not allocate target machine!");
153    TargetMachine &Target = *target.get();
154    const TargetData &TD = Target.getTargetData();
155
156    // Build up all of the passes that we want to do to the module...
157    PassManager Passes;
158    Passes.add(new TargetData(TD));
159
160    // Create a new pass for each one specified on the command line
161    for (unsigned i = 0; i < LLCPassList.size(); ++i) {
162      const PassInfo *aPass = LLCPassList[i];
163
164      if (aPass->getNormalCtor()) {
165        Pass *P = aPass->getNormalCtor()();
166        Passes.add(P);
167      } else {
168        std::cerr << argv[0] << ": cannot create pass: "
169                  << aPass->getPassName() << "\n";
170      }
171    }
172
173#ifndef NDEBUG
174    if(!NoVerify)
175      Passes.add(createVerifierPass());
176#endif
177
178    // Figure out where we are going to send the output...
179    std::ostream *Out = 0;
180    if (OutputFilename != "") {
181      if (OutputFilename != "-") {
182        // Specified an output filename?
183        if (!Force && std::ifstream(OutputFilename.c_str())) {
184          // If force is not specified, make sure not to overwrite a file!
185          std::cerr << argv[0] << ": error opening '" << OutputFilename
186                    << "': file exists!\n"
187                    << "Use -f command line argument to force output\n";
188          return 1;
189        }
190        Out = new std::ofstream(OutputFilename.c_str());
191
192        // Make sure that the Out file gets unlinked from the disk if we get a
193        // SIGINT
194        sys::RemoveFileOnSignal(sys::Path(OutputFilename));
195      } else {
196        Out = &std::cout;
197      }
198    } else {
199      if (InputFilename == "-") {
200        OutputFilename = "-";
201        Out = &std::cout;
202      } else {
203        OutputFilename = GetFileNameRoot(InputFilename);
204
205        switch (FileType) {
206        case TargetMachine::AssemblyFile:
207          if (MArch->Name[0] != 'c' || MArch->Name[1] != 0)  // not CBE
208            OutputFilename += ".s";
209          else
210            OutputFilename += ".cbe.c";
211          break;
212        case TargetMachine::ObjectFile:
213          OutputFilename += ".o";
214          break;
215        case TargetMachine::DynamicLibrary:
216          OutputFilename += LTDL_SHLIB_EXT;
217          break;
218        }
219
220        if (!Force && std::ifstream(OutputFilename.c_str())) {
221          // If force is not specified, make sure not to overwrite a file!
222          std::cerr << argv[0] << ": error opening '" << OutputFilename
223                    << "': file exists!\n"
224                    << "Use -f command line argument to force output\n";
225          return 1;
226        }
227
228        Out = new std::ofstream(OutputFilename.c_str());
229        if (!Out->good()) {
230          std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
231          delete Out;
232          return 1;
233        }
234
235        // Make sure that the Out file gets unlinked from the disk if we get a
236        // SIGINT
237        sys::RemoveFileOnSignal(sys::Path(OutputFilename));
238      }
239    }
240
241    // Ask the target to add backend passes as necessary.
242    if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
243      std::cerr << argv[0] << ": target '" << Target.getName()
244                << "' does not support generation of this file type!\n";
245      if (Out != &std::cout) delete Out;
246      // And the Out file is empty and useless, so remove it now.
247      sys::Path(OutputFilename).eraseFromDisk();
248      return 1;
249    } else {
250      // Run our queue of passes all at once now, efficiently.
251      Passes.run(*M.get());
252    }
253
254    // Delete the ostream if it's not a stdout stream
255    if (Out != &std::cout) delete Out;
256
257    return 0;
258  } catch (const std::string& msg) {
259    std::cerr << argv[0] << ": " << msg << "\n";
260  } catch (...) {
261    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
262  }
263  return 1;
264}
265