Replacing std::iostreams with llvm iostreams. Some of these changes involve
[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/System/Program.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/Archive.h"
24 #include "llvm/Bytecode/WriteBytecodePass.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Support/SystemUtils.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Streams.h"
31 using namespace llvm;
32
33 namespace {
34   cl::opt<bool>
35   DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
36
37   cl::opt<bool>
38   Verify("verify", cl::desc("Verify intermediate results of all passes"));
39
40   cl::opt<bool>
41   DisableOptimizations("disable-opt",
42                        cl::desc("Do not run any optimization passes"));
43
44   cl::opt<bool>
45   NoCompress("disable-compression", cl::init(false),
46              cl::desc("Don't compress the generated bytecode"));
47 }
48
49 /// CopyEnv - This function takes an array of environment variables and makes a
50 /// copy of it.  This copy can then be manipulated any way the caller likes
51 /// without affecting the process's real environment.
52 ///
53 /// Inputs:
54 ///  envp - An array of C strings containing an environment.
55 ///
56 /// Return value:
57 ///  NULL - An error occurred.
58 ///
59 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
60 ///  in the array is a duplicate of the one in the original array (i.e. we do
61 ///  not copy the char *'s from one array to another).
62 ///
63 static char ** CopyEnv(char ** const envp) {
64   // Count the number of entries in the old list;
65   unsigned entries;   // The number of entries in the old environment list
66   for (entries = 0; envp[entries] != NULL; entries++)
67     /*empty*/;
68
69   // Add one more entry for the NULL pointer that ends the list.
70   ++entries;
71
72   // If there are no entries at all, just return NULL.
73   if (entries == 0)
74     return NULL;
75
76   // Allocate a new environment list.
77   char **newenv = new char* [entries];
78   if ((newenv = new char* [entries]) == NULL)
79     return NULL;
80
81   // Make a copy of the list.  Don't forget the NULL that ends the list.
82   entries = 0;
83   while (envp[entries] != NULL) {
84     newenv[entries] = new char[strlen (envp[entries]) + 1];
85     strcpy (newenv[entries], envp[entries]);
86     ++entries;
87   }
88   newenv[entries] = NULL;
89
90   return newenv;
91 }
92
93
94 /// RemoveEnv - Remove the specified environment variable from the environment
95 /// array.
96 ///
97 /// Inputs:
98 ///  name - The name of the variable to remove.  It cannot be NULL.
99 ///  envp - The array of environment variables.  It cannot be NULL.
100 ///
101 /// Notes:
102 ///  This is mainly done because functions to remove items from the environment
103 ///  are not available across all platforms.  In particular, Solaris does not
104 ///  seem to have an unsetenv() function or a setenv() function (or they are
105 ///  undocumented if they do exist).
106 ///
107 static void RemoveEnv(const char * name, char ** const envp) {
108   for (unsigned index=0; envp[index] != NULL; index++) {
109     // Find the first equals sign in the array and make it an EOS character.
110     char *p = strchr (envp[index], '=');
111     if (p == NULL)
112       continue;
113     else
114       *p = '\0';
115
116     // Compare the two strings.  If they are equal, zap this string.
117     // Otherwise, restore it.
118     if (!strcmp(name, envp[index]))
119       *envp[index] = '\0';
120     else
121       *p = '=';
122   }
123 }
124
125 static void dumpArgs(const char **args) {
126   llvm_cerr << *args++;
127   while (*args)
128     llvm_cerr << ' ' << *args++;
129   llvm_cerr << '\n' << std::flush;
130 }
131
132 static inline void addPass(PassManager &PM, Pass *P) {
133   // Add the pass to the pass manager...
134   PM.add(P);
135
136   // If we are verifying all of the intermediate steps, add the verifier...
137   if (Verify) PM.add(createVerifierPass());
138 }
139
140 static bool isBytecodeLibrary(const sys::Path &FullPath) {
141   // Check for a bytecode file
142   if (FullPath.isBytecodeFile()) return true;
143   // Check for a dynamic library file
144   if (FullPath.isDynamicLibrary()) return false;
145   // Check for a true bytecode archive file
146   if (FullPath.isArchive() ) {
147     std::string ErrorMessage;
148     Archive* ar = Archive::OpenAndLoadSymbols( FullPath, &ErrorMessage );
149     return ar->isBytecodeArchive();
150   }
151   return false;
152 }
153
154 static bool isBytecodeLPath(const std::string &LibPath) {
155   sys::Path LPath(LibPath);
156
157   // Make sure it exists and is a directory
158   sys::FileStatus Status;
159   if (LPath.getFileStatus(Status) || !Status.isDir)
160     return false;
161   
162   // Grab the contents of the -L path
163   std::set<sys::Path> Files;
164   if (LPath.getDirectoryContents(Files, 0))
165     return false;
166   
167   // Iterate over the contents one by one to determine
168   // if this -L path has any bytecode shared libraries
169   // or archives
170   std::set<sys::Path>::iterator File = Files.begin();
171   std::string dllsuffix = sys::Path::GetDLLSuffix();
172   for (; File != Files.end(); ++File) {
173
174     // Not a file?
175     if (File->getFileStatus(Status) || Status.isDir)
176       continue;
177
178     std::string path = File->toString();
179
180     // Check for an ending '.dll', '.so' or '.a' suffix as all
181     // other files are not of interest to us here
182     if (path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
183         && path.find(".a", path.size()-2) == std::string::npos)
184       continue;
185
186     // Finally, check to see if the file is a true bytecode file
187     if (isBytecodeLibrary(*File))
188       return true;
189   }
190   return false;
191 }
192
193 /// GenerateBytecode - generates a bytecode file from the specified module.
194 ///
195 /// Inputs:
196 ///  M           - The module for which bytecode should be generated.
197 ///  StripLevel  - 2 if we should strip all symbols, 1 if we should strip
198 ///                debug info.
199 ///  Internalize - Flags whether all symbols should be marked internal.
200 ///  Out         - Pointer to file stream to which to write the output.
201 ///
202 /// Returns non-zero value on error.
203 ///
204 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
205                            std::ostream *Out) {
206   // In addition to just linking the input from GCC, we also want to spiff it up
207   // a little bit.  Do this now.
208   PassManager Passes;
209
210   if (Verify) Passes.add(createVerifierPass());
211
212   // Add an appropriate TargetData instance for this module...
213   addPass(Passes, new TargetData(M));
214
215   // Often if the programmer does not specify proper prototypes for the
216   // functions they are calling, they end up calling a vararg version of the
217   // function that does not get a body filled in (the real function has typed
218   // arguments).  This pass merges the two functions.
219   addPass(Passes, createFunctionResolvingPass());
220
221   if (!DisableOptimizations) {
222     // Now that composite has been compiled, scan through the module, looking
223     // for a main function.  If main is defined, mark all other functions
224     // internal.
225     addPass(Passes, createInternalizePass(Internalize));
226
227     // Propagate constants at call sites into the functions they call.  This
228     // opens opportunities for globalopt (and inlining) by substituting function
229     // pointers passed as arguments to direct uses of functions.
230     addPass(Passes, createIPSCCPPass());
231     
232     // Now that we internalized some globals, see if we can hack on them!
233     addPass(Passes, createGlobalOptimizerPass());
234
235     // Linking modules together can lead to duplicated global constants, only
236     // keep one copy of each constant...
237     addPass(Passes, createConstantMergePass());
238
239     // Remove unused arguments from functions...
240     addPass(Passes, createDeadArgEliminationPass());
241
242     if (!DisableInline)
243       addPass(Passes, createFunctionInliningPass()); // Inline small functions
244
245     addPass(Passes, createPruneEHPass());            // Remove dead EH info
246     addPass(Passes, createGlobalOptimizerPass());    // Optimize globals again.
247     addPass(Passes, createGlobalDCEPass());          // Remove dead functions
248
249     // If we didn't decide to inline a function, check to see if we can
250     // transform it to pass arguments by value instead of by reference.
251     addPass(Passes, createArgumentPromotionPass());
252
253     // The IPO passes may leave cruft around.  Clean up after them.
254     addPass(Passes, createInstructionCombiningPass());
255
256     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
257
258     // Run a few AA driven optimizations here and now, to cleanup the code.
259     addPass(Passes, createGlobalsModRefPass());      // IP alias analysis
260
261     addPass(Passes, createLICMPass());               // Hoist loop invariants
262     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
263     addPass(Passes, createGCSEPass());               // Remove common subexprs
264     addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
265
266     // Cleanup and simplify the code after the scalar optimizations.
267     addPass(Passes, createInstructionCombiningPass());
268
269     // Delete basic blocks, which optimization passes may have killed...
270     addPass(Passes, createCFGSimplificationPass());
271
272     // Now that we have optimized the program, discard unreachable functions...
273     addPass(Passes, createGlobalDCEPass());
274   }
275
276   // If the -s or -S command line options were specified, strip the symbols out
277   // of the resulting program to make it smaller.  -s and -S are GLD options
278   // that we are supporting.
279   if (StripLevel)
280     addPass(Passes, createStripSymbolsPass(StripLevel == 1));
281
282   // Make sure everything is still good.
283   Passes.add(createVerifierPass());
284
285   // Add the pass that writes bytecode to the output file...
286   llvm_ostream L(*Out);
287   addPass(Passes, new WriteBytecodePass(&L, false, !NoCompress));
288
289   // Run our queue of passes all at once now, efficiently.
290   Passes.run(*M);
291
292   return 0;
293 }
294
295 /// GenerateAssembly - generates a native assembly language source file from the
296 /// specified bytecode file.
297 ///
298 /// Inputs:
299 ///  InputFilename  - The name of the output bytecode file.
300 ///  OutputFilename - The name of the file to generate.
301 ///  llc            - The pathname to use for LLC.
302 ///
303 /// Return non-zero value on error.
304 ///
305 int llvm::GenerateAssembly(const std::string &OutputFilename,
306                            const std::string &InputFilename,
307                            const sys::Path &llc,
308                            std::string& ErrMsg,
309                            bool Verbose) {
310   // Run LLC to convert the bytecode file into assembly code.
311   std::vector<const char*> args;
312   args.push_back(llc.c_str());
313   args.push_back("-f");
314   args.push_back("-o");
315   args.push_back(OutputFilename.c_str());
316   args.push_back(InputFilename.c_str());
317   args.push_back(0);
318   if (Verbose) dumpArgs(&args[0]);
319   return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
320 }
321
322 /// GenerateCFile - generates a C source file from the specified bytecode file.
323 int llvm::GenerateCFile(const std::string &OutputFile,
324                         const std::string &InputFile,
325                         const sys::Path &llc,
326                         std::string& ErrMsg,
327                         bool Verbose) {
328   // Run LLC to convert the bytecode file into C.
329   std::vector<const char*> args;
330   args.push_back(llc.c_str());
331   args.push_back("-march=c");
332   args.push_back("-f");
333   args.push_back("-o");
334   args.push_back(OutputFile.c_str());
335   args.push_back(InputFile.c_str());
336   args.push_back(0);
337   if (Verbose) dumpArgs(&args[0]);
338   return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
339 }
340
341 /// GenerateNative - generates a native executable file from the specified
342 /// assembly source file.
343 ///
344 /// Inputs:
345 ///  InputFilename  - The name of the output bytecode file.
346 ///  OutputFilename - The name of the file to generate.
347 ///  Libraries      - The list of libraries with which to link.
348 ///  gcc            - The pathname to use for GGC.
349 ///  envp           - A copy of the process's current environment.
350 ///
351 /// Outputs:
352 ///  None.
353 ///
354 /// Returns non-zero value on error.
355 ///
356 int llvm::GenerateNative(const std::string &OutputFilename,
357                          const std::string &InputFilename,
358                          const std::vector<std::string> &LibPaths,
359                          const std::vector<std::string> &Libraries,
360                          const sys::Path &gcc, char ** const envp,
361                          bool Shared,
362                          bool ExportAllAsDynamic,
363                          const std::vector<std::string> &RPaths,
364                          const std::string &SOName,
365                          std::string& ErrMsg,
366                          bool Verbose) {
367   // Remove these environment variables from the environment of the
368   // programs that we will execute.  It appears that GCC sets these
369   // environment variables so that the programs it uses can configure
370   // themselves identically.
371   //
372   // However, when we invoke GCC below, we want it to use its normal
373   // configuration.  Hence, we must sanitize its environment.
374   char ** clean_env = CopyEnv(envp);
375   if (clean_env == NULL)
376     return 1;
377   RemoveEnv("LIBRARY_PATH", clean_env);
378   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
379   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
380   RemoveEnv("COMPILER_PATH", clean_env);
381   RemoveEnv("COLLECT_GCC", clean_env);
382
383
384   // Run GCC to assemble and link the program into native code.
385   //
386   // Note:
387   //  We can't just assemble and link the file with the system assembler
388   //  and linker because we don't know where to put the _start symbol.
389   //  GCC mysteriously knows how to do it.
390   std::vector<const char*> args;
391   args.push_back(gcc.c_str());
392   args.push_back("-fno-strict-aliasing");
393   args.push_back("-O3");
394   args.push_back("-o");
395   args.push_back(OutputFilename.c_str());
396   args.push_back(InputFilename.c_str());
397
398   // StringsToDelete - We don't want to call c_str() on temporary strings.
399   // If we need a temporary string, copy it here so that the memory is not
400   // reclaimed until after the exec call.  All of these strings are allocated
401   // with strdup.
402   std::vector<char*> StringsToDelete;
403
404   if (Shared) args.push_back("-shared");
405   if (ExportAllAsDynamic) args.push_back("-export-dynamic");
406   if (!RPaths.empty()) {
407     for (std::vector<std::string>::const_iterator I = RPaths.begin(),
408         E = RPaths.end(); I != E; I++) {
409       std::string rp = "-Wl,-rpath," + *I;
410       StringsToDelete.push_back(strdup(rp.c_str()));
411       args.push_back(StringsToDelete.back());
412     }
413   }
414   if (!SOName.empty()) {
415     std::string so = "-Wl,-soname," + SOName;
416     StringsToDelete.push_back(strdup(so.c_str()));
417     args.push_back(StringsToDelete.back());
418   }
419
420   // Add in the libpaths to find the libraries.
421   //
422   // Note:
423   //  When gccld is called from the llvm-gxx frontends, the -L paths for
424   //  the LLVM cfrontend install paths are appended.  We don't want the
425   //  native linker to use these -L paths as they contain bytecode files.
426   //  Further, we don't want any -L paths that contain bytecode shared
427   //  libraries or true bytecode archive files.  We omit them in all such
428   //  cases.
429   for (unsigned index = 0; index < LibPaths.size(); index++)
430     if (!isBytecodeLPath(LibPaths[index])) {
431       std::string Tmp = "-L"+LibPaths[index];
432       StringsToDelete.push_back(strdup(Tmp.c_str()));
433       args.push_back(StringsToDelete.back());
434     }
435
436   // Add in the libraries to link.
437   for (unsigned index = 0; index < Libraries.size(); index++)
438     // HACK: If this is libg, discard it.  This gets added by the compiler
439     // driver when doing: 'llvm-gcc main.c -Wl,-native -o a.out -g'. Note that
440     // this should really be fixed by changing the llvm-gcc compiler driver.
441     if (Libraries[index] != "crtend" && Libraries[index] != "g") {
442       std::string Tmp = "-l"+Libraries[index];
443       StringsToDelete.push_back(strdup(Tmp.c_str()));
444       args.push_back(StringsToDelete.back());
445     }
446   args.push_back(0); // Null terminate.
447
448   // Run the compiler to assembly and link together the program.
449   if (Verbose) dumpArgs(&args[0]);
450   int Res = sys::Program::ExecuteAndWait(
451       gcc, &args[0],(const char**)clean_env,0,0,&ErrMsg);
452
453   delete [] clean_env;
454
455   while (!StringsToDelete.empty()) {
456     free(StringsToDelete.back());
457     StringsToDelete.pop_back();
458   }
459   return Res;
460 }
461