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