Convert to new simpler, more powerful pass structure
[oota-llvm.git] / tools / llc / llc.cpp
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/Sparc.h"
9 #include "llvm/Target/TargetMachine.h"
10 #include "llvm/Transforms/Instrumentation/TraceValues.h"
11 #include "llvm/Transforms/LowerAllocations.h"
12 #include "llvm/Transforms/HoistPHIConstants.h"
13 #include "llvm/Transforms/PrintModulePass.h"
14 #include "llvm/Support/CommandLine.h"
15 #include "llvm/Module.h"
16 #include "llvm/Method.h"
17 #include <memory>
18 #include <string>
19 #include <fstream>
20
21 cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
22 cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");
23 cl::Flag   Force         ("f", "Overwrite output files");
24 cl::Flag   DumpAsm       ("d", "Print bytecode before native code generation",
25                           cl::Hidden);
26 cl::Flag   DoNotEmitAssembly("noasm", "Do not emit assembly code", cl::Hidden);
27 cl::Flag   TraceBBValues ("trace",
28                           "Trace values at basic block and method exits");
29 cl::Flag   TraceMethodValues("tracem", "Trace values only at method exits");
30 cl::Flag   DebugTrace    ("dumptrace",
31                           "output trace code to a <fn>.trace.ll file",
32                           cl::Hidden);
33
34
35 // GetFileNameRoot - Helper function to get the basename of a filename...
36 static inline string GetFileNameRoot(const string &InputFilename) {
37   string IFN = InputFilename;
38   string outputFilename;
39   int Len = IFN.length();
40   if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
41     outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
42   } else {
43     outputFilename = IFN;
44   }
45   return outputFilename;
46 }
47
48
49 //===---------------------------------------------------------------------===//
50 // GenerateCodeForTarget Pass
51 // 
52 // Native code generation for a specified target.
53 //===---------------------------------------------------------------------===//
54
55 class GenerateCodeForTarget : public Pass {
56   TargetMachine &Target;
57 public:
58   inline GenerateCodeForTarget(TargetMachine &T) : Target(T) {}
59
60   // doPerMethodWork - This method does the actual work of generating code for
61   // the specified method.
62   //
63   bool doPerMethodWork(Method *M) {
64     if (!M->isExternal() && Target.compileMethod(M)) {
65       cerr << "Error compiling " << InputFilename << "!\n";
66       return true;
67     }
68     
69     return false;
70   }
71 };
72
73
74 //===---------------------------------------------------------------------===//
75 // EmitAssembly Pass
76 // 
77 // Write assembly code to specified output stream
78 //===---------------------------------------------------------------------===//
79
80 class EmitAssembly : public Pass {
81   const TargetMachine &Target;   // Target to compile for
82   ostream *Out;                  // Stream to print on
83   bool DeleteStream;             // Delete stream in dtor?
84 public:
85   inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
86     : Target(T), Out(O), DeleteStream(D) {}
87
88
89   virtual bool doPassFinalization(Module *M) {
90     // TODO: This should be performed as a moduleCleanup function, but we don't
91     // have one yet!
92     Target.emitAssembly(M, *Out);
93
94     if (DeleteStream) delete Out;
95     return false;
96   }
97 };
98
99
100 //===---------------------------------------------------------------------===//
101 // Function main()
102 // 
103 // Entry point for the llc compiler.
104 //===---------------------------------------------------------------------===//
105
106 int main(int argc, char **argv) {
107   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
108   
109   // Allocate a target... in the future this will be controllable on the
110   // command line.
111   auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
112   assert(target.get() && "Could not allocate target machine!");
113
114   TargetMachine &Target = *target.get();
115   
116   // Load the module to be compiled...
117   auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
118   if (M.get() == 0) {
119     cerr << "bytecode didn't read correctly.\n";
120     return 1;
121   }
122
123   // Build up all of the passes that we want to do to the module...
124   vector<Pass*> Passes;
125
126   // Replace malloc and free instructions with library calls
127   Passes.push_back(new LowerAllocations(Target.DataLayout));
128
129   // Hoist constants out of PHI nodes into predecessor BB's
130   Passes.push_back(new HoistPHIConstants());
131
132   if (TraceBBValues || TraceMethodValues)    // If tracing enabled...
133     // Insert trace code in all methods in the module
134     Passes.push_back(new InsertTraceCode(TraceBBValues, 
135                                          TraceBBValues || TraceMethodValues));
136
137
138   if (DebugTrace) {                          // If Trace Debugging is enabled...
139     // Then write the module with tracing code out in assembly form
140     assert(InputFilename != "-" && "files on stdin not supported with tracing");
141     string traceFileName = GetFileNameRoot(InputFilename) + ".trace.ll";
142
143     ostream *os = new ofstream(traceFileName.c_str(), 
144                                (Force ? 0 : ios::noreplace)|ios::out);
145     if (!os->good()) {
146       cerr << "Error opening " << traceFileName << "!\n";
147       delete os;
148       return 1;
149     }
150
151     Passes.push_back(new PrintModulePass("", os, true));
152   }
153
154   // If LLVM dumping after transformations is requested, add it to the pipeline
155   if (DumpAsm)
156     Passes.push_back(new PrintModulePass("Method after xformations: \n",&cerr));
157
158   // Generate Target code...
159   Passes.push_back(new GenerateCodeForTarget(Target));
160
161   if (!DoNotEmitAssembly) {                // If asm output is enabled...
162     // Figure out where we are going to send the output...
163     ostream *Out = 0;
164     if (OutputFilename != "") {   // Specified an output filename?
165       Out = new ofstream(OutputFilename.c_str(), 
166                          (Force ? 0 : ios::noreplace)|ios::out);
167     } else {
168       if (InputFilename == "-") {
169         OutputFilename = "-";
170         Out = &cout;
171       } else {
172         string OutputFilename = GetFileNameRoot(InputFilename); 
173         OutputFilename += ".s";
174         Out = new ofstream(OutputFilename.c_str(), 
175                            (Force ? 0 : ios::noreplace)|ios::out);
176         if (!Out->good()) {
177           cerr << "Error opening " << OutputFilename << "!\n";
178           delete Out;
179           return 1;
180         }
181       }
182     }
183     
184     // Output assembly language to the .s file
185     Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
186   }
187   
188   // Run our queue of passes all at once now, efficiently.  This form of
189   // runAllPasses frees the Pass objects after runAllPasses completes.
190   Pass::runAllPassesAndFree(M.get(), Passes);
191
192   return 0;
193 }
194
195