Add a pointer to the owning LLVMContext to Module. This requires threading LLVMConte...
[oota-llvm.git] / tools / llvm-ld / llvm-ld.cpp
1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is intended to be compatible with GCC, and follows standard
11 // system 'ld' conventions.  As such, the default output file is ./a.out.
12 // Additionally, this program outputs a shell script that is used to invoke LLI
13 // to execute the program.  In this manner, the generated executable (a.out for
14 // example), is directly executable, whereas the bitcode file actually lives in
15 // the a.out.bc file generated by this program.  Also, Force is on by default.
16 //
17 // Note that if someone (or a script) deletes the executable program generated,
18 // the .bc file will be left around.  Considering that this is a temporary hack,
19 // I'm not too worried about this.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/System/Program.h"
27 #include "llvm/Module.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Streams.h"
39 #include "llvm/Support/SystemUtils.h"
40 #include "llvm/System/Signals.h"
41 #include "llvm/Config/config.h"
42 #include <fstream>
43 #include <memory>
44 #include <cstring>
45 using namespace llvm;
46
47 // Input/Output Options
48 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
49   cl::desc("<input bitcode files>"));
50
51 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
52   cl::desc("Override output filename"),
53   cl::value_desc("filename"));
54
55 static cl::opt<bool> Verbose("v",
56   cl::desc("Print information about actions taken"));
57
58 static cl::list<std::string> LibPaths("L", cl::Prefix,
59   cl::desc("Specify a library search path"),
60   cl::value_desc("directory"));
61
62 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
63   cl::desc("Specify a framework search path"),
64   cl::value_desc("directory"));
65
66 static cl::list<std::string> Libraries("l", cl::Prefix,
67   cl::desc("Specify libraries to link to"),
68   cl::value_desc("library prefix"));
69
70 static cl::list<std::string> Frameworks("framework",
71   cl::desc("Specify frameworks to link to"),
72   cl::value_desc("framework"));
73
74 // Options to control the linking, optimization, and code gen processes
75 static cl::opt<bool> LinkAsLibrary("link-as-library",
76   cl::desc("Link the .bc files together as a library, not an executable"));
77
78 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
79   cl::desc("Alias for -link-as-library"));
80
81 static cl::opt<bool> Native("native",
82   cl::desc("Generate a native binary instead of a shell script"));
83
84 static cl::opt<bool>NativeCBE("native-cbe",
85   cl::desc("Generate a native binary with the C backend and GCC"));
86
87 static cl::list<std::string> PostLinkOpts("post-link-opts",
88   cl::value_desc("path"),
89   cl::desc("Run one or more optimization programs after linking"));
90
91 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
92   cl::desc("Pass options to the system linker"));
93
94 // Compatibility options that llvm-ld ignores but are supported for 
95 // compatibility with LD
96 static cl::opt<std::string> CO3("soname", cl::Hidden,
97   cl::desc("Compatibility option: ignored"));
98
99 static cl::opt<std::string> CO4("version-script", cl::Hidden,
100   cl::desc("Compatibility option: ignored"));
101
102 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
103   cl::desc("Compatibility option: ignored"));
104
105 static  cl::opt<std::string> CO6("h", cl::Hidden,
106   cl::desc("Compatibility option: ignored"));
107
108 static cl::opt<bool> CO7("start-group", cl::Hidden, 
109   cl::desc("Compatibility option: ignored"));
110
111 static cl::opt<bool> CO8("end-group", cl::Hidden, 
112   cl::desc("Compatibility option: ignored"));
113
114 static cl::opt<std::string> CO9("m", cl::Hidden, 
115   cl::desc("Compatibility option: ignored"));
116
117 /// This is just for convenience so it doesn't have to be passed around
118 /// everywhere.
119 static std::string progname;
120
121 /// PrintAndExit - Prints a message to standard error and exits with error code
122 ///
123 /// Inputs:
124 ///  Message  - The message to print to standard error.
125 ///
126 static void PrintAndExit(const std::string &Message, int errcode = 1) {
127   cerr << progname << ": " << Message << "\n";
128   llvm_shutdown();
129   exit(errcode);
130 }
131
132 static void PrintCommand(const std::vector<const char*> &args) {
133   std::vector<const char*>::const_iterator I = args.begin(), E = args.end(); 
134   for (; I != E; ++I)
135     if (*I)
136       cout << "'" << *I << "'" << " ";
137   cout << "\n" << std::flush;
138 }
139
140 /// CopyEnv - This function takes an array of environment variables and makes a
141 /// copy of it.  This copy can then be manipulated any way the caller likes
142 /// without affecting the process's real environment.
143 ///
144 /// Inputs:
145 ///  envp - An array of C strings containing an environment.
146 ///
147 /// Return value:
148 ///  NULL - An error occurred.
149 ///
150 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
151 ///  in the array is a duplicate of the one in the original array (i.e. we do
152 ///  not copy the char *'s from one array to another).
153 ///
154 static char ** CopyEnv(char ** const envp) {
155   // Count the number of entries in the old list;
156   unsigned entries;   // The number of entries in the old environment list
157   for (entries = 0; envp[entries] != NULL; entries++)
158     /*empty*/;
159
160   // Add one more entry for the NULL pointer that ends the list.
161   ++entries;
162
163   // If there are no entries at all, just return NULL.
164   if (entries == 0)
165     return NULL;
166
167   // Allocate a new environment list.
168   char **newenv = new char* [entries];
169   if ((newenv = new char* [entries]) == NULL)
170     return NULL;
171
172   // Make a copy of the list.  Don't forget the NULL that ends the list.
173   entries = 0;
174   while (envp[entries] != NULL) {
175     newenv[entries] = new char[strlen (envp[entries]) + 1];
176     strcpy (newenv[entries], envp[entries]);
177     ++entries;
178   }
179   newenv[entries] = NULL;
180
181   return newenv;
182 }
183
184
185 /// RemoveEnv - Remove the specified environment variable from the environment
186 /// array.
187 ///
188 /// Inputs:
189 ///  name - The name of the variable to remove.  It cannot be NULL.
190 ///  envp - The array of environment variables.  It cannot be NULL.
191 ///
192 /// Notes:
193 ///  This is mainly done because functions to remove items from the environment
194 ///  are not available across all platforms.  In particular, Solaris does not
195 ///  seem to have an unsetenv() function or a setenv() function (or they are
196 ///  undocumented if they do exist).
197 ///
198 static void RemoveEnv(const char * name, char ** const envp) {
199   for (unsigned index=0; envp[index] != NULL; index++) {
200     // Find the first equals sign in the array and make it an EOS character.
201     char *p = strchr (envp[index], '=');
202     if (p == NULL)
203       continue;
204     else
205       *p = '\0';
206
207     // Compare the two strings.  If they are equal, zap this string.
208     // Otherwise, restore it.
209     if (!strcmp(name, envp[index]))
210       *envp[index] = '\0';
211     else
212       *p = '=';
213   }
214
215   return;
216 }
217
218 /// GenerateBitcode - generates a bitcode file from the module provided
219 void GenerateBitcode(Module* M, const std::string& FileName) {
220
221   if (Verbose)
222     cout << "Generating Bitcode To " << FileName << '\n';
223
224   // Create the output file.
225   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
226                                std::ios::binary;
227   std::ofstream Out(FileName.c_str(), io_mode);
228   if (!Out.good())
229     PrintAndExit("error opening '" + FileName + "' for writing!");
230
231   // Ensure that the bitcode file gets removed from the disk if we get a
232   // terminating signal.
233   sys::RemoveFileOnSignal(sys::Path(FileName));
234
235   // Write it out
236   WriteBitcodeToFile(M, Out);
237
238   // Close the bitcode file.
239   Out.close();
240 }
241
242 /// GenerateAssembly - generates a native assembly language source file from the
243 /// specified bitcode file.
244 ///
245 /// Inputs:
246 ///  InputFilename  - The name of the input bitcode file.
247 ///  OutputFilename - The name of the file to generate.
248 ///  llc            - The pathname to use for LLC.
249 ///  envp           - The environment to use when running LLC.
250 ///
251 /// Return non-zero value on error.
252 ///
253 static int GenerateAssembly(const std::string &OutputFilename,
254                             const std::string &InputFilename,
255                             const sys::Path &llc,
256                             std::string &ErrMsg ) {
257   // Run LLC to convert the bitcode file into assembly code.
258   std::vector<const char*> args;
259   args.push_back(llc.c_str());
260   // We will use GCC to assemble the program so set the assembly syntax to AT&T,
261   // regardless of what the target in the bitcode file is.
262   args.push_back("-x86-asm-syntax=att");
263   args.push_back("-f");
264   args.push_back("-o");
265   args.push_back(OutputFilename.c_str());
266   args.push_back(InputFilename.c_str());
267   args.push_back(0);
268
269   if (Verbose) {
270     cout << "Generating Assembly With: \n";
271     PrintCommand(args);
272   }
273
274   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
275 }
276
277 /// GenerateCFile - generates a C source file from the specified bitcode file.
278 static int GenerateCFile(const std::string &OutputFile,
279                          const std::string &InputFile,
280                          const sys::Path &llc,
281                          std::string& ErrMsg) {
282   // Run LLC to convert the bitcode file into C.
283   std::vector<const char*> args;
284   args.push_back(llc.c_str());
285   args.push_back("-march=c");
286   args.push_back("-f");
287   args.push_back("-o");
288   args.push_back(OutputFile.c_str());
289   args.push_back(InputFile.c_str());
290   args.push_back(0);
291
292   if (Verbose) {
293     cout << "Generating C Source With: \n";
294     PrintCommand(args);
295   }
296
297   return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
298 }
299
300 /// GenerateNative - generates a native object file from the
301 /// specified bitcode file.
302 ///
303 /// Inputs:
304 ///  InputFilename   - The name of the input bitcode file.
305 ///  OutputFilename  - The name of the file to generate.
306 ///  NativeLinkItems - The native libraries, files, code with which to link
307 ///  LibPaths        - The list of directories in which to find libraries.
308 ///  FrameworksPaths - The list of directories in which to find frameworks.
309 ///  Frameworks      - The list of frameworks (dynamic libraries)
310 ///  gcc             - The pathname to use for GGC.
311 ///  envp            - A copy of the process's current environment.
312 ///
313 /// Outputs:
314 ///  None.
315 ///
316 /// Returns non-zero value on error.
317 ///
318 static int GenerateNative(const std::string &OutputFilename,
319                           const std::string &InputFilename,
320                           const Linker::ItemList &LinkItems,
321                           const sys::Path &gcc, char ** const envp,
322                           std::string& ErrMsg) {
323   // Remove these environment variables from the environment of the
324   // programs that we will execute.  It appears that GCC sets these
325   // environment variables so that the programs it uses can configure
326   // themselves identically.
327   //
328   // However, when we invoke GCC below, we want it to use its normal
329   // configuration.  Hence, we must sanitize its environment.
330   char ** clean_env = CopyEnv(envp);
331   if (clean_env == NULL)
332     return 1;
333   RemoveEnv("LIBRARY_PATH", clean_env);
334   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
335   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
336   RemoveEnv("COMPILER_PATH", clean_env);
337   RemoveEnv("COLLECT_GCC", clean_env);
338
339
340   // Run GCC to assemble and link the program into native code.
341   //
342   // Note:
343   //  We can't just assemble and link the file with the system assembler
344   //  and linker because we don't know where to put the _start symbol.
345   //  GCC mysteriously knows how to do it.
346   std::vector<std::string> args;
347   args.push_back(gcc.c_str());
348   args.push_back("-fno-strict-aliasing");
349   args.push_back("-O3");
350   args.push_back("-o");
351   args.push_back(OutputFilename);
352   args.push_back(InputFilename);
353
354   // Add in the library and framework paths
355   for (unsigned index = 0; index < LibPaths.size(); index++) {
356     args.push_back("-L" + LibPaths[index]);
357   }
358   for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
359     args.push_back("-F" + FrameworkPaths[index]);
360   }
361
362   // Add the requested options
363   for (unsigned index = 0; index < XLinker.size(); index++)
364     args.push_back(XLinker[index]);
365
366   // Add in the libraries to link.
367   for (unsigned index = 0; index < LinkItems.size(); index++)
368     if (LinkItems[index].first != "crtend") {
369       if (LinkItems[index].second)
370         args.push_back("-l" + LinkItems[index].first);
371       else
372         args.push_back(LinkItems[index].first);
373     }
374
375   // Add in frameworks to link.
376   for (unsigned index = 0; index < Frameworks.size(); index++) {
377     args.push_back("-framework");
378     args.push_back(Frameworks[index]);
379   }
380       
381   // Now that "args" owns all the std::strings for the arguments, call the c_str
382   // method to get the underlying string array.  We do this game so that the
383   // std::string array is guaranteed to outlive the const char* array.
384   std::vector<const char *> Args;
385   for (unsigned i = 0, e = args.size(); i != e; ++i)
386     Args.push_back(args[i].c_str());
387   Args.push_back(0);
388
389   if (Verbose) {
390     cout << "Generating Native Executable With:\n";
391     PrintCommand(Args);
392   }
393
394   // Run the compiler to assembly and link together the program.
395   int R = sys::Program::ExecuteAndWait(
396     gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
397   delete [] clean_env;
398   return R;
399 }
400
401 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
402 /// bitcode file for the program.
403 static void EmitShellScript(char **argv) {
404   if (Verbose)
405     cout << "Emitting Shell Script\n";
406 #if defined(_WIN32) || defined(__CYGWIN__)
407   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
408   // support windows systems, we copy the llvm-stub.exe executable from the
409   // build tree to the destination file.
410   std::string ErrMsg;  
411   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
412   if (llvmstub.isEmpty())
413     PrintAndExit("Could not find llvm-stub.exe executable!");
414
415   if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
416     PrintAndExit(ErrMsg);
417
418   return;
419 #endif
420
421   // Output the script to start the program...
422   std::ofstream Out2(OutputFilename.c_str());
423   if (!Out2.good())
424     PrintAndExit("error opening '" + OutputFilename + "' for writing!");
425
426   Out2 << "#!/bin/sh\n";
427   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
428   Out2 << "lli=${LLVMINTERP-lli}\n";
429   Out2 << "exec $lli \\\n";
430   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
431   LibPaths.push_back("/lib");
432   LibPaths.push_back("/usr/lib");
433   LibPaths.push_back("/usr/X11R6/lib");
434   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
435   // shared object at all! See RH 8: plain text.
436   std::vector<std::string>::iterator libc =
437     std::find(Libraries.begin(), Libraries.end(), "c");
438   if (libc != Libraries.end()) Libraries.erase(libc);
439   // List all the shared object (native) libraries this executable will need
440   // on the command line, so that we don't have to do this manually!
441   for (std::vector<std::string>::iterator i = Libraries.begin(),
442          e = Libraries.end(); i != e; ++i) {
443     // try explicit -L arguments first:
444     sys::Path FullLibraryPath;
445     for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
446            E = LibPaths.end(); P != E; ++P) {
447       FullLibraryPath = *P;
448       FullLibraryPath.appendComponent("lib" + *i);
449       FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
450       if (!FullLibraryPath.isEmpty()) {
451         if (!FullLibraryPath.isDynamicLibrary()) {
452           // Not a native shared library; mark as invalid
453           FullLibraryPath = sys::Path();
454         } else break;
455       }
456     }
457     if (FullLibraryPath.isEmpty())
458       FullLibraryPath = sys::Path::FindLibrary(*i);
459     if (!FullLibraryPath.isEmpty())
460       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
461   }
462   Out2 << "    $0.bc ${1+\"$@\"}\n";
463   Out2.close();
464 }
465
466 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
467 // linker function by combining the Files and Libraries in the order they were
468 // declared on the command line.
469 static void BuildLinkItems(
470   Linker::ItemList& Items,
471   const cl::list<std::string>& Files,
472   const cl::list<std::string>& Libraries) {
473
474   // Build the list of linkage items for LinkItems.
475
476   cl::list<std::string>::const_iterator fileIt = Files.begin();
477   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
478
479   int libPos = -1, filePos = -1;
480   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
481     if (libIt != Libraries.end())
482       libPos = Libraries.getPosition(libIt - Libraries.begin());
483     else
484       libPos = -1;
485     if (fileIt != Files.end())
486       filePos = Files.getPosition(fileIt - Files.begin());
487     else
488       filePos = -1;
489
490     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
491       // Add a source file
492       Items.push_back(std::make_pair(*fileIt++, false));
493     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
494       // Add a library
495       Items.push_back(std::make_pair(*libIt++, true));
496     }
497   }
498 }
499
500 // Rightly this should go in a header file but it just seems such a waste.
501 namespace llvm {
502 extern void Optimize(Module*);
503 }
504
505 int main(int argc, char **argv, char **envp) {
506   // Print a stack trace if we signal out.
507   sys::PrintStackTraceOnErrorSignal();
508   PrettyStackTraceProgram X(argc, argv);
509
510   LLVMContext Context;
511   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
512   try {
513     // Initial global variable above for convenience printing of program name.
514     progname = sys::Path(argv[0]).getBasename();
515
516     // Parse the command line options
517     cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
518
519     // Construct a Linker (now that Verbose is set)
520     Linker TheLinker(progname, OutputFilename, &Context, Verbose);
521
522     // Keep track of the native link items (versus the bitcode items)
523     Linker::ItemList NativeLinkItems;
524
525     // Add library paths to the linker
526     TheLinker.addPaths(LibPaths);
527     TheLinker.addSystemPaths();
528
529     // Remove any consecutive duplicates of the same library...
530     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
531                     Libraries.end());
532
533     if (LinkAsLibrary) {
534       std::vector<sys::Path> Files;
535       for (unsigned i = 0; i < InputFilenames.size(); ++i )
536         Files.push_back(sys::Path(InputFilenames[i]));
537       if (TheLinker.LinkInFiles(Files))
538         return 1; // Error already printed
539
540       // The libraries aren't linked in but are noted as "dependent" in the
541       // module.
542       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
543            E = Libraries.end(); I != E ; ++I) {
544         TheLinker.getModule()->addLibrary(*I);
545       }
546     } else {
547       // Build a list of the items from our command line
548       Linker::ItemList Items;
549       BuildLinkItems(Items, InputFilenames, Libraries);
550
551       // Link all the items together
552       if (TheLinker.LinkInItems(Items, NativeLinkItems) )
553         return 1; // Error already printed
554     }
555
556     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
557
558     // Optimize the module
559     Optimize(Composite.get());
560
561 #if defined(_WIN32) || defined(__CYGWIN__)
562     if (!LinkAsLibrary) {
563       // Default to "a.exe" instead of "a.out".
564       if (OutputFilename.getNumOccurrences() == 0)
565         OutputFilename = "a.exe";
566
567       // If there is no suffix add an "exe" one.
568       sys::Path ExeFile( OutputFilename );
569       if (ExeFile.getSuffix() == "") {
570         ExeFile.appendSuffix("exe");
571         OutputFilename = ExeFile.toString();
572       }
573     }
574 #endif
575
576     // Generate the bitcode for the optimized module.
577     std::string RealBitcodeOutput = OutputFilename;
578
579     if (!LinkAsLibrary) RealBitcodeOutput += ".bc";
580     GenerateBitcode(Composite.get(), RealBitcodeOutput);
581
582     // If we are not linking a library, generate either a native executable
583     // or a JIT shell script, depending upon what the user wants.
584     if (!LinkAsLibrary) {
585       // If the user wants to run a post-link optimization, run it now.
586       if (!PostLinkOpts.empty()) {
587         std::vector<std::string> opts = PostLinkOpts;
588         for (std::vector<std::string>::iterator I = opts.begin(),
589              E = opts.end(); I != E; ++I) {
590           sys::Path prog(*I);
591           if (!prog.canExecute()) {
592             prog = sys::Program::FindProgramByName(*I);
593             if (prog.isEmpty())
594               PrintAndExit(std::string("Optimization program '") + *I +
595                 "' is not found or not executable.");
596           }
597           // Get the program arguments
598           sys::Path tmp_output("opt_result");
599           std::string ErrMsg;
600           if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
601             PrintAndExit(ErrMsg);
602
603           const char* args[4];
604           args[0] = I->c_str();
605           args[1] = RealBitcodeOutput.c_str();
606           args[2] = tmp_output.c_str();
607           args[3] = 0;
608           if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
609             if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
610               sys::Path target(RealBitcodeOutput);
611               target.eraseFromDisk();
612               if (tmp_output.renamePathOnDisk(target, &ErrMsg))
613                 PrintAndExit(ErrMsg, 2);
614             } else
615               PrintAndExit("Post-link optimization output is not bitcode");
616           } else {
617             PrintAndExit(ErrMsg);
618           }
619         }
620       }
621
622       // If the user wants to generate a native executable, compile it from the
623       // bitcode file.
624       //
625       // Otherwise, create a script that will run the bitcode through the JIT.
626       if (Native) {
627         // Name of the Assembly Language output file
628         sys::Path AssemblyFile ( OutputFilename);
629         AssemblyFile.appendSuffix("s");
630
631         // Mark the output files for removal if we get an interrupt.
632         sys::RemoveFileOnSignal(AssemblyFile);
633         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
634
635         // Determine the locations of the llc and gcc programs.
636         sys::Path llc = FindExecutable("llc", argv[0]);
637         if (llc.isEmpty())
638           PrintAndExit("Failed to find llc");
639
640         sys::Path gcc = FindExecutable("gcc", argv[0]);
641         if (gcc.isEmpty())
642           PrintAndExit("Failed to find gcc");
643
644         // Generate an assembly language file for the bitcode.
645         std::string ErrMsg;
646         if (0 != GenerateAssembly(AssemblyFile.toString(), RealBitcodeOutput,
647             llc, ErrMsg))
648           PrintAndExit(ErrMsg);
649
650         if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
651                                 NativeLinkItems, gcc, envp, ErrMsg))
652           PrintAndExit(ErrMsg);
653
654         // Remove the assembly language file.
655         AssemblyFile.eraseFromDisk();
656       } else if (NativeCBE) {
657         sys::Path CFile (OutputFilename);
658         CFile.appendSuffix("cbe.c");
659
660         // Mark the output files for removal if we get an interrupt.
661         sys::RemoveFileOnSignal(CFile);
662         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
663
664         // Determine the locations of the llc and gcc programs.
665         sys::Path llc = FindExecutable("llc", argv[0]);
666         if (llc.isEmpty())
667           PrintAndExit("Failed to find llc");
668
669         sys::Path gcc = FindExecutable("gcc", argv[0]);
670         if (gcc.isEmpty())
671           PrintAndExit("Failed to find gcc");
672
673         // Generate an assembly language file for the bitcode.
674         std::string ErrMsg;
675         if (0 != GenerateCFile(
676             CFile.toString(), RealBitcodeOutput, llc, ErrMsg))
677           PrintAndExit(ErrMsg);
678
679         if (0 != GenerateNative(OutputFilename, CFile.toString(), 
680                                 NativeLinkItems, gcc, envp, ErrMsg))
681           PrintAndExit(ErrMsg);
682
683         // Remove the assembly language file.
684         CFile.eraseFromDisk();
685
686       } else {
687         EmitShellScript(argv);
688       }
689
690       // Make the script executable...
691       std::string ErrMsg;
692       if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
693         PrintAndExit(ErrMsg);
694
695       // Make the bitcode file readable and directly executable in LLEE as well
696       if (sys::Path(RealBitcodeOutput).makeExecutableOnDisk(&ErrMsg))
697         PrintAndExit(ErrMsg);
698
699       if (sys::Path(RealBitcodeOutput).makeReadableOnDisk(&ErrMsg))
700         PrintAndExit(ErrMsg);
701     }
702   } catch (const std::string& msg) {
703     PrintAndExit(msg,2);
704   } catch (...) {
705     PrintAndExit("Unexpected unknown exception occurred.", 2);
706   }
707
708   // Graceful exit
709   return 0;
710 }