Fix PR139:\
[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/Linker.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Analysis/LoadValueNumbering.h"
21 #include "llvm/Analysis/Passes.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Bytecode/WriteBytecodePass.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/IPO.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/CommandLine.h"
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 /// CopyEnv - This function takes an array of environment variables and makes a
44 /// copy of it.  This copy can then be manipulated any way the caller likes
45 /// without affecting the process's real environment.
46 ///
47 /// Inputs:
48 ///  envp - An array of C strings containing an environment.
49 ///
50 /// Return value:
51 ///  NULL - An error occurred.
52 ///
53 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
54 ///  in the array is a duplicate of the one in the original array (i.e. we do
55 ///  not copy the char *'s from one array to another).
56 ///
57 static char ** CopyEnv(char ** const envp) {
58   // Count the number of entries in the old list;
59   unsigned entries;   // The number of entries in the old environment list
60   for (entries = 0; envp[entries] != NULL; entries++)
61     /*empty*/;
62
63   // Add one more entry for the NULL pointer that ends the list.
64   ++entries;
65
66   // If there are no entries at all, just return NULL.
67   if (entries == 0)
68     return NULL;
69
70   // Allocate a new environment list.
71   char **newenv = new char* [entries];
72   if ((newenv = new char* [entries]) == NULL)
73     return NULL;
74
75   // Make a copy of the list.  Don't forget the NULL that ends the list.
76   entries = 0;
77   while (envp[entries] != NULL) {
78     newenv[entries] = new char[strlen (envp[entries]) + 1];
79     strcpy (newenv[entries], envp[entries]);
80     ++entries;
81   }
82   newenv[entries] = NULL;
83
84   return newenv;
85 }
86
87
88 /// RemoveEnv - Remove the specified environment variable from the environment
89 /// array.
90 ///
91 /// Inputs:
92 ///  name - The name of the variable to remove.  It cannot be NULL.
93 ///  envp - The array of environment variables.  It cannot be NULL.
94 ///
95 /// Notes:
96 ///  This is mainly done because functions to remove items from the environment
97 ///  are not available across all platforms.  In particular, Solaris does not
98 ///  seem to have an unsetenv() function or a setenv() function (or they are
99 ///  undocumented if they do exist).
100 ///
101 static void RemoveEnv(const char * name, char ** const envp) {
102   for (unsigned index=0; envp[index] != NULL; index++) {
103     // Find the first equals sign in the array and make it an EOS character.
104     char *p = strchr (envp[index], '=');
105     if (p == NULL)
106       continue;
107     else
108       *p = '\0';
109
110     // Compare the two strings.  If they are equal, zap this string.
111     // Otherwise, restore it.
112     if (!strcmp(name, envp[index]))
113       *envp[index] = '\0';
114     else
115       *p = '=';
116   }
117
118   return;
119 }
120
121 static inline void addPass(PassManager &PM, Pass *P) {
122   // Add the pass to the pass manager...
123   PM.add(P);
124   
125   // If we are verifying all of the intermediate steps, add the verifier...
126   if (Verify) PM.add(createVerifierPass());
127 }
128
129 /// GenerateBytecode - generates a bytecode file from the specified module.
130 ///
131 /// Inputs:
132 ///  M           - The module for which bytecode should be generated.
133 ///  StripLevel  - 2 if we should strip all symbols, 1 if we should strip
134 ///                debug info.
135 ///  Internalize - Flags whether all symbols should be marked internal.
136 ///  Out         - Pointer to file stream to which to write the output.
137 ///
138 /// Returns non-zero value on error.
139 ///
140 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
141                            std::ostream *Out) {
142   // In addition to just linking the input from GCC, we also want to spiff it up
143   // a little bit.  Do this now.
144   PassManager Passes;
145
146   if (Verify) Passes.add(createVerifierPass());
147
148   // Add an appropriate TargetData instance for this module...
149   addPass(Passes, new TargetData("gccld", M));
150
151   // Often if the programmer does not specify proper prototypes for the
152   // functions they are calling, they end up calling a vararg version of the
153   // function that does not get a body filled in (the real function has typed
154   // arguments).  This pass merges the two functions.
155   addPass(Passes, createFunctionResolvingPass());
156
157   if (!DisableOptimizations) {
158     if (Internalize) {
159       // Now that composite has been compiled, scan through the module, looking
160       // for a main function.  If main is defined, mark all other functions
161       // internal.
162       addPass(Passes, createInternalizePass());
163     }
164
165     // Now that we internalized some globals, see if we can hack on them!
166     addPass(Passes, createGlobalOptimizerPass());
167
168     // Linking modules together can lead to duplicated global constants, only
169     // keep one copy of each constant...
170     addPass(Passes, createConstantMergePass());
171
172     // Propagate constants at call sites into the functions they call.
173     addPass(Passes, createIPConstantPropagationPass());
174
175     // Remove unused arguments from functions...
176     addPass(Passes, createDeadArgEliminationPass());
177
178     if (!DisableInline)
179       addPass(Passes, createFunctionInliningPass()); // Inline small functions
180
181     addPass(Passes, createPruneEHPass());            // Remove dead EH info
182     addPass(Passes, createGlobalOptimizerPass());    // Optimize globals again.
183     addPass(Passes, createGlobalDCEPass());          // Remove dead functions
184
185     // If we didn't decide to inline a function, check to see if we can
186     // transform it to pass arguments by value instead of by reference.
187     addPass(Passes, createArgumentPromotionPass());
188
189     // The IPO passes may leave cruft around.  Clean up after them.
190     addPass(Passes, createInstructionCombiningPass());
191
192     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
193
194     // Run a few AA driven optimizations here and now, to cleanup the code.
195     addPass(Passes, createGlobalsModRefPass());      // IP alias analysis
196
197     addPass(Passes, createLICMPass());               // Hoist loop invariants
198     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
199     addPass(Passes, createGCSEPass());               // Remove common subexprs
200     addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
201
202     // Cleanup and simplify the code after the scalar optimizations.
203     addPass(Passes, createInstructionCombiningPass());
204
205     // Delete basic blocks, which optimization passes may have killed...
206     addPass(Passes, createCFGSimplificationPass());
207
208     // Now that we have optimized the program, discard unreachable functions...
209     addPass(Passes, createGlobalDCEPass());
210   }
211
212   // If the -s or -S command line options were specified, strip the symbols out
213   // of the resulting program to make it smaller.  -s and -S are GLD options
214   // that we are supporting.
215   if (StripLevel)
216     addPass(Passes, createStripSymbolsPass(StripLevel == 1));
217
218   // Make sure everything is still good.
219   Passes.add(createVerifierPass());
220
221   // Add the pass that writes bytecode to the output file...
222   addPass(Passes, new WriteBytecodePass(Out));
223
224   // Run our queue of passes all at once now, efficiently.
225   Passes.run(*M);
226
227   return 0;
228 }
229
230 /// GenerateAssembly - generates a native assembly language source file from the
231 /// specified bytecode file.
232 ///
233 /// Inputs:
234 ///  InputFilename  - The name of the output bytecode file.
235 ///  OutputFilename - The name of the file to generate.
236 ///  llc            - The pathname to use for LLC.
237 ///  envp           - The environment to use when running LLC.
238 ///
239 /// Return non-zero value on error.
240 ///
241 int llvm::GenerateAssembly(const std::string &OutputFilename,
242                            const std::string &InputFilename,
243                            const std::string &llc,
244                            char ** const envp) {
245   // Run LLC to convert the bytecode file into assembly code.
246   const char *cmd[6];
247   cmd[0] = llc.c_str();
248   cmd[1] = "-f";
249   cmd[2] = "-o";
250   cmd[3] = OutputFilename.c_str();
251   cmd[4] = InputFilename.c_str();
252   cmd[5] = 0;
253
254   return ExecWait(cmd, envp);
255 }
256
257 /// GenerateAssembly - generates a native assembly language source file from the
258 /// specified bytecode file.
259 int llvm::GenerateCFile(const std::string &OutputFile,
260                         const std::string &InputFile,
261                         const std::string &llc, char ** const envp) {
262   // Run LLC to convert the bytecode file into C.
263   const char *cmd[7];
264
265   cmd[0] = llc.c_str();
266   cmd[1] = "-march=c";
267   cmd[2] = "-f";
268   cmd[3] = "-o";
269   cmd[4] = OutputFile.c_str();
270   cmd[5] = InputFile.c_str();
271   cmd[6] = 0;
272   return ExecWait(cmd, envp);
273 }
274
275 /// GenerateNative - generates a native assembly language source file from the
276 /// specified assembly source file.
277 ///
278 /// Inputs:
279 ///  InputFilename  - The name of the output bytecode file.
280 ///  OutputFilename - The name of the file to generate.
281 ///  Libraries      - The list of libraries with which to link.
282 ///  LibPaths       - The list of directories in which to find libraries.
283 ///  gcc            - The pathname to use for GGC.
284 ///  envp           - A copy of the process's current environment.
285 ///
286 /// Outputs:
287 ///  None.
288 ///
289 /// Returns non-zero value on error.
290 ///
291 int llvm::GenerateNative(const std::string &OutputFilename,
292                          const std::string &InputFilename,
293                          const std::vector<std::string> &Libraries,
294                          const std::vector<std::string> &LibPaths,
295                          const std::string &gcc, char ** const envp) {
296   // Remove these environment variables from the environment of the
297   // programs that we will execute.  It appears that GCC sets these
298   // environment variables so that the programs it uses can configure
299   // themselves identically.
300   //
301   // However, when we invoke GCC below, we want it to use its normal
302   // configuration.  Hence, we must sanitize its environment.
303   char ** clean_env = CopyEnv(envp);
304   if (clean_env == NULL)
305     return 1;
306   RemoveEnv("LIBRARY_PATH", clean_env);
307   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
308   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
309   RemoveEnv("COMPILER_PATH", clean_env);
310   RemoveEnv("COLLECT_GCC", clean_env);
311
312   std::vector<const char *> cmd;
313
314   // Run GCC to assemble and link the program into native code.
315   //
316   // Note:
317   //  We can't just assemble and link the file with the system assembler
318   //  and linker because we don't know where to put the _start symbol.
319   //  GCC mysteriously knows how to do it.
320   cmd.push_back(gcc.c_str());
321   cmd.push_back("-fno-strict-aliasing");
322   cmd.push_back("-O3");
323   cmd.push_back("-o");
324   cmd.push_back(OutputFilename.c_str());
325   cmd.push_back(InputFilename.c_str());
326
327   // Adding the library paths creates a problem for native generation.  If we
328   // include the search paths from llvmgcc, then we'll be telling normal gcc
329   // to look inside of llvmgcc's library directories for libraries.  This is
330   // bad because those libraries hold only bytecode files (not native object
331   // files).  In the end, we attempt to link the bytecode libgcc into a native
332   // program.
333 #if 0
334   // Add in the library path options.
335   for (unsigned index=0; index < LibPaths.size(); index++) {
336     cmd.push_back("-L");
337     cmd.push_back(LibPaths[index].c_str());
338   }
339 #endif
340
341   // Add in the libraries to link.
342   std::vector<std::string> Libs(Libraries);
343   for (unsigned index = 0; index < Libs.size(); index++) {
344     if (Libs[index] != "crtend") {
345       Libs[index] = "-l" + Libs[index];
346       cmd.push_back(Libs[index].c_str());
347     }
348   }
349   cmd.push_back(NULL);
350
351   // Run the compiler to assembly and link together the program.
352   return ExecWait(&(cmd[0]), clean_env);
353 }
354