1 //===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
3 // This is the llc compiler driver.
5 //===----------------------------------------------------------------------===//
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"
25 //------------------------------------------------------------------------------
26 // Option declarations for LLC.
27 //------------------------------------------------------------------------------
29 // Make all registered optimization passes available to llc. These passes
30 // will all be run before the simplification and lowering steps used by the
31 // back-end code generator, and will be run in the order specified on the
32 // command line. The OptimizationList is automatically populated with
33 // registered Passes by the PassNameParser.
35 static cl::list<const PassInfo*, bool,
36 FilteredPassNameParser<PassInfo::Optimization> >
37 OptimizationList(cl::desc("Optimizations available:"));
40 // General options for llc. Other pass-specific options are specified
41 // within the corresponding llc passes, and target-specific options
42 // and back-end code generation options are specified with the target machine.
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53 DumpAsm("d", cl::desc("Print bytecode before native code generation"),
56 static cl::opt<std::string>
57 TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
58 cl::value_desc("directory"), cl::Hidden);
61 // flags set from -tracem and -trace options to control tracing
62 static bool TraceFunctions = false;
63 static bool TraceBasicBlocks = false;
66 // GetFileNameRoot - Helper function to get the basename of a filename...
67 static inline std::string
68 GetFileNameRoot(const std::string &InputFilename)
70 std::string IFN = InputFilename;
71 std::string outputFilename;
72 int Len = IFN.length();
73 if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
74 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
78 return outputFilename;
82 insertTraceCodeFor(Module &M)
86 // Insert trace code in all functions in the module
88 Passes.add(createTraceValuesPassForBasicBlocks());
89 else if (TraceFunctions)
90 Passes.add(createTraceValuesPassForFunction());
94 // Eliminate duplication in constant pool
95 Passes.add(createConstantMergePass());
97 // Run passes to insert and clean up trace code...
100 std::string ErrorMessage;
102 // Load the module that contains the runtime helper routines neccesary for
103 // pointer hashing and stuff... link this module into the program if possible
105 Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");
107 // Check if the TraceLibPath contains a valid module. If not, try to load
108 // the module from the current LLVM-GCC install directory. This is kindof
109 // a hack, but allows people to not HAVE to have built the library.
111 if (TraceModule == 0)
112 TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
113 "gcc-lib/llvm/3.1/libinstr.bc");
115 // If we still didn't get it, cancel trying to link it in...
116 if (TraceModule == 0)
117 std::cerr <<"WARNING: couldn't load trace routines to link into program!\n";
120 // Link in the trace routines... if this fails, don't panic, because the
121 // compile should still succeed, but the native linker will probably fail.
123 std::auto_ptr<Module> TraceRoutines(TraceModule);
124 if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
125 std::cerr << "WARNING: Error linking in trace routines: "
126 << ErrorMessage << "\n";
129 // Write out the module with tracing code just before code generation
130 assert (InputFilename != "-"
131 && "Cannot write out traced bytecode when reading input from stdin");
132 std::string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";
134 std::ofstream Out(TraceFilename.c_str());
136 std::cerr << "Error opening '" << TraceFilename
137 << "'!: Skipping output of trace code as bytecode\n";
140 std::cerr << "Emitting trace code to '" << TraceFilename
141 << "' for comparison...\n";
142 WriteBytecodeToFile(&M, Out);
148 // Making tracing a module pass so the entire module with tracing
149 // can be written out before continuing.
150 struct InsertTracingCodePass: public Pass {
151 virtual bool run(Module &M) {
152 return insertTraceCodeFor(M);
157 //===---------------------------------------------------------------------===//
160 // Entry point for the llc compiler.
161 //===---------------------------------------------------------------------===//
164 main(int argc, char **argv)
166 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
168 // Allocate a target... in the future this will be controllable on the
170 std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
171 assert(target.get() && "Could not allocate target machine!");
173 TargetMachine &Target = *target.get();
174 const TargetData &TD = Target.getTargetData();
176 // Load the module to be compiled...
177 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
180 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
184 // Build up all of the passes that we want to do to the module...
187 Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getSubWordDataSize(),
188 TD.getIntegerRegSize(), TD.getPointerSize(),
189 TD.getPointerAlignment()));
191 // Create a new optimization pass for each one specified on the command line
192 // Deal specially with tracing passes, which must be run differently than opt.
194 for (unsigned i = 0; i < OptimizationList.size(); ++i)
196 const PassInfo *Opt = OptimizationList[i];
198 if (std::string(Opt->getPassArgument()) == "trace")
199 TraceFunctions = !(TraceBasicBlocks = true);
200 else if (std::string(Opt->getPassArgument()) == "tracem")
201 TraceFunctions = !(TraceBasicBlocks = false);
203 { // handle other passes as normal optimization passes
204 if (Opt->getNormalCtor())
205 Passes.add(Opt->getNormalCtor()());
206 else if (Opt->getTargetCtor())
207 Passes.add(Opt->getTargetCtor()(Target));
209 std::cerr << argv[0] << ": cannot create pass: "
210 << Opt->getPassName() << "\n";
214 // Run tracing passes after other optimization passes and before llc passes.
215 if (TraceFunctions || TraceBasicBlocks)
216 Passes.add(new InsertTracingCodePass);
218 // Decompose multi-dimensional refs into a sequence of 1D refs
219 Passes.add(createDecomposeMultiDimRefsPass());
221 // Replace malloc and free instructions with library calls.
222 // Do this after tracing until lli implements these lib calls.
223 // For now, it will emulate malloc and free internally.
224 Passes.add(createLowerAllocationsPass());
226 // If LLVM dumping after transformations is requested, add it to the pipeline
228 Passes.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));
230 // Strip all of the symbols from the bytecode so that it will be smaller...
231 Passes.add(createSymbolStrippingPass());
233 // Figure out where we are going to send the output...
234 std::ostream *Out = 0;
235 if (OutputFilename != "")
236 { // Specified an output filename?
237 if (!Force && std::ifstream(OutputFilename.c_str())) {
238 // If force is not specified, make sure not to overwrite a file!
239 std::cerr << argv[0] << ": error opening '" << OutputFilename
240 << "': file exists!\n"
241 << "Use -f command line argument to force output\n";
244 Out = new std::ofstream(OutputFilename.c_str());
246 // Make sure that the Out file gets unlink'd from the disk if we get a
248 RemoveFileOnSignal(OutputFilename);
252 if (InputFilename == "-")
254 OutputFilename = "-";
259 std::string OutputFilename = GetFileNameRoot(InputFilename);
260 OutputFilename += ".s";
262 if (!Force && std::ifstream(OutputFilename.c_str()))
264 // If force is not specified, make sure not to overwrite a file!
265 std::cerr << argv[0] << ": error opening '" << OutputFilename
266 << "': file exists!\n"
267 << "Use -f command line argument to force output\n";
271 Out = new std::ofstream(OutputFilename.c_str());
274 std::cerr << argv[0] << ": error opening " << OutputFilename
280 // Make sure that the Out file gets unlink'd from the disk if we get a
282 RemoveFileOnSignal(OutputFilename);
286 // Ask the target to add backend passes as neccesary
287 if (Target.addPassesToEmitAssembly(Passes, *Out)) {
288 std::cerr << argv[0] << ": target '" << Target.getName()
289 << " does not support static compilation!\n";
291 // Run our queue of passes all at once now, efficiently.
292 Passes.run(*M.get());
295 // Delete the ostream if it's not a stdout stream
296 if (Out != &std::cout) delete Out;