llc.cpp revision c986392c30043c056608b06ddf2f10fdd35a8d5e
1//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
2//
3// This is the llc compiler driver.
4//
5//===----------------------------------------------------------------------===//
6
7#include "llvm/Bytecode/Reader.h"
8#include "llvm/Target/TargetMachineImpls.h"
9#include "llvm/Target/TargetMachine.h"
10#include "llvm/Transforms/Instrumentation.h"
11#include "llvm/Transforms/Scalar.h"
12#include "llvm/Transforms/Utils/Linker.h"
13#include "llvm/Assembly/PrintModulePass.h"
14#include "llvm/Bytecode/WriteBytecodePass.h"
15#include "llvm/Transforms/IPO.h"
16#include "llvm/Module.h"
17#include "llvm/PassManager.h"
18#include "llvm/Pass.h"
19#include "llvm/Support/PassNameParser.h"
20#include "Support/CommandLine.h"
21#include "Support/Signals.h"
22#include <memory>
23#include <fstream>
24using std::string;
25using std::cerr;
26
27//------------------------------------------------------------------------------
28// Option declarations for LLC.
29//------------------------------------------------------------------------------
30
31// Make all registered optimization passes available to llc.  These passes
32// will all be run before the simplification and lowering steps used by the
33// back-end code generator, and will be run in the order specified on the
34// command line. The OptimizationList is automatically populated with
35// registered Passes by the PassNameParser.
36//
37static cl::list<const PassInfo*, bool,
38                FilteredPassNameParser<PassInfo::Optimization> >
39OptimizationList(cl::desc("Optimizations available:"));
40
41
42// General options for llc.  Other pass-specific options are specified
43// within the corresponding llc passes, and target-specific options
44// and back-end code generation options are specified with the target machine.
45//
46static cl::opt<string>
47InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
48
49static cl::opt<string>
50OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53
54static cl::opt<bool>
55DumpAsm("d", cl::desc("Print bytecode before native code generation"),
56        cl::Hidden);
57
58static cl::opt<string>
59TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
60             cl::value_desc("directory"), cl::Hidden);
61
62
63// flags set from -tracem and -trace options to control tracing
64static bool TraceFunctions   = false;
65static bool TraceBasicBlocks = false;
66
67
68// GetFileNameRoot - Helper function to get the basename of a filename...
69static inline string
70GetFileNameRoot(const string &InputFilename)
71{
72  string IFN = InputFilename;
73  string outputFilename;
74  int Len = IFN.length();
75  if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
76    outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
77  } else {
78    outputFilename = IFN;
79  }
80  return outputFilename;
81}
82
83static bool
84insertTraceCodeFor(Module &M)
85{
86  PassManager Passes;
87
88  // Insert trace code in all functions in the module
89  if (TraceBasicBlocks)
90    Passes.add(createTraceValuesPassForBasicBlocks());
91  else if (TraceFunctions)
92    Passes.add(createTraceValuesPassForFunction());
93  else
94    return false;
95
96  // Eliminate duplication in constant pool
97  Passes.add(createConstantMergePass());
98
99  // Run passes to insert and clean up trace code...
100  Passes.run(M);
101
102  std::string ErrorMessage;
103
104  // Load the module that contains the runtime helper routines neccesary for
105  // pointer hashing and stuff...  link this module into the program if possible
106  //
107  Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");
108
109  // Check if the TraceLibPath contains a valid module.  If not, try to load
110  // the module from the current LLVM-GCC install directory.  This is kindof
111  // a hack, but allows people to not HAVE to have built the library.
112  //
113  if (TraceModule == 0)
114    TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
115                                    "gcc-lib/llvm/3.1/libinstr.bc");
116
117  // If we still didn't get it, cancel trying to link it in...
118  if (TraceModule == 0)
119    cerr << "Warning, could not load trace routines to link into program!\n";
120  else
121    {
122      // Link in the trace routines... if this fails, don't panic, because the
123      // compile should still succeed, but the native linker will probably fail.
124      //
125      std::auto_ptr<Module> TraceRoutines(TraceModule);
126      if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
127        cerr << "Warning: Error linking in trace routines: "
128             << ErrorMessage << "\n";
129    }
130
131  // Write out the module with tracing code just before code generation
132  assert (InputFilename != "-"
133          && "Cannot write out traced bytecode when reading input from stdin");
134  string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";
135
136  std::ofstream Out(TraceFilename.c_str());
137  if (!Out.good())
138    cerr << "Error opening '" << TraceFilename
139         << "'!: Skipping output of trace code as bytecode\n";
140  else
141    {
142      cerr << "Emitting trace code to '" << TraceFilename
143           << "' for comparison...\n";
144      WriteBytecodeToFile(&M, Out);
145    }
146
147  return true;
148}
149
150// Making tracing a module pass so the entire module with tracing
151// can be written out before continuing.
152struct InsertTracingCodePass: public Pass {
153  virtual bool run(Module &M) {
154    return insertTraceCodeFor(M);
155  }
156};
157
158
159//===---------------------------------------------------------------------===//
160// Function main()
161//
162// Entry point for the llc compiler.
163//===---------------------------------------------------------------------===//
164
165int
166main(int argc, char **argv)
167{
168  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
169
170  // Allocate a target... in the future this will be controllable on the
171  // command line.
172  std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
173  assert(target.get() && "Could not allocate target machine!");
174
175  TargetMachine &Target = *target.get();
176
177  // Load the module to be compiled...
178  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
179  if (M.get() == 0)
180    {
181      cerr << argv[0] << ": bytecode didn't read correctly.\n";
182      return 1;
183    }
184
185  // Build up all of the passes that we want to do to the module...
186  PassManager Passes;
187
188  // Create a new optimization pass for each one specified on the command line
189  // Deal specially with tracing passes, which must be run differently than opt.
190  //
191  for (unsigned i = 0; i < OptimizationList.size(); ++i)
192    {
193      const PassInfo *Opt = OptimizationList[i];
194
195      if (std::string(Opt->getPassArgument()) == "trace")
196        TraceFunctions = !(TraceBasicBlocks = true);
197      else if (std::string(Opt->getPassArgument()) == "tracem")
198        TraceFunctions = !(TraceBasicBlocks = false);
199      else
200        { // handle other passes as normal optimization passes
201          if (Opt->getNormalCtor())
202            Passes.add(Opt->getNormalCtor()());
203          else if (Opt->getTargetCtor())
204            Passes.add(Opt->getTargetCtor()(Target));
205          else
206            cerr << argv[0] << ": cannot create pass: "
207                 << Opt->getPassName() << "\n";
208        }
209    }
210
211  // Run tracing passes after other optimization passes and before llc passes.
212  if (TraceFunctions || TraceBasicBlocks)
213    Passes.add(new InsertTracingCodePass);
214
215  // Decompose multi-dimensional refs into a sequence of 1D refs
216  Passes.add(createDecomposeMultiDimRefsPass());
217
218  // Replace malloc and free instructions with library calls.
219  // Do this after tracing until lli implements these lib calls.
220  // For now, it will emulate malloc and free internally.
221  Passes.add(createLowerAllocationsPass());
222
223  // If LLVM dumping after transformations is requested, add it to the pipeline
224  if (DumpAsm)
225    Passes.add(new PrintFunctionPass("Code after xformations: \n", &cerr));
226
227  // Strip all of the symbols from the bytecode so that it will be smaller...
228  Passes.add(createSymbolStrippingPass());
229
230  // Figure out where we are going to send the output...
231  std::ostream *Out = 0;
232  if (OutputFilename != "")
233    {   // Specified an output filename?
234      if (!Force && std::ifstream(OutputFilename.c_str())) {
235        // If force is not specified, make sure not to overwrite a file!
236        cerr << argv[0] << ": error opening '" << OutputFilename
237             << "': file exists!\n"
238             << "Use -f command line argument to force output\n";
239        return 1;
240      }
241      Out = new std::ofstream(OutputFilename.c_str());
242
243      // Make sure that the Out file gets unlink'd from the disk if we get a
244      // SIGINT
245      RemoveFileOnSignal(OutputFilename);
246    }
247  else
248    {
249      if (InputFilename == "-")
250        {
251          OutputFilename = "-";
252          Out = &std::cout;
253        }
254      else
255        {
256          string OutputFilename = GetFileNameRoot(InputFilename);
257          OutputFilename += ".s";
258
259          if (!Force && std::ifstream(OutputFilename.c_str()))
260            {
261              // If force is not specified, make sure not to overwrite a file!
262              cerr << argv[0] << ": error opening '" << OutputFilename
263                   << "': file exists!\n"
264                   << "Use -f command line argument to force output\n";
265              return 1;
266            }
267
268          Out = new std::ofstream(OutputFilename.c_str());
269          if (!Out->good())
270            {
271              cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
272              delete Out;
273              return 1;
274            }
275
276          // Make sure that the Out file gets unlink'd from the disk if we get a
277          // SIGINT
278          RemoveFileOnSignal(OutputFilename);
279        }
280    }
281
282  // Ask the target to add backend passes as neccesary
283  if (Target.addPassesToEmitAssembly(Passes, *Out)) {
284    cerr << argv[0] << ": target '" << Target.getName()
285         << " does not support static compilation!\n";
286  } else {
287    // Run our queue of passes all at once now, efficiently.
288    Passes.run(*M.get());
289  }
290
291  // Delete the ostream if it's not a stdout stream
292  if (Out != &std::cout) delete Out;
293
294  return 0;
295}
296