Trace code should always be exported just before code generation;
[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    ("debugtrace",
31                           "output trace code as assembly instead of bytecode");
32
33
34 // GetFileNameRoot - Helper function to get the basename of a filename...
35 static inline string GetFileNameRoot(const string &InputFilename) {
36   string IFN = InputFilename;
37   string outputFilename;
38   int Len = IFN.length();
39   if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
40     outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
41   } else {
42     outputFilename = IFN;
43   }
44   return outputFilename;
45 }
46
47
48 //===---------------------------------------------------------------------===//
49 // GenerateCodeForTarget Pass
50 // 
51 // Native code generation for a specified target.
52 //===---------------------------------------------------------------------===//
53
54 class GenerateCodeForTarget : public Pass {
55   TargetMachine &Target;
56 public:
57   inline GenerateCodeForTarget(TargetMachine &T) : Target(T) {}
58
59   // doPerMethodWork - This method does the actual work of generating code for
60   // the specified method.
61   //
62   bool doPerMethodWork(Method *M) {
63     if (!M->isExternal() && Target.compileMethod(M)) {
64       cerr << "Error compiling " << InputFilename << "!\n";
65       return true;
66     }
67     
68     return false;
69   }
70 };
71
72
73 //===---------------------------------------------------------------------===//
74 // EmitAssembly Pass
75 // 
76 // Write assembly code to specified output stream
77 //===---------------------------------------------------------------------===//
78
79 class EmitAssembly : public Pass {
80   const TargetMachine &Target;   // Target to compile for
81   ostream *Out;                  // Stream to print on
82   bool DeleteStream;             // Delete stream in dtor?
83 public:
84   inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
85     : Target(T), Out(O), DeleteStream(D) {}
86
87
88   virtual bool doPassFinalization(Module *M) {
89     // TODO: This should be performed as a moduleCleanup function, but we don't
90     // have one yet!
91     Target.emitAssembly(M, *Out);
92
93     if (DeleteStream) delete Out;
94     return false;
95   }
96 };
97
98
99 //===---------------------------------------------------------------------===//
100 // Function main()
101 // 
102 // Entry point for the llc compiler.
103 //===---------------------------------------------------------------------===//
104
105 int main(int argc, char **argv) {
106   int retCode = 0;
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     {
134       // Insert trace code in all methods in the module
135       Passes.push_back(new InsertTraceCode(TraceBBValues, 
136                                            TraceBBValues ||TraceMethodValues));
137       
138       // Then write out the module with tracing code before code generation 
139       assert(InputFilename != "-" &&
140              "files on stdin not supported with tracing");
141       string traceFileName = GetFileNameRoot(InputFilename)
142                              + (DebugTrace? ".trace.ll" : ".trace.bc");
143       ostream *os = new ofstream(traceFileName.c_str(), 
144                                  (Force ? 0 : ios::noreplace)|ios::out);
145       if (!os->good()) {
146         cerr << "Error opening " << traceFileName
147              << "! SKIPPING OUTPUT OF TRACE CODE\n";
148         delete os;
149         retCode = 1;
150       }
151       
152       Passes.push_back(new PrintModulePass("", os,
153                                            /*deleteStream*/ true,
154                                            /*printAsBytecode*/ ! DebugTrace));
155     }
156   
157   // If LLVM dumping after transformations is requested, add it to the pipeline
158   if (DumpAsm)
159     Passes.push_back(new PrintModulePass("Code after xformations: \n",&cerr));
160
161   // Generate Target code...
162   Passes.push_back(new GenerateCodeForTarget(Target));
163
164   if (!DoNotEmitAssembly) {                // If asm output is enabled...
165     // Figure out where we are going to send the output...
166     ostream *Out = 0;
167     if (OutputFilename != "") {   // Specified an output filename?
168       Out = new ofstream(OutputFilename.c_str(), 
169                          (Force ? 0 : ios::noreplace)|ios::out);
170     } else {
171       if (InputFilename == "-") {
172         OutputFilename = "-";
173         Out = &cout;
174       } else {
175         string OutputFilename = GetFileNameRoot(InputFilename); 
176         OutputFilename += ".s";
177         Out = new ofstream(OutputFilename.c_str(), 
178                            (Force ? 0 : ios::noreplace)|ios::out);
179         if (!Out->good()) {
180           cerr << "Error opening " << OutputFilename << "!\n";
181           delete Out;
182           return 1;
183         }
184       }
185     }
186     
187     // Output assembly language to the .s file
188     Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
189   }
190   
191   // Run our queue of passes all at once now, efficiently.  This form of
192   // runAllPasses frees the Pass objects after runAllPasses completes.
193   Pass::runAllPassesAndFree(M.get(), Passes);
194
195   return retCode;
196 }
197
198