1 //===- GenerateCode.cpp - Functions for generating executable files ------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
35 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
38 Verify("verify", cl::desc("Verify intermediate results of all passes"));
41 DisableOptimizations("disable-opt",
42 cl::desc("Do not run any optimization passes"));
45 /// CopyEnv - This function takes an array of environment variables and makes a
46 /// copy of it. This copy can then be manipulated any way the caller likes
47 /// without affecting the process's real environment.
50 /// envp - An array of C strings containing an environment.
53 /// NULL - An error occurred.
55 /// Otherwise, a pointer to a new array of C strings is returned. Every string
56 /// in the array is a duplicate of the one in the original array (i.e. we do
57 /// not copy the char *'s from one array to another).
59 static char ** CopyEnv(char ** const envp) {
60 // Count the number of entries in the old list;
61 unsigned entries; // The number of entries in the old environment list
62 for (entries = 0; envp[entries] != NULL; entries++)
65 // Add one more entry for the NULL pointer that ends the list.
68 // If there are no entries at all, just return NULL.
72 // Allocate a new environment list.
73 char **newenv = new char* [entries];
74 if ((newenv = new char* [entries]) == NULL)
77 // Make a copy of the list. Don't forget the NULL that ends the list.
79 while (envp[entries] != NULL) {
80 newenv[entries] = new char[strlen (envp[entries]) + 1];
81 strcpy (newenv[entries], envp[entries]);
84 newenv[entries] = NULL;
90 /// RemoveEnv - Remove the specified environment variable from the environment
94 /// name - The name of the variable to remove. It cannot be NULL.
95 /// envp - The array of environment variables. It cannot be NULL.
98 /// This is mainly done because functions to remove items from the environment
99 /// are not available across all platforms. In particular, Solaris does not
100 /// seem to have an unsetenv() function or a setenv() function (or they are
101 /// undocumented if they do exist).
103 static void RemoveEnv(const char * name, char ** const envp) {
104 for (unsigned index=0; envp[index] != NULL; index++) {
105 // Find the first equals sign in the array and make it an EOS character.
106 char *p = strchr (envp[index], '=');
112 // Compare the two strings. If they are equal, zap this string.
113 // Otherwise, restore it.
114 if (!strcmp(name, envp[index]))
123 static void dumpArgs(const char **args) {
124 std::cout << *args++;
126 std::cout << ' ' << *args++;
130 static inline void addPass(PassManager &PM, Pass *P) {
131 // Add the pass to the pass manager...
134 // If we are verifying all of the intermediate steps, add the verifier...
135 if (Verify) PM.add(createVerifierPass());
138 static bool isBytecodeLibrary(const sys::Path &FullPath) {
139 // Check for a bytecode file
140 if (FullPath.isBytecodeFile()) return true;
141 // Check for a dynamic library file
142 if (FullPath.isDynamicLibrary()) return false;
143 // Check for a true bytecode archive file
144 if (FullPath.isArchive() ) {
145 std::string ErrorMessage;
146 Archive* ar = Archive::OpenAndLoadSymbols( FullPath, &ErrorMessage );
147 return ar->isBytecodeArchive();
152 static bool isBytecodeLPath(const std::string &LibPath) {
153 bool isBytecodeLPath = false;
155 sys::Path LPath(LibPath);
157 // Make sure it exists
159 return isBytecodeLPath;
161 // Make sure its a directory
164 if (!LPath.isDirectory())
165 return isBytecodeLPath;
167 catch (std::string& xcptn)
169 return isBytecodeLPath;
172 // Grab the contents of the -L path
173 std::set<sys::Path> Files;
174 LPath.getDirectoryContents(Files);
176 // Iterate over the contents one by one to determine
177 // if this -L path has any bytecode shared libraries
179 std::set<sys::Path>::iterator File = Files.begin();
180 for (; File != Files.end(); ++File) {
182 if ( File->isDirectory() )
185 std::string path = File->toString();
186 std::string dllsuffix = sys::Path::GetDLLSuffix();
188 // Check for an ending '.dll,.so' or '.a' suffix as all
189 // other files are not of interest to us here
190 if ( path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
191 && path.find(".a", path.size()-2) == std::string::npos )
194 // Finally, check to see if the file is a true bytecode file
195 if (isBytecodeLibrary(*File))
196 isBytecodeLPath = true;
198 return isBytecodeLPath;
201 /// GenerateBytecode - generates a bytecode file from the specified module.
204 /// M - The module for which bytecode should be generated.
205 /// StripLevel - 2 if we should strip all symbols, 1 if we should strip
207 /// Internalize - Flags whether all symbols should be marked internal.
208 /// Out - Pointer to file stream to which to write the output.
210 /// Returns non-zero value on error.
212 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
214 // In addition to just linking the input from GCC, we also want to spiff it up
215 // a little bit. Do this now.
218 if (Verify) Passes.add(createVerifierPass());
220 // Add an appropriate TargetData instance for this module...
221 addPass(Passes, new TargetData("gccld", M));
223 // Often if the programmer does not specify proper prototypes for the
224 // functions they are calling, they end up calling a vararg version of the
225 // function that does not get a body filled in (the real function has typed
226 // arguments). This pass merges the two functions.
227 addPass(Passes, createFunctionResolvingPass());
229 if (!DisableOptimizations) {
231 // Now that composite has been compiled, scan through the module, looking
232 // for a main function. If main is defined, mark all other functions
234 addPass(Passes, createInternalizePass());
237 // Now that we internalized some globals, see if we can hack on them!
238 addPass(Passes, createGlobalOptimizerPass());
240 // Linking modules together can lead to duplicated global constants, only
241 // keep one copy of each constant...
242 addPass(Passes, createConstantMergePass());
244 // Propagate constants at call sites into the functions they call.
245 addPass(Passes, createIPSCCPPass());
247 // Remove unused arguments from functions...
248 addPass(Passes, createDeadArgEliminationPass());
251 addPass(Passes, createFunctionInliningPass()); // Inline small functions
253 addPass(Passes, createPruneEHPass()); // Remove dead EH info
254 addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again.
255 addPass(Passes, createGlobalDCEPass()); // Remove dead functions
257 // If we didn't decide to inline a function, check to see if we can
258 // transform it to pass arguments by value instead of by reference.
259 addPass(Passes, createArgumentPromotionPass());
261 // The IPO passes may leave cruft around. Clean up after them.
262 addPass(Passes, createInstructionCombiningPass());
264 addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
266 // Run a few AA driven optimizations here and now, to cleanup the code.
267 addPass(Passes, createGlobalsModRefPass()); // IP alias analysis
269 addPass(Passes, createLICMPass()); // Hoist loop invariants
270 addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
271 addPass(Passes, createGCSEPass()); // Remove common subexprs
272 addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
274 // Cleanup and simplify the code after the scalar optimizations.
275 addPass(Passes, createInstructionCombiningPass());
277 // Delete basic blocks, which optimization passes may have killed...
278 addPass(Passes, createCFGSimplificationPass());
280 // Now that we have optimized the program, discard unreachable functions...
281 addPass(Passes, createGlobalDCEPass());
284 // If the -s or -S command line options were specified, strip the symbols out
285 // of the resulting program to make it smaller. -s and -S are GLD options
286 // that we are supporting.
288 addPass(Passes, createStripSymbolsPass(StripLevel == 1));
290 // Make sure everything is still good.
291 Passes.add(createVerifierPass());
293 // Add the pass that writes bytecode to the output file...
294 addPass(Passes, new WriteBytecodePass(Out));
296 // Run our queue of passes all at once now, efficiently.
302 /// GenerateAssembly - generates a native assembly language source file from the
303 /// specified bytecode file.
306 /// InputFilename - The name of the output bytecode file.
307 /// OutputFilename - The name of the file to generate.
308 /// llc - The pathname to use for LLC.
310 /// Return non-zero value on error.
312 int llvm::GenerateAssembly(const std::string &OutputFilename,
313 const std::string &InputFilename,
314 const sys::Path &llc,
316 // Run LLC to convert the bytecode file into assembly code.
317 std::vector<const char*> args;
318 args.push_back(llc.c_str());
319 args.push_back("-f");
320 args.push_back("-o");
321 args.push_back(OutputFilename.c_str());
322 args.push_back(InputFilename.c_str());
324 if (Verbose) dumpArgs(&args[0]);
325 return sys::Program::ExecuteAndWait(llc, &args[0]);
328 /// GenerateCFile - generates a C source file from the specified bytecode file.
329 int llvm::GenerateCFile(const std::string &OutputFile,
330 const std::string &InputFile,
331 const sys::Path &llc,
333 // Run LLC to convert the bytecode file into C.
334 std::vector<const char*> args;
335 args.push_back(llc.c_str());
336 args.push_back("-march=c");
337 args.push_back("-f");
338 args.push_back("-o");
339 args.push_back(OutputFile.c_str());
340 args.push_back(InputFile.c_str());
342 if (Verbose) dumpArgs(&args[0]);
343 return sys::Program::ExecuteAndWait(llc, &args[0]);
346 /// GenerateNative - generates a native executable file from the specified
347 /// assembly source file.
350 /// InputFilename - The name of the output bytecode file.
351 /// OutputFilename - The name of the file to generate.
352 /// Libraries - The list of libraries with which to link.
353 /// gcc - The pathname to use for GGC.
354 /// envp - A copy of the process's current environment.
359 /// Returns non-zero value on error.
361 int llvm::GenerateNative(const std::string &OutputFilename,
362 const std::string &InputFilename,
363 const std::vector<std::string> &LibPaths,
364 const std::vector<std::string> &Libraries,
365 const sys::Path &gcc, char ** const envp,
367 bool ExportAllAsDynamic,
368 const std::string &RPath,
369 const std::string &SOName,
371 // Remove these environment variables from the environment of the
372 // programs that we will execute. It appears that GCC sets these
373 // environment variables so that the programs it uses can configure
374 // themselves identically.
376 // However, when we invoke GCC below, we want it to use its normal
377 // configuration. Hence, we must sanitize its environment.
378 char ** clean_env = CopyEnv(envp);
379 if (clean_env == NULL)
381 RemoveEnv("LIBRARY_PATH", clean_env);
382 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
383 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
384 RemoveEnv("COMPILER_PATH", clean_env);
385 RemoveEnv("COLLECT_GCC", clean_env);
388 // Run GCC to assemble and link the program into native code.
391 // We can't just assemble and link the file with the system assembler
392 // and linker because we don't know where to put the _start symbol.
393 // GCC mysteriously knows how to do it.
394 std::vector<const char*> args;
395 args.push_back(gcc.c_str());
396 args.push_back("-fno-strict-aliasing");
397 args.push_back("-O3");
398 args.push_back("-o");
399 args.push_back(OutputFilename.c_str());
400 args.push_back(InputFilename.c_str());
402 if (Shared) args.push_back("-shared");
403 if (ExportAllAsDynamic) args.push_back("-export-dynamic");
404 if (!RPath.empty()) {
405 std::string rp = "-Wl,-rpath," + RPath;
406 args.push_back(rp.c_str());
408 if (!SOName.empty()) {
409 std::string so = "-Wl,-soname," + SOName;
410 args.push_back(so.c_str());
413 // Add in the libpaths to find the libraries.
416 // When gccld is called from the llvm-gxx frontends, the -L paths for
417 // the LLVM cfrontend install paths are appended. We don't want the
418 // native linker to use these -L paths as they contain bytecode files.
419 // Further, we don't want any -L paths that contain bytecode shared
420 // libraries or true bytecode archive files. We omit them in all such
422 for (unsigned index = 0; index < LibPaths.size(); index++) {
423 if (!isBytecodeLPath( LibPaths[index]) ) {
424 args.push_back("-L");
425 args.push_back(LibPaths[index].c_str());
429 // Add in the libraries to link.
430 for (unsigned index = 0; index < Libraries.size(); index++) {
431 if (Libraries[index] != "crtend") {
432 args.push_back("-l");
433 args.push_back(Libraries[index].c_str());
438 // Run the compiler to assembly and link together the program.
439 if (Verbose) dumpArgs(&args[0]);
440 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);