For PR797:
[oota-llvm.git] / tools / gccld / GenerateCode.cpp
index f0466ddd334233e9e495b36f37ae42fb4af2b0b1..61bcdfae717ea063fa92be2bf068ad9ceadd4b51 100644 (file)
@@ -1,10 +1,10 @@
 //===- GenerateCode.cpp - Functions for generating executable files  ------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file was developed by the LLVM research group and is distributed under
 // the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
 // This file contains functions for generating executable files once linking
@@ -116,15 +116,13 @@ static void RemoveEnv(const char * name, char ** const envp) {
     else
       *p = '=';
   }
-
-  return;
 }
 
 static void dumpArgs(const char **args) {
-  std::cout << *args++;
+  std::cerr << *args++;
   while (*args)
-    std::cout << ' ' << *args++;
-  std::cout << '\n';
+    std::cerr << ' ' << *args++;
+  std::cerr << '\n' << std::flush;
 }
 
 static inline void addPass(PassManager &PM, Pass *P) {
@@ -150,45 +148,42 @@ static bool isBytecodeLibrary(const sys::Path &FullPath) {
 }
 
 static bool isBytecodeLPath(const std::string &LibPath) {
-  bool isBytecodeLPath = false;
-
-  // Make sure the -L path has a '/' character
-  // because llvm-g++ passes them without the ending
-  // '/' char and sys::Path doesn't think it is a 
-  // directory (see: sys::Path::isDirectory) without it 
-  std::string dir = LibPath;
-  if ( dir[dir.length()-1] != '/' )
-  dir.append("/");
-
-  sys::Path LPath(dir);
+  sys::Path LPath(LibPath);
 
+  // Make sure it exists and is a directory
+  sys::FileStatus Status;
+  if (LPath.getFileStatus(Status) || !Status.isDir)
+    return false;
+  
   // Grab the contents of the -L path
   std::set<sys::Path> Files;
-  LPath.getDirectoryContents(Files);
-
+  if (LPath.getDirectoryContents(Files, 0))
+    return false;
+  
   // Iterate over the contents one by one to determine
   // if this -L path has any bytecode shared libraries
   // or archives
   std::set<sys::Path>::iterator File = Files.begin();
+  std::string dllsuffix = sys::Path::GetDLLSuffix();
   for (; File != Files.end(); ++File) {
 
-    if ( File->isDirectory() )
+    // Not a file?
+    if (File->getFileStatus(Status) || Status.isDir)
       continue;
 
     std::string path = File->toString();
-    std::string dllsuffix = sys::Path::GetDLLSuffix();
 
-    // Check for an ending '.dll,.so' or '.a' suffix as all
+    // Check for an ending '.dll', '.so' or '.a' suffix as all
     // other files are not of interest to us here
-    if ( path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
-        && path.find(".a", path.size()-2) == std::string::npos )
+    if (path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
+        && path.find(".a", path.size()-2) == std::string::npos)
       continue;
 
     // Finally, check to see if the file is a true bytecode file
     if (isBytecodeLibrary(*File))
-      isBytecodeLPath = true;
+      return true;
   }
-  return isBytecodeLPath;
+  return false;
 }
 
 /// GenerateBytecode - generates a bytecode file from the specified module.
@@ -211,7 +206,7 @@ int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
   if (Verify) Passes.add(createVerifierPass());
 
   // Add an appropriate TargetData instance for this module...
-  addPass(Passes, new TargetData("gccld", M));
+  addPass(Passes, new TargetData(M));
 
   // Often if the programmer does not specify proper prototypes for the
   // functions they are calling, they end up calling a vararg version of the
@@ -220,12 +215,10 @@ int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
   addPass(Passes, createFunctionResolvingPass());
 
   if (!DisableOptimizations) {
-    if (Internalize) {
-      // Now that composite has been compiled, scan through the module, looking
-      // for a main function.  If main is defined, mark all other functions
-      // internal.
-      addPass(Passes, createInternalizePass());
-    }
+    // Now that composite has been compiled, scan through the module, looking
+    // for a main function.  If main is defined, mark all other functions
+    // internal.
+    addPass(Passes, createInternalizePass(Internalize));
 
     // Now that we internalized some globals, see if we can hack on them!
     addPass(Passes, createGlobalOptimizerPass());
@@ -305,6 +298,7 @@ int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
 int llvm::GenerateAssembly(const std::string &OutputFilename,
                            const std::string &InputFilename,
                            const sys::Path &llc,
+                           std::string& ErrMsg,
                            bool Verbose) {
   // Run LLC to convert the bytecode file into assembly code.
   std::vector<const char*> args;
@@ -315,14 +309,14 @@ int llvm::GenerateAssembly(const std::string &OutputFilename,
   args.push_back(InputFilename.c_str());
   args.push_back(0);
   if (Verbose) dumpArgs(&args[0]);
-  return sys::Program::ExecuteAndWait(llc, &args[0]);
+  return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
 }
 
-/// GenerateAssembly - generates a native assembly language source file from the
-/// specified bytecode file.
+/// GenerateCFile - generates a C source file from the specified bytecode file.
 int llvm::GenerateCFile(const std::string &OutputFile,
                         const std::string &InputFile,
                         const sys::Path &llc,
+                        std::string& ErrMsg,
                         bool Verbose) {
   // Run LLC to convert the bytecode file into C.
   std::vector<const char*> args;
@@ -334,11 +328,11 @@ int llvm::GenerateCFile(const std::string &OutputFile,
   args.push_back(InputFile.c_str());
   args.push_back(0);
   if (Verbose) dumpArgs(&args[0]);
-  return sys::Program::ExecuteAndWait(llc, &args[0]);
+  return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
 }
 
-/// GenerateNative - generates a native assembly language source file from the
-/// specified assembly source file.
+/// GenerateNative - generates a native executable file from the specified
+/// assembly source file.
 ///
 /// Inputs:
 ///  InputFilename  - The name of the output bytecode file.
@@ -358,8 +352,10 @@ int llvm::GenerateNative(const std::string &OutputFilename,
                          const std::vector<std::string> &Libraries,
                          const sys::Path &gcc, char ** const envp,
                          bool Shared,
-                         const std::string &RPath,
+                         bool ExportAllAsDynamic,
+                         const std::vector<std::string> &RPaths,
                          const std::string &SOName,
+                         std::string& ErrMsg,
                          bool Verbose) {
   // Remove these environment variables from the environment of the
   // programs that we will execute.  It appears that GCC sets these
@@ -392,43 +388,67 @@ int llvm::GenerateNative(const std::string &OutputFilename,
   args.push_back(OutputFilename.c_str());
   args.push_back(InputFilename.c_str());
 
+  // StringsToDelete - We don't want to call c_str() on temporary strings.
+  // If we need a temporary string, copy it here so that the memory is not
+  // reclaimed until after the exec call.  All of these strings are allocated
+  // with strdup.
+  std::vector<char*> StringsToDelete;
+
   if (Shared) args.push_back("-shared");
-  if (!RPath.empty()) {
-    std::string rp = "-Wl,-rpath," + RPath;
-    args.push_back(rp.c_str());
+  if (ExportAllAsDynamic) args.push_back("-export-dynamic");
+  if (!RPaths.empty()) {
+    for (std::vector<std::string>::const_iterator I = RPaths.begin(),
+        E = RPaths.end(); I != E; I++) {
+      std::string rp = "-Wl,-rpath," + *I;
+      StringsToDelete.push_back(strdup(rp.c_str()));
+      args.push_back(StringsToDelete.back());
+    }
   }
   if (!SOName.empty()) {
     std::string so = "-Wl,-soname," + SOName;
-    args.push_back(so.c_str());
+    StringsToDelete.push_back(strdup(so.c_str()));
+    args.push_back(StringsToDelete.back());
   }
 
   // Add in the libpaths to find the libraries.
   //
   // Note:
   //  When gccld is called from the llvm-gxx frontends, the -L paths for
-  //  the LLVM cfrontend install paths are appended.  We don't want the 
+  //  the LLVM cfrontend install paths are appended.  We don't want the
   //  native linker to use these -L paths as they contain bytecode files.
   //  Further, we don't want any -L paths that contain bytecode shared
   //  libraries or true bytecode archive files.  We omit them in all such
   //  cases.
-  for (unsigned index = 0; index < LibPaths.size(); index++) {
-    if (!isBytecodeLPath( LibPaths[index]) ) {
-      args.push_back("-L");
-      args.push_back(LibPaths[index].c_str());
+  for (unsigned index = 0; index < LibPaths.size(); index++)
+    if (!isBytecodeLPath(LibPaths[index])) {
+      std::string Tmp = "-L"+LibPaths[index];
+      StringsToDelete.push_back(strdup(Tmp.c_str()));
+      args.push_back(StringsToDelete.back());
     }
-  }
+
   // Add in the libraries to link.
-  for (unsigned index = 0; index < Libraries.size(); index++) {
-    if (Libraries[index] != "crtend") {
-      args.push_back("-l");
-      args.push_back(Libraries[index].c_str());
+  for (unsigned index = 0; index < Libraries.size(); index++)
+    // HACK: If this is libg, discard it.  This gets added by the compiler
+    // driver when doing: 'llvm-gcc main.c -Wl,-native -o a.out -g'. Note that
+    // this should really be fixed by changing the llvm-gcc compiler driver.
+    if (Libraries[index] != "crtend" && Libraries[index] != "g") {
+      std::string Tmp = "-l"+Libraries[index];
+      StringsToDelete.push_back(strdup(Tmp.c_str()));
+      args.push_back(StringsToDelete.back());
     }
-  }
-  args.push_back(0);
+  args.push_back(0); // Null terminate.
 
   // Run the compiler to assembly and link together the program.
   if (Verbose) dumpArgs(&args[0]);
-  return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
+  int Res = sys::Program::ExecuteAndWait(
+      gcc, &args[0],(const char**)clean_env,0,0,&ErrMsg);
+
+  delete [] clean_env;
+
+  while (!StringsToDelete.empty()) {
+    free(StringsToDelete.back());
+    StringsToDelete.pop_back();
+  }
+  return Res;
 }