+static void PrintAndExit(const std::string &Message, int errcode = 1) {
+ cerr << progname << ": " << Message << "\n";
+ llvm_shutdown();
+ exit(errcode);
+}
+
+static void PrintCommand(const std::vector<const char*> &args) {
+ std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
+ for (; I != E; ++I)
+ if (*I)
+ cout << "'" << *I << "'" << " ";
+ cout << "\n" << std::flush;
+}
+
+/// CopyEnv - This function takes an array of environment variables and makes a
+/// copy of it. This copy can then be manipulated any way the caller likes
+/// without affecting the process's real environment.
+///
+/// Inputs:
+/// envp - An array of C strings containing an environment.
+///
+/// Return value:
+/// NULL - An error occurred.
+///
+/// Otherwise, a pointer to a new array of C strings is returned. Every string
+/// in the array is a duplicate of the one in the original array (i.e. we do
+/// not copy the char *'s from one array to another).
+///
+static char ** CopyEnv(char ** const envp) {
+ // Count the number of entries in the old list;
+ unsigned entries; // The number of entries in the old environment list
+ for (entries = 0; envp[entries] != NULL; entries++)
+ /*empty*/;
+
+ // Add one more entry for the NULL pointer that ends the list.
+ ++entries;
+
+ // If there are no entries at all, just return NULL.
+ if (entries == 0)
+ return NULL;
+
+ // Allocate a new environment list.
+ char **newenv = new char* [entries];
+ if ((newenv = new char* [entries]) == NULL)
+ return NULL;
+
+ // Make a copy of the list. Don't forget the NULL that ends the list.
+ entries = 0;
+ while (envp[entries] != NULL) {
+ newenv[entries] = new char[strlen (envp[entries]) + 1];
+ strcpy (newenv[entries], envp[entries]);
+ ++entries;
+ }
+ newenv[entries] = NULL;
+
+ return newenv;
+}
+
+
+/// RemoveEnv - Remove the specified environment variable from the environment
+/// array.
+///
+/// Inputs:
+/// name - The name of the variable to remove. It cannot be NULL.
+/// envp - The array of environment variables. It cannot be NULL.
+///
+/// Notes:
+/// This is mainly done because functions to remove items from the environment
+/// are not available across all platforms. In particular, Solaris does not
+/// seem to have an unsetenv() function or a setenv() function (or they are
+/// undocumented if they do exist).
+///
+static void RemoveEnv(const char * name, char ** const envp) {
+ for (unsigned index=0; envp[index] != NULL; index++) {
+ // Find the first equals sign in the array and make it an EOS character.
+ char *p = strchr (envp[index], '=');
+ if (p == NULL)
+ continue;
+ else
+ *p = '\0';
+
+ // Compare the two strings. If they are equal, zap this string.
+ // Otherwise, restore it.
+ if (!strcmp(name, envp[index]))
+ *envp[index] = '\0';
+ else
+ *p = '=';
+ }
+
+ return;
+}
+
+/// GenerateBitcode - generates a bitcode file from the module provided
+void GenerateBitcode(Module* M, const std::string& FileName) {
+
+ if (Verbose)
+ cout << "Generating Bitcode To " << FileName << '\n';
+
+ // Create the output file.
+ std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
+ std::ios::binary;
+ std::ofstream Out(FileName.c_str(), io_mode);
+ if (!Out.good())
+ PrintAndExit("error opening '" + FileName + "' for writing!");
+
+ // Ensure that the bitcode file gets removed from the disk if we get a
+ // terminating signal.
+ sys::RemoveFileOnSignal(sys::Path(FileName));
+
+ // Write it out
+ WriteBitcodeToFile(M, Out);
+
+ // Close the bitcode file.
+ Out.close();
+}
+
+/// GenerateAssembly - generates a native assembly language source file from the
+/// specified bitcode file.
+///
+/// Inputs:
+/// InputFilename - The name of the input bitcode file.
+/// OutputFilename - The name of the file to generate.
+/// llc - The pathname to use for LLC.
+/// envp - The environment to use when running LLC.
+///
+/// Return non-zero value on error.
+///
+static int GenerateAssembly(const std::string &OutputFilename,
+ const std::string &InputFilename,
+ const sys::Path &llc,
+ std::string &ErrMsg ) {
+ // Run LLC to convert the bitcode file into assembly code.
+ std::vector<const char*> args;
+ args.push_back(llc.c_str());
+ args.push_back("-f");
+ args.push_back("-o");
+ args.push_back(OutputFilename.c_str());
+ args.push_back(InputFilename.c_str());
+ args.push_back(0);
+
+ if (Verbose) {
+ cout << "Generating Assembly With: \n";
+ PrintCommand(args);
+ }
+
+ return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
+}
+
+/// GenerateCFile - generates a C source file from the specified bitcode file.
+static int GenerateCFile(const std::string &OutputFile,
+ const std::string &InputFile,
+ const sys::Path &llc,
+ std::string& ErrMsg) {
+ // Run LLC to convert the bitcode file into C.
+ std::vector<const char*> args;
+ args.push_back(llc.c_str());
+ args.push_back("-march=c");
+ args.push_back("-f");
+ args.push_back("-o");
+ args.push_back(OutputFile.c_str());
+ args.push_back(InputFile.c_str());
+ args.push_back(0);
+
+ if (Verbose) {
+ cout << "Generating C Source With: \n";
+ PrintCommand(args);
+ }
+
+ return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
+}
+
+/// GenerateNative - generates a native object file from the
+/// specified bitcode file.
+///
+/// Inputs:
+/// InputFilename - The name of the input bitcode file.
+/// OutputFilename - The name of the file to generate.
+/// NativeLinkItems - The native libraries, files, code with which to link
+/// LibPaths - The list of directories in which to find libraries.
+/// FrameworksPaths - The list of directories in which to find frameworks.
+/// Frameworks - The list of frameworks (dynamic libraries)
+/// gcc - The pathname to use for GGC.
+/// envp - A copy of the process's current environment.
+///
+/// Outputs:
+/// None.
+///
+/// Returns non-zero value on error.
+///
+static int GenerateNative(const std::string &OutputFilename,
+ const std::string &InputFilename,
+ const Linker::ItemList &LinkItems,
+ const sys::Path &gcc, char ** const envp,
+ std::string& ErrMsg) {
+ // Remove these environment variables from the environment of the
+ // programs that we will execute. It appears that GCC sets these
+ // environment variables so that the programs it uses can configure
+ // themselves identically.
+ //
+ // However, when we invoke GCC below, we want it to use its normal
+ // configuration. Hence, we must sanitize its environment.
+ char ** clean_env = CopyEnv(envp);
+ if (clean_env == NULL)
+ return 1;
+ RemoveEnv("LIBRARY_PATH", clean_env);
+ RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
+ RemoveEnv("GCC_EXEC_PREFIX", clean_env);
+ RemoveEnv("COMPILER_PATH", clean_env);
+ RemoveEnv("COLLECT_GCC", clean_env);
+
+
+ // Run GCC to assemble and link the program into native code.
+ //
+ // Note:
+ // We can't just assemble and link the file with the system assembler
+ // and linker because we don't know where to put the _start symbol.
+ // GCC mysteriously knows how to do it.
+ std::vector<std::string> args;
+ args.push_back(gcc.c_str());
+ args.push_back("-fno-strict-aliasing");
+ args.push_back("-O3");
+ args.push_back("-o");
+ args.push_back(OutputFilename);
+ args.push_back(InputFilename);
+
+ // Add in the library and framework paths
+ for (unsigned index = 0; index < LibPaths.size(); index++) {
+ args.push_back("-L" + LibPaths[index]);
+ }
+ for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
+ args.push_back("-F" + FrameworkPaths[index]);
+ }
+
+ // Add the requested options
+ for (unsigned index = 0; index < XLinker.size(); index++)
+ args.push_back(XLinker[index]);
+
+ // Add in the libraries to link.
+ for (unsigned index = 0; index < LinkItems.size(); index++)
+ if (LinkItems[index].first != "crtend") {
+ if (LinkItems[index].second)
+ args.push_back("-l" + LinkItems[index].first);
+ else
+ args.push_back(LinkItems[index].first);
+ }
+
+ // Add in frameworks to link.
+ for (unsigned index = 0; index < Frameworks.size(); index++) {
+ args.push_back("-framework");
+ args.push_back(Frameworks[index]);
+ }
+
+ // Now that "args" owns all the std::strings for the arguments, call the c_str
+ // method to get the underlying string array. We do this game so that the
+ // std::string array is guaranteed to outlive the const char* array.
+ std::vector<const char *> Args;
+ for (unsigned i = 0, e = args.size(); i != e; ++i)
+ Args.push_back(args[i].c_str());
+ Args.push_back(0);
+
+ if (Verbose) {
+ cout << "Generating Native Executable With:\n";
+ PrintCommand(Args);
+ }
+
+ // Run the compiler to assembly and link together the program.
+ int R = sys::Program::ExecuteAndWait(
+ gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
+ delete [] clean_env;
+ return R;