Run the new pass in gccld now that it passes all tests
[oota-llvm.git] / tools / gccld / GenerateCode.cpp
1 //===- GenerateCode.cpp - Functions for generating executable files  ------===//
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 file contains functions for generating executable files once linking
11 // has finished.  This includes generating a shell script to run the JIT or
12 // a native executable derived from the bytecode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "gccld.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Analysis/LoadValueNumbering.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Transforms/Utils/Linker.h"
26 #include "Support/SystemUtils.h"
27 #include "Support/CommandLine.h"
28
29 using namespace llvm;
30
31 namespace {
32   cl::opt<bool>
33   DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
34
35   cl::opt<bool>
36   Verify("verify", cl::desc("Verify intermediate results of all passes"));
37
38   cl::opt<bool>
39   DisableOptimizations("disable-opt",
40                        cl::desc("Do not run any optimization passes"));
41 }
42
43 namespace llvm {
44
45 static inline void addPass(PassManager &PM, Pass *P) {
46   // Add the pass to the pass manager...
47   PM.add(P);
48   
49   // If we are verifying all of the intermediate steps, add the verifier...
50   if (Verify) PM.add(createVerifierPass());
51 }
52
53 /// GenerateBytecode - generates a bytecode file from the specified module.
54 ///
55 /// Inputs:
56 ///  M           - The module for which bytecode should be generated.
57 ///  Strip       - Flags whether symbols should be stripped from the output.
58 ///  Internalize - Flags whether all symbols should be marked internal.
59 ///  Out         - Pointer to file stream to which to write the output.
60 ///
61 /// Outputs:
62 ///  None.
63 ///
64 /// Returns non-zero value on error.
65 ///
66 int
67 GenerateBytecode (Module *M, bool Strip, bool Internalize, std::ostream *Out) {
68   // In addition to just linking the input from GCC, we also want to spiff it up
69   // a little bit.  Do this now.
70   PassManager Passes;
71
72   if (Verify) Passes.add(createVerifierPass());
73
74   // Add an appropriate TargetData instance for this module...
75   addPass(Passes, new TargetData("gccld", M));
76
77   // Often if the programmer does not specify proper prototypes for the
78   // functions they are calling, they end up calling a vararg version of the
79   // function that does not get a body filled in (the real function has typed
80   // arguments).  This pass merges the two functions.
81   addPass(Passes, createFunctionResolvingPass());
82
83   if (!DisableOptimizations) {
84     if (Internalize) {
85       // Now that composite has been compiled, scan through the module, looking
86       // for a main function.  If main is defined, mark all other functions
87       // internal.
88       addPass(Passes, createInternalizePass());
89     }
90
91     // Now that we internalized some globals, see if we can mark any globals as
92     // being constant!
93     addPass(Passes, createGlobalConstifierPass());
94
95     // Linking modules together can lead to duplicated global constants, only
96     // keep one copy of each constant...
97     addPass(Passes, createConstantMergePass());
98
99     // If the -s command line option was specified, strip the symbols out of the
100     // resulting program to make it smaller.  -s is a GCC option that we are
101     // supporting.
102     if (Strip)
103       addPass(Passes, createSymbolStrippingPass());
104
105     // Propagate constants at call sites into the functions they call.
106     addPass(Passes, createIPConstantPropagationPass());
107
108     // Remove unused arguments from functions...
109     addPass(Passes, createDeadArgEliminationPass());
110
111     if (!DisableInline)
112       addPass(Passes, createFunctionInliningPass()); // Inline small functions
113
114     // If we didn't decide to inline a function, check to see if we can
115     // transform it to pass arguments by value instead of by reference.
116     addPass(Passes, createArgumentPromotionPass());
117
118     // The IPO passes may leave cruft around.  Clean up after them.
119     addPass(Passes, createInstructionCombiningPass());
120
121     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
122
123     // Run a few AA driven optimizations here and now, to cleanup the code.
124     // Eventually we should put an IP AA in place here.
125
126     addPass(Passes, createLICMPass());               // Hoist loop invariants
127     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
128     addPass(Passes, createGCSEPass());               // Remove common subexprs
129
130     // Cleanup and simplify the code after the scalar optimizations.
131     addPass(Passes, createInstructionCombiningPass());
132
133     // Delete basic blocks, which optimization passes may have killed...
134     addPass(Passes, createCFGSimplificationPass());
135
136     // Now that we have optimized the program, discard unreachable functions...
137     addPass(Passes, createGlobalDCEPass());
138   }
139
140   // Make sure everything is still good.
141   Passes.add(createVerifierPass());
142
143   // Add the pass that writes bytecode to the output file...
144   addPass(Passes, new WriteBytecodePass(Out));
145
146   // Run our queue of passes all at once now, efficiently.
147   Passes.run(*M);
148
149   return 0;
150 }
151
152 /// GenerateAssembly - generates a native assembly language source file from the
153 /// specified bytecode file.
154 ///
155 /// Inputs:
156 ///  InputFilename  - The name of the output bytecode file.
157 ///  OutputFilename - The name of the file to generate.
158 ///  llc            - The pathname to use for LLC.
159 ///  envp           - The environment to use when running LLC.
160 ///
161 /// Outputs:
162 ///  None.
163 ///
164 /// Return non-zero value on error.
165 ///
166 int
167 GenerateAssembly(const std::string &OutputFilename,
168                  const std::string &InputFilename,
169                  const std::string &llc,
170                  char ** const envp)
171 {
172   // Run LLC to convert the bytecode file into assembly code.
173   const char *cmd[8];
174
175   cmd[0] = llc.c_str();
176   cmd[1] = "-f";
177   cmd[2] = "-o";
178   cmd[3] = OutputFilename.c_str();
179   cmd[4] = InputFilename.c_str();
180   cmd[5] = NULL;
181
182   return ExecWait(cmd, envp);
183 }
184
185 /// GenerateNative - generates a native assembly language source file from the
186 /// specified assembly source file.
187 ///
188 /// Inputs:
189 ///  InputFilename  - The name of the output bytecode file.
190 ///  OutputFilename - The name of the file to generate.
191 ///  Libraries      - The list of libraries with which to link.
192 ///  LibPaths       - The list of directories in which to find libraries.
193 ///  gcc            - The pathname to use for GGC.
194 ///  envp           - A copy of the process's current environment.
195 ///
196 /// Outputs:
197 ///  None.
198 ///
199 /// Returns non-zero value on error.
200 ///
201 int
202 GenerateNative(const std::string &OutputFilename,
203                const std::string &InputFilename,
204                const std::vector<std::string> &Libraries,
205                const std::vector<std::string> &LibPaths,
206                const std::string &gcc,
207                char ** const envp) {
208   // Remove these environment variables from the environment of the
209   // programs that we will execute.  It appears that GCC sets these
210   // environment variables so that the programs it uses can configure
211   // themselves identically.
212   //
213   // However, when we invoke GCC below, we want it to use its normal
214   // configuration.  Hence, we must sanitize its environment.
215   char ** clean_env = CopyEnv(envp);
216   if (clean_env == NULL)
217     return 1;
218   RemoveEnv("LIBRARY_PATH", clean_env);
219   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
220   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
221   RemoveEnv("COMPILER_PATH", clean_env);
222   RemoveEnv("COLLECT_GCC", clean_env);
223
224   std::vector<const char *> cmd;
225
226   // Run GCC to assemble and link the program into native code.
227   //
228   // Note:
229   //  We can't just assemble and link the file with the system assembler
230   //  and linker because we don't know where to put the _start symbol.
231   //  GCC mysteriously knows how to do it.
232   cmd.push_back(gcc.c_str());
233   cmd.push_back("-o");
234   cmd.push_back(OutputFilename.c_str());
235   cmd.push_back(InputFilename.c_str());
236
237   // Adding the library paths creates a problem for native generation.  If we
238   // include the search paths from llvmgcc, then we'll be telling normal gcc
239   // to look inside of llvmgcc's library directories for libraries.  This is
240   // bad because those libraries hold only bytecode files (not native object
241   // files).  In the end, we attempt to link the bytecode libgcc into a native
242   // program.
243 #if 0
244   // Add in the library path options.
245   for (unsigned index=0; index < LibPaths.size(); index++) {
246     cmd.push_back("-L");
247     cmd.push_back(LibPaths[index].c_str());
248   }
249 #endif
250
251   // Add in the libraries to link.
252   std::vector<std::string> Libs(Libraries);
253   for (unsigned index = 0; index < Libs.size(); index++) {
254     if (Libs[index] != "crtend") {
255       Libs[index] = "-l" + Libs[index];
256       cmd.push_back(Libs[index].c_str());
257     }
258   }
259   cmd.push_back(NULL);
260
261   // Run the compiler to assembly and link together the program.
262   return ExecWait(&(cmd[0]), clean_env);
263 }
264
265 } // End llvm namespace