For PR521:
[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 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 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 bytecode 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/Linker.h"
24 #include "llvm/System/Program.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/Writer.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/System/Signals.h"
36 #include <fstream>
37 #include <iostream>
38 #include <memory>
39
40 using namespace llvm;
41
42 // Input/Output Options
43 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44   cl::desc("<input bytecode files>"));
45
46 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
47   cl::desc("Override output filename"),
48   cl::value_desc("filename"));
49
50 static cl::opt<bool> Verbose("v",
51   cl::desc("Print information about actions taken"));
52
53 static cl::list<std::string> LibPaths("L", cl::Prefix,
54   cl::desc("Specify a library search path"),
55   cl::value_desc("directory"));
56
57 static cl::list<std::string> Libraries("l", cl::Prefix,
58   cl::desc("Specify libraries to link to"),
59   cl::value_desc("library prefix"));
60
61 static cl::opt<bool> LinkAsLibrary("link-as-library",
62   cl::desc("Link the .bc files together as a library, not an executable"));
63
64 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65   cl::desc("Alias for -link-as-library"));
66
67 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
68   MachineArch("march", cl::desc("Architecture to generate assembly for:"));
69
70 static cl::opt<bool> Native("native",
71   cl::desc("Generate a native binary instead of a shell script"));
72
73 static cl::opt<bool>NativeCBE("native-cbe",
74   cl::desc("Generate a native binary with the C backend and GCC"));
75
76 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77   cl::desc("Disable writing of compressed bytecode files"));
78
79 static cl::list<std::string> PostLinkOpts("post-link-opts",
80   cl::value_desc("path to post-link optimization programs"),
81   cl::desc("Run one or more optimization programs after linking"));
82
83 // Compatibility options that are ignored but supported by LD
84 static cl::opt<std::string> CO3("soname", cl::Hidden,
85   cl::desc("Compatibility option: ignored"));
86
87 static cl::opt<std::string> CO4("version-script", cl::Hidden,
88   cl::desc("Compatibility option: ignored"));
89
90 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
91   cl::desc("Compatibility option: ignored"));
92
93 static  cl::opt<std::string> CO6("h", cl::Hidden,
94   cl::desc("Compatibility option: ignored"));
95
96 /// This is just for convenience so it doesn't have to be passed around
97 /// everywhere.
98 static std::string progname;
99
100 /// PrintAndReturn - Prints a message to standard error and returns true.
101 ///
102 /// Inputs:
103 ///  progname - The name of the program (i.e. argv[0]).
104 ///  Message  - The message to print to standard error.
105 ///
106 static int PrintAndReturn(const std::string &Message) {
107   std::cerr << progname << ": " << Message << "\n";
108   return 1;
109 }
110
111 /// CopyEnv - This function takes an array of environment variables and makes a
112 /// copy of it.  This copy can then be manipulated any way the caller likes
113 /// without affecting the process's real environment.
114 ///
115 /// Inputs:
116 ///  envp - An array of C strings containing an environment.
117 ///
118 /// Return value:
119 ///  NULL - An error occurred.
120 ///
121 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
122 ///  in the array is a duplicate of the one in the original array (i.e. we do
123 ///  not copy the char *'s from one array to another).
124 ///
125 static char ** CopyEnv(char ** const envp) {
126   // Count the number of entries in the old list;
127   unsigned entries;   // The number of entries in the old environment list
128   for (entries = 0; envp[entries] != NULL; entries++)
129     /*empty*/;
130
131   // Add one more entry for the NULL pointer that ends the list.
132   ++entries;
133
134   // If there are no entries at all, just return NULL.
135   if (entries == 0)
136     return NULL;
137
138   // Allocate a new environment list.
139   char **newenv = new char* [entries];
140   if ((newenv = new char* [entries]) == NULL)
141     return NULL;
142
143   // Make a copy of the list.  Don't forget the NULL that ends the list.
144   entries = 0;
145   while (envp[entries] != NULL) {
146     newenv[entries] = new char[strlen (envp[entries]) + 1];
147     strcpy (newenv[entries], envp[entries]);
148     ++entries;
149   }
150   newenv[entries] = NULL;
151
152   return newenv;
153 }
154
155
156 /// RemoveEnv - Remove the specified environment variable from the environment
157 /// array.
158 ///
159 /// Inputs:
160 ///  name - The name of the variable to remove.  It cannot be NULL.
161 ///  envp - The array of environment variables.  It cannot be NULL.
162 ///
163 /// Notes:
164 ///  This is mainly done because functions to remove items from the environment
165 ///  are not available across all platforms.  In particular, Solaris does not
166 ///  seem to have an unsetenv() function or a setenv() function (or they are
167 ///  undocumented if they do exist).
168 ///
169 static void RemoveEnv(const char * name, char ** const envp) {
170   for (unsigned index=0; envp[index] != NULL; index++) {
171     // Find the first equals sign in the array and make it an EOS character.
172     char *p = strchr (envp[index], '=');
173     if (p == NULL)
174       continue;
175     else
176       *p = '\0';
177
178     // Compare the two strings.  If they are equal, zap this string.
179     // Otherwise, restore it.
180     if (!strcmp(name, envp[index]))
181       *envp[index] = '\0';
182     else
183       *p = '=';
184   }
185
186   return;
187 }
188
189 /// GenerateBytecode - generates a bytecode file from the module provided
190 void GenerateBytecode(Module* M, const std::string& FileName) {
191
192   // Create the output file.
193   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
194                                std::ios::binary;
195   std::ofstream Out(FileName.c_str(), io_mode);
196   if (!Out.good()) {
197     PrintAndReturn("error opening '" + FileName + "' for writing!");
198     return;
199   }
200
201   // Ensure that the bytecode file gets removed from the disk if we get a
202   // terminating signal.
203   sys::RemoveFileOnSignal(sys::Path(FileName));
204
205   // Write it out
206   WriteBytecodeToFile(M, Out, !DisableCompression);
207
208   // Close the bytecode file.
209   Out.close();
210 }
211
212 /// GenerateAssembly - generates a native assembly language source file from the
213 /// specified bytecode file.
214 ///
215 /// Inputs:
216 ///  InputFilename  - The name of the output bytecode file.
217 ///  OutputFilename - The name of the file to generate.
218 ///  llc            - The pathname to use for LLC.
219 ///  envp           - The environment to use when running LLC.
220 ///
221 /// Return non-zero value on error.
222 ///
223 static int GenerateAssembly(const std::string &OutputFilename,
224                             const std::string &InputFilename,
225                             const sys::Path &llc) {
226   // Run LLC to convert the bytecode file into assembly code.
227   std::vector<const char*> args;
228   args.push_back(llc.c_str());
229   args.push_back("-f");
230   args.push_back("-o");
231   args.push_back(OutputFilename.c_str());
232   args.push_back(InputFilename.c_str());
233   args.push_back(0);
234
235   return sys::Program::ExecuteAndWait(llc,&args[0]);
236 }
237
238 /// GenerateAssembly - generates a native assembly language source file from the
239 /// specified bytecode file.
240 static int GenerateCFile(const std::string &OutputFile,
241                          const std::string &InputFile,
242                          const sys::Path &llc) {
243   // Run LLC to convert the bytecode file into C.
244   std::vector<const char*> args;
245   args.push_back(llc.c_str());
246   args.push_back("-march=c");
247   args.push_back("-f");
248   args.push_back("-o");
249   args.push_back(OutputFile.c_str());
250   args.push_back(InputFile.c_str());
251   args.push_back(0);
252   return sys::Program::ExecuteAndWait(llc, &args[0]);
253 }
254
255 /// GenerateNative - generates a native assembly language source file from the
256 /// specified assembly source file.
257 ///
258 /// Inputs:
259 ///  InputFilename  - The name of the output bytecode file.
260 ///  OutputFilename - The name of the file to generate.
261 ///  Libraries      - The list of libraries with which to link.
262 ///  LibPaths       - The list of directories in which to find libraries.
263 ///  gcc            - The pathname to use for GGC.
264 ///  envp           - A copy of the process's current environment.
265 ///
266 /// Outputs:
267 ///  None.
268 ///
269 /// Returns non-zero value on error.
270 ///
271 static int GenerateNative(const std::string &OutputFilename,
272                           const std::string &InputFilename,
273                           const std::vector<std::string> &Libraries,
274                           const sys::Path &gcc, char ** const envp) {
275   // Remove these environment variables from the environment of the
276   // programs that we will execute.  It appears that GCC sets these
277   // environment variables so that the programs it uses can configure
278   // themselves identically.
279   //
280   // However, when we invoke GCC below, we want it to use its normal
281   // configuration.  Hence, we must sanitize its environment.
282   char ** clean_env = CopyEnv(envp);
283   if (clean_env == NULL)
284     return 1;
285   RemoveEnv("LIBRARY_PATH", clean_env);
286   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
287   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
288   RemoveEnv("COMPILER_PATH", clean_env);
289   RemoveEnv("COLLECT_GCC", clean_env);
290
291
292   // Run GCC to assemble and link the program into native code.
293   //
294   // Note:
295   //  We can't just assemble and link the file with the system assembler
296   //  and linker because we don't know where to put the _start symbol.
297   //  GCC mysteriously knows how to do it.
298   std::vector<const char*> args;
299   args.push_back(gcc.c_str());
300   args.push_back("-fno-strict-aliasing");
301   args.push_back("-O3");
302   args.push_back("-o");
303   args.push_back(OutputFilename.c_str());
304   args.push_back(InputFilename.c_str());
305
306   // Add in the libraries to link.
307   for (unsigned index = 0; index < Libraries.size(); index++)
308     if (Libraries[index] != "crtend") {
309       args.push_back("-l");
310       args.push_back(Libraries[index].c_str());
311     }
312   args.push_back(0);
313
314   // Run the compiler to assembly and link together the program.
315   return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
316 }
317
318 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
319 /// bytecode file for the program.
320 static void EmitShellScript(char **argv) {
321 #if defined(_WIN32) || defined(__CYGWIN__)
322   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
323   // support windows systems, we copy the llvm-stub.exe executable from the
324   // build tree to the destination file.
325   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
326   if (llvmstub.isEmpty()) {
327     std::cerr << "Could not find llvm-stub.exe executable!\n";
328     exit(1);
329   }
330   sys::CopyFile(sys::Path(OutputFilename), llvmstub);
331   return;
332 #endif
333
334   // Output the script to start the program...
335   std::ofstream Out2(OutputFilename.c_str());
336   if (!Out2.good())
337     exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
338
339   Out2 << "#!/bin/sh\n";
340   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
341   Out2 << "lli=${LLVMINTERP-lli}\n";
342   Out2 << "exec $lli \\\n";
343   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
344   LibPaths.push_back("/lib");
345   LibPaths.push_back("/usr/lib");
346   LibPaths.push_back("/usr/X11R6/lib");
347   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
348   // shared object at all! See RH 8: plain text.
349   std::vector<std::string>::iterator libc =
350     std::find(Libraries.begin(), Libraries.end(), "c");
351   if (libc != Libraries.end()) Libraries.erase(libc);
352   // List all the shared object (native) libraries this executable will need
353   // on the command line, so that we don't have to do this manually!
354   for (std::vector<std::string>::iterator i = Libraries.begin(),
355          e = Libraries.end(); i != e; ++i) {
356     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
357     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
358       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
359   }
360   Out2 << "    $0.bc ${1+\"$@\"}\n";
361   Out2.close();
362 }
363
364 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
365 // linker function by combining the Files and Libraries in the order they were
366 // declared on the command line.
367 static void BuildLinkItems(
368   Linker::ItemList& Items,
369   const cl::list<std::string>& Files,
370   const cl::list<std::string>& Libraries) {
371
372   // Build the list of linkage items for LinkItems.
373
374   cl::list<std::string>::const_iterator fileIt = Files.begin();
375   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
376
377   int libPos = -1, filePos = -1;
378   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
379     if (libIt != Libraries.end())
380       libPos = Libraries.getPosition(libIt - Libraries.begin());
381     else
382       libPos = -1;
383     if (fileIt != Files.end())
384       filePos = Files.getPosition(fileIt - Files.begin());
385     else
386       filePos = -1;
387
388     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
389       // Add a source file
390       Items.push_back(std::make_pair(*fileIt++, false));
391     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
392       // Add a library
393       Items.push_back(std::make_pair(*libIt++, true));
394     }
395   }
396 }
397
398 // Rightly this should go in a header file but it just seems such a waste.
399 namespace llvm {
400 extern void Optimize(Module*);
401 }
402
403 int main(int argc, char **argv, char **envp) {
404   try {
405     // Initial global variable above for convenience printing of program name.
406     progname = sys::Path(argv[0]).getBasename();
407     Linker TheLinker(progname, OutputFilename, Verbose);
408
409     // Set up the library paths for the Linker
410     TheLinker.addPaths(LibPaths);
411     TheLinker.addSystemPaths();
412
413     // Parse the command line options
414     cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
415     sys::PrintStackTraceOnErrorSignal();
416
417     // Remove any consecutive duplicates of the same library...
418     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
419                     Libraries.end());
420
421     if (LinkAsLibrary) {
422       std::vector<sys::Path> Files;
423       for (unsigned i = 0; i < InputFilenames.size(); ++i )
424         Files.push_back(sys::Path(InputFilenames[i]));
425       if (TheLinker.LinkInFiles(Files))
426         return 1; // Error already printed
427
428       // The libraries aren't linked in but are noted as "dependent" in the
429       // module.
430       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
431            E = Libraries.end(); I != E ; ++I) {
432         TheLinker.getModule()->addLibrary(*I);
433       }
434     } else {
435       // Build a list of the items from our command line
436       Linker::ItemList Items;
437       Linker::ItemList NativeItems;
438       BuildLinkItems(Items, InputFilenames, Libraries);
439
440       // Link all the items together
441       if (TheLinker.LinkInItems(Items,NativeItems) )
442         return 1;
443     }
444
445     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
446
447     // Optimize the module
448     Optimize(Composite.get());
449
450     // Generate the bytecode for the optimized module.
451     std::string RealBytecodeOutput = OutputFilename;
452     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
453     GenerateBytecode(Composite.get(), RealBytecodeOutput);
454
455     // If we are not linking a library, generate either a native executable
456     // or a JIT shell script, depending upon what the user wants.
457     if (!LinkAsLibrary) {
458       // If the user wants to run a post-link optimization, run it now.
459       if (!PostLinkOpts.empty()) {
460         std::vector<std::string> opts = PostLinkOpts;
461         for (std::vector<std::string>::iterator I = opts.begin(),
462              E = opts.end(); I != E; ++I) {
463           sys::Path prog(*I);
464           if (!prog.canExecute()) {
465             prog = sys::Program::FindProgramByName(*I);
466             if (prog.isEmpty())
467               return PrintAndReturn(std::string("Optimization program '") + *I +
468                 "' is not found or not executable.");
469           }
470           // Get the program arguments
471           sys::Path tmp_output("opt_result");
472           if (!tmp_output.createTemporaryFileOnDisk()) {
473             return PrintAndReturn(
474               "Can't create temporary file for post-link optimization");
475           }
476           const char* args[4];
477           args[0] = I->c_str();
478           args[1] = RealBytecodeOutput.c_str();
479           args[2] = tmp_output.c_str();
480           args[3] = 0;
481           if (0 == sys::Program::ExecuteAndWait(prog, args)) {
482             if (tmp_output.isBytecodeFile()) {
483               sys::Path target(RealBytecodeOutput);
484               target.eraseFromDisk();
485               tmp_output.renamePathOnDisk(target);
486             } else
487               return PrintAndReturn(
488                 "Post-link optimization output is not bytecode");
489           }
490         }
491       }
492
493       // If the user wants to generate a native executable, compile it from the
494       // bytecode file.
495       //
496       // Otherwise, create a script that will run the bytecode through the JIT.
497       if (Native) {
498         // Name of the Assembly Language output file
499         sys::Path AssemblyFile ( OutputFilename);
500         AssemblyFile.appendSuffix("s");
501
502         // Mark the output files for removal if we get an interrupt.
503         sys::RemoveFileOnSignal(AssemblyFile);
504         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
505
506         // Determine the locations of the llc and gcc programs.
507         sys::Path llc = FindExecutable("llc", argv[0]);
508         if (llc.isEmpty())
509           return PrintAndReturn("Failed to find llc");
510
511         sys::Path gcc = FindExecutable("gcc", argv[0]);
512         if (gcc.isEmpty())
513           return PrintAndReturn("Failed to find gcc");
514
515         // Generate an assembly language file for the bytecode.
516         if (Verbose) std::cout << "Generating Assembly Code\n";
517         GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
518         if (Verbose) std::cout << "Generating Native Code\n";
519         GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
520                        gcc, envp);
521
522         // Remove the assembly language file.
523         AssemblyFile.eraseFromDisk();
524       } else if (NativeCBE) {
525         sys::Path CFile (OutputFilename);
526         CFile.appendSuffix("cbe.c");
527
528         // Mark the output files for removal if we get an interrupt.
529         sys::RemoveFileOnSignal(CFile);
530         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
531
532         // Determine the locations of the llc and gcc programs.
533         sys::Path llc = FindExecutable("llc", argv[0]);
534         if (llc.isEmpty())
535           return PrintAndReturn("Failed to find llc");
536
537         sys::Path gcc = FindExecutable("gcc", argv[0]);
538         if (gcc.isEmpty())
539           return PrintAndReturn("Failed to find gcc");
540
541         // Generate an assembly language file for the bytecode.
542         if (Verbose) std::cout << "Generating Assembly Code\n";
543         GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
544         if (Verbose) std::cout << "Generating Native Code\n";
545         GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
546
547         // Remove the assembly language file.
548         CFile.eraseFromDisk();
549
550       } else {
551         EmitShellScript(argv);
552       }
553
554       // Make the script executable...
555       sys::Path(OutputFilename).makeExecutableOnDisk();
556
557       // Make the bytecode file readable and directly executable in LLEE as well
558       sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
559       sys::Path(RealBytecodeOutput).makeReadableOnDisk();
560     }
561
562     return 0;
563   } catch (const std::string& msg) {
564     std::cerr << argv[0] << ": " << msg << "\n";
565   } catch (...) {
566     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
567   }
568   return 1;
569 }