0327a3cc115fa2c0560c2e4864f3b6323cc3614f
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.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 "gccld.h"
24 #include "llvm/Linker.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/System/Signals.h"
35 #include "llvm/Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38 using namespace llvm;
39
40 namespace {
41   cl::list<std::string>
42   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
43                  cl::OneOrMore);
44
45   cl::opt<std::string>
46   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
47                  cl::value_desc("filename"));
48
49   cl::opt<bool>
50   Verbose("v", cl::desc("Print information about actions taken"));
51
52   cl::list<std::string>
53   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
54            cl::value_desc("directory"));
55
56   cl::list<std::string>
57   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
58             cl::value_desc("library prefix"));
59
60   cl::opt<bool>
61   Strip("strip-all", cl::desc("Strip all symbol info from executable"));
62   cl::opt<bool>
63   StripDebug("strip-debug",
64              cl::desc("Strip debugger symbol info from executable"));
65
66   cl::opt<bool>
67   NoInternalize("disable-internalize",
68                 cl::desc("Do not mark all symbols as internal"));
69   cl::alias
70   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71                 cl::aliasopt(NoInternalize));
72
73   cl::opt<bool>
74   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
75                                             " library, not an executable"));
76   cl::alias
77   Relink("r", cl::desc("Alias for -link-as-library"),
78          cl::aliasopt(LinkAsLibrary));
79
80   cl::opt<bool>
81   Native("native", cl::ZeroOrMore,
82          cl::desc("Generate a native binary instead of a shell script"));
83   cl::opt<bool>
84   NativeCBE("native-cbe", cl::ZeroOrMore,
85             cl::desc("Generate a native binary with the C backend and GCC"));
86
87   cl::opt<bool>
88   SaveTemps("save-temps",
89          cl::desc("Do not delete temporary files"));
90
91   cl::list<std::string>
92   RPath("rpath",
93         cl::desc("Set runtime shared library search path (requires -native or"
94                  " -native-cbe)"),
95         cl::Prefix, cl::value_desc("directory"));
96
97   cl::opt<std::string>
98   SOName("soname",
99          cl::desc("Set internal name of shared library (requires -native or"
100                  " -native-cbe)"),
101          cl::Prefix, cl::value_desc("name"));
102
103   // Compatibility options that are ignored but supported by LD
104   cl::opt<std::string>
105   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
106   cl::opt<bool>
107   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
108   cl::opt<std::string>
109   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
110   cl::opt<bool>
111   CO7("start-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
112   cl::opt<bool>
113   CO8("end-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
114
115   cl::alias A0("s", cl::desc("Alias for --strip-all"),
116                cl::aliasopt(Strip));
117   cl::alias A1("S", cl::desc("Alias for --strip-debug"),
118                cl::aliasopt(StripDebug));
119
120 }
121
122 /// PrintAndReturn - Prints a message to standard error and returns true.
123 ///
124 /// Inputs:
125 ///  progname - The name of the program (i.e. argv[0]).
126 ///  Message  - The message to print to standard error.
127 ///
128 static int PrintAndReturn(const char *progname, const std::string &Message) {
129   llvm_cerr << progname << ": " << Message << "\n";
130   return 1;
131 }
132
133 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
134 /// bytecode file for the program.
135 static void EmitShellScript(char **argv) {
136 #if defined(_WIN32) || defined(__CYGWIN__)  
137   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
138   // support windows systems, we copy the llvm-stub.exe executable from the
139   // build tree to the destination file.
140   std::string ErrMsg;  
141   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
142   if (llvmstub.isEmpty()) {
143     llvm_cerr << "Could not find llvm-stub.exe executable!\n";
144     exit(1);
145   }
146   if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg)) {
147     llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
148     exit(1);    
149   }
150
151   return;  
152 #endif
153
154   // Output the script to start the program...
155   std::ofstream Out2(OutputFilename.c_str());
156   if (!Out2.good())
157     exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
158                                  "' for writing!"));
159
160   Out2 << "#!/bin/sh\n";
161   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
162   Out2 << "lli=${LLVMINTERP-lli}\n";
163   Out2 << "exec $lli \\\n";
164
165   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
166   // shared object at all! See RH 8: plain text.
167   std::vector<std::string>::iterator libc =
168     std::find(Libraries.begin(), Libraries.end(), "c");
169   if (libc != Libraries.end()) Libraries.erase(libc);
170   // List all the shared object (native) libraries this executable will need
171   // on the command line, so that we don't have to do this manually!
172   for (std::vector<std::string>::iterator i = Libraries.begin(),
173          e = Libraries.end(); i != e; ++i) {
174     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
175     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
176       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
177   }
178   Out2 << "    $0.bc ${1+\"$@\"}\n";
179   Out2.close();
180 }
181
182 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
183 // linker function by combining the Files and Libraries in the order they were
184 // declared on the command line.
185 static void BuildLinkItems(
186   Linker::ItemList& Items,
187   const cl::list<std::string>& Files,
188   const cl::list<std::string>& Libraries) {
189
190   // Build the list of linkage items for LinkItems.
191
192   cl::list<std::string>::const_iterator fileIt = Files.begin();
193   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
194
195   int libPos = -1, filePos = -1;
196   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
197     if (libIt != Libraries.end())
198       libPos = Libraries.getPosition(libIt - Libraries.begin());
199     else
200       libPos = -1;
201     if (fileIt != Files.end())
202       filePos = Files.getPosition(fileIt - Files.begin());
203     else
204       filePos = -1;
205
206     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
207       // Add a source file
208       Items.push_back(std::make_pair(*fileIt++, false));
209     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
210       // Add a library
211       Items.push_back(std::make_pair(*libIt++, true));
212     }
213   }
214 }
215
216 int main(int argc, char **argv, char **envp ) {
217   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
218   sys::PrintStackTraceOnErrorSignal();
219
220   int exitCode = 0;
221
222   std::string ProgName = sys::Path(argv[0]).getBasename();
223   Linker TheLinker(ProgName, OutputFilename, Verbose);
224
225   try {
226     // Remove any consecutive duplicates of the same library...
227     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
228                     Libraries.end());
229
230     TheLinker.addPaths(LibPaths);
231     TheLinker.addSystemPaths();
232
233     if (LinkAsLibrary) {
234       std::vector<sys::Path> Files;
235       for (unsigned i = 0; i < InputFilenames.size(); ++i )
236         Files.push_back(sys::Path(InputFilenames[i]));
237
238       if (TheLinker.LinkInFiles(Files))
239         return 1; // Error already printed by linker
240
241       // The libraries aren't linked in but are noted as "dependent" in the
242       // module.
243       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
244            E = Libraries.end(); I != E ; ++I) {
245         TheLinker.getModule()->addLibrary(*I);
246       }
247
248     } else {
249       // Build a list of the items from our command line
250       Linker::ItemList Items;
251       Linker::ItemList NativeItems;
252       BuildLinkItems(Items, InputFilenames, Libraries);
253
254       // Link all the items together
255       if (TheLinker.LinkInItems(Items,NativeItems))
256         return 1; // Error already printed
257
258       // Revise the Libraries based on the remaining (native) libraries that
259       // were not linked in to the bytecode. This ensures that we don't attempt
260       // to pass a bytecode library to the native linker
261       Libraries.clear(); // we've consumed the libraries except for native
262       if ((Native || NativeCBE) && !NativeItems.empty()) {
263         for (Linker::ItemList::const_iterator I = NativeItems.begin(), 
264              E = NativeItems.end(); I != E; ++I) {
265           Libraries.push_back(I->first);
266         }
267       }
268     }
269
270     // We're done with the Linker, so tell it to release its module
271     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
272
273     // Create the output file.
274     std::string RealBytecodeOutput = OutputFilename;
275     if (!LinkAsLibrary || Native || NativeCBE) RealBytecodeOutput += ".bc";
276     std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
277                                  std::ios::binary;
278     std::ofstream Out(RealBytecodeOutput.c_str(), io_mode);
279     if (!Out.good())
280       return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
281                                      "' for writing!");
282
283     // Ensure that the bytecode file gets removed from the disk if we get a
284     // SIGINT signal.
285     sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
286
287     // Strip everything if Strip is set, otherwise if stripdebug is set, just
288     // strip debug info.
289     int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
290
291     // Internalize the module if neither -disable-internalize nor
292     // -link-as-library are passed in.
293     bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
294
295     // Generate the bytecode file.
296     if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
297       Out.close();
298       return PrintAndReturn(argv[0], "error generating bytecode");
299     }
300
301     // Close the bytecode file.
302     Out.close();
303
304     // Generate either a native file or a JIT shell script.  If the user wants
305     // to generate a native file, compile it from the bytecode file. Otherwise,
306     // if the target is not a library, create a script that will run the
307     // bytecode through the JIT.
308     if (Native) {
309       // Name of the Assembly Language output file
310       sys::Path AssemblyFile (OutputFilename);
311       AssemblyFile.appendSuffix("s");
312
313       // Mark the output files for removal if we get an interrupt.
314       sys::RemoveFileOnSignal(AssemblyFile);
315       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
316
317       // Determine the locations of the llc and gcc programs.
318       sys::Path llc = FindExecutable("llc", argv[0]);
319       if (llc.isEmpty())
320         return PrintAndReturn(argv[0], "Failed to find llc");
321
322       sys::Path gcc = FindExecutable("gcc", argv[0]);
323       if (gcc.isEmpty())
324         return PrintAndReturn(argv[0], "Failed to find gcc");
325
326       // Generate an assembly language file for the bytecode.
327       if (Verbose) llvm_cout << "Generating Assembly Code\n";
328       std::string ErrMsg;
329       if (0 != GenerateAssembly(
330           AssemblyFile.toString(), RealBytecodeOutput, llc, ErrMsg, Verbose)) {
331         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
332         return 2;
333       }
334       if (Verbose) llvm_cout << "Generating Native Code\n";
335       if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
336                      LibPaths, Libraries, gcc, envp, LinkAsLibrary,
337                      NoInternalize, RPath, SOName, ErrMsg, Verbose) ) {
338         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
339         return 2;
340       }
341
342       if (!SaveTemps) {
343         // Remove the assembly language file.
344         AssemblyFile.eraseFromDisk();
345         // Remove the bytecode language file.
346         sys::Path(RealBytecodeOutput).eraseFromDisk();
347       }
348
349     } else if (NativeCBE) {
350       sys::Path CFile (OutputFilename);
351       CFile.appendSuffix("cbe.c");
352
353       // Mark the output files for removal if we get an interrupt.
354       sys::RemoveFileOnSignal(CFile);
355       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
356
357       // Determine the locations of the llc and gcc programs.
358       sys::Path llc = FindExecutable("llc", argv[0]);
359       if (llc.isEmpty())
360         return PrintAndReturn(argv[0], "Failed to find llc");
361
362       sys::Path gcc = FindExecutable("gcc", argv[0]);
363       if (gcc.isEmpty())
364         return PrintAndReturn(argv[0], "Failed to find gcc");
365
366       // Generate an assembly language file for the bytecode.
367       if (Verbose) llvm_cout << "Generating C Source Code\n";
368       std::string ErrMsg;
369       if (0 != GenerateCFile(
370           CFile.toString(), RealBytecodeOutput, llc, ErrMsg, Verbose)) {
371         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
372         return 2;
373       }
374       if (Verbose) llvm_cout << "Generating Native Code\n";
375       if (0 != GenerateNative(OutputFilename, CFile.toString(),
376                      LibPaths, Libraries, gcc, envp, LinkAsLibrary,
377                      NoInternalize, RPath, SOName, ErrMsg, Verbose)) {
378         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
379         return 2;
380       }
381
382       if (!SaveTemps) {
383         // Remove the assembly language file.
384         CFile.eraseFromDisk();
385         // Remove the bytecode language file.
386         sys::Path(RealBytecodeOutput).eraseFromDisk();
387       }
388
389     } else if (!LinkAsLibrary) {
390       EmitShellScript(argv);
391
392       // Make the bytecode file readable and directly executable in LLEE
393       std::string ErrMsg;
394       if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
395         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
396         return 1;
397       }
398       if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
399         llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
400         return 1;
401       }
402     }
403
404     // Make the output, whether native or script, executable as well...
405     std::string ErrMsg;
406     if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
407       llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
408       return 1;
409     }
410   } catch (const char*msg) {
411     llvm_cerr << argv[0] << ": " << msg << "\n";
412     exitCode = 1;
413   } catch (const std::string& msg) {
414     llvm_cerr << argv[0] << ": " << msg << "\n";
415     exitCode = 2;
416   } catch (...) {
417     // This really shouldn't happen, but just in case ....
418     llvm_cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
419     exitCode = 3;
420   }
421
422   return exitCode;
423 }