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