For PR351:
[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/Bytecode/WriteBytecodePass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/IPO.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.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",
82          cl::desc("Generate a native binary instead of a shell script"));
83   cl::opt<bool>    
84   NativeCBE("native-cbe",
85             cl::desc("Generate a native binary with the C backend and GCC"));
86   
87   // Compatibility options that are ignored but supported by LD
88   cl::opt<std::string>
89   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
90   cl::opt<std::string>
91   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
92   cl::opt<bool>
93   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
94   cl::opt<std::string>
95   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
96
97   cl::alias A0("s", cl::desc("Alias for --strip-all"),
98                cl::aliasopt(Strip));
99   cl::alias A1("S", cl::desc("Alias for --strip-debug"),
100                cl::aliasopt(StripDebug));
101
102 }
103
104 /// PrintAndReturn - Prints a message to standard error and returns true.
105 ///
106 /// Inputs:
107 ///  progname - The name of the program (i.e. argv[0]).
108 ///  Message  - The message to print to standard error.
109 ///
110 static int PrintAndReturn(const char *progname, const std::string &Message) {
111   std::cerr << progname << ": " << Message << "\n";
112   return 1;
113 }
114
115 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
116 /// bytecode file for the program.
117 static void EmitShellScript(char **argv) {
118 #if defined(_WIN32) || defined(__CYGWIN__)
119   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
120   // support windows systems, we copy the llvm-stub.exe executable from the
121   // build tree to the destination file.
122   std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]).toString();
123   if (llvmstub.empty()) {
124     std::cerr << "Could not find llvm-stub.exe executable!\n";
125     exit(1);
126   }
127   if (CopyFile(OutputFilename, llvmstub)) {
128     std::cerr << "Could not copy the llvm-stub.exe executable!\n";
129     exit(1);
130   }
131   return;
132 #endif
133
134   // Output the script to start the program...
135   std::ofstream Out2(OutputFilename.c_str());
136   if (!Out2.good())
137     exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
138                                  "' for writing!"));
139
140   Out2 << "#!/bin/sh\n";
141   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
142   Out2 << "lli=${LLVMINTERP-lli}\n";
143   Out2 << "exec $lli \\\n";
144
145   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
146   // shared object at all! See RH 8: plain text.
147   std::vector<std::string>::iterator libc = 
148     std::find(Libraries.begin(), Libraries.end(), "c");
149   if (libc != Libraries.end()) Libraries.erase(libc);
150   // List all the shared object (native) libraries this executable will need
151   // on the command line, so that we don't have to do this manually!
152   for (std::vector<std::string>::iterator i = Libraries.begin(), 
153          e = Libraries.end(); i != e; ++i) {
154     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
155     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
156       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
157   }
158   Out2 << "    $0.bc ${1+\"$@\"}\n";
159   Out2.close();
160 }
161
162 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
163 // linker function by combining the Files and Libraries in the order they were
164 // declared on the command line.
165 static void BuildLinkItems(
166   Linker::ItemList& Items,
167   const cl::list<std::string>& Files,
168   const cl::list<std::string>& Libraries) {
169
170   // Build the list of linkage items for LinkItems. 
171
172   cl::list<std::string>::const_iterator fileIt = Files.begin();
173   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
174
175   int libPos = -1, filePos = -1;
176   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
177     if (libIt != Libraries.end())
178       libPos = Libraries.getPosition(libIt - Libraries.begin());
179     else
180       libPos = -1;
181     if (fileIt != Files.end())
182       filePos = Files.getPosition(fileIt - Files.begin());
183     else
184       filePos = -1;
185
186     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
187       // Add a source file
188       Items.push_back(std::make_pair(*fileIt++, false));
189     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
190       // Add a library
191       Items.push_back(std::make_pair(*libIt++, true));
192     }
193   }
194 }
195
196 int main(int argc, char **argv, char **envp ) {
197   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
198   sys::PrintStackTraceOnErrorSignal();
199
200   int exitCode = 0;
201
202   std::string ProgName = sys::Path(argv[0]).getBasename();
203   Linker TheLinker(ProgName, Verbose);
204
205   try {
206     // Remove any consecutive duplicates of the same library...
207     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
208                     Libraries.end());
209
210     TheLinker.addPaths(LibPaths);
211     TheLinker.addSystemPaths();
212
213     if (LinkAsLibrary) {
214       std::vector<sys::Path> Files;
215       for (unsigned i = 0; i < InputFilenames.size(); ++i )
216         Files.push_back(sys::Path(InputFilenames[i]));
217
218       if (TheLinker.LinkInFiles(Files))
219         return 1; // Error already printed by linker
220
221       // The libraries aren't linked in but are noted as "dependent" in the
222       // module.
223       for (cl::list<std::string>::const_iterator I = Libraries.begin(), 
224            E = Libraries.end(); I != E ; ++I) {
225         TheLinker.getModule()->addLibrary(*I);
226       }
227
228     } else {
229       // Build a list of the items from our command line
230       Linker::ItemList Items;
231       BuildLinkItems(Items, InputFilenames, Libraries);
232
233       // Link all the items together
234       if (TheLinker.LinkInItems(Items))
235         return 1; // Error already printed
236     }
237
238     // We're done with the Linker, so tell it to release its module
239     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
240
241     // Create the output file.
242     std::string RealBytecodeOutput = OutputFilename;
243     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
244     std::ofstream Out(RealBytecodeOutput.c_str());
245     if (!Out.good())
246       return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
247                                      "' for writing!");
248
249     // Ensure that the bytecode file gets removed from the disk if we get a
250     // SIGINT signal.
251     sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
252
253     // Strip everything if Strip is set, otherwise if stripdebug is set, just
254     // strip debug info.
255     int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
256
257     // Internalize the module if neither -disable-internalize nor 
258     // -link-as-library are passed in.
259     bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
260
261     // Generate the bytecode file.
262     if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
263       Out.close();
264       return PrintAndReturn(argv[0], "error generating bytecode");
265     }
266
267     // Close the bytecode file.
268     Out.close();
269
270     // If we are not linking a library, generate either a native executable
271     // or a JIT shell script, depending upon what the user wants.
272     if (!LinkAsLibrary) {
273       // If the user wants to generate a native executable, compile it from the
274       // bytecode file.
275       //
276       // Otherwise, create a script that will run the bytecode through the JIT.
277       if (Native) {
278         // Name of the Assembly Language output file
279         std::string AssemblyFile = OutputFilename + ".s";
280
281         // Mark the output files for removal if we get an interrupt.
282         sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
283         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
284
285         // Determine the locations of the llc and gcc programs.
286         std::string llc = FindExecutable("llc", argv[0]).toString();
287         if (llc.empty())
288           return PrintAndReturn(argv[0], "Failed to find llc");
289
290         std::string gcc = FindExecutable("gcc", argv[0]).toString();
291         if (gcc.empty())
292           return PrintAndReturn(argv[0], "Failed to find gcc");
293
294         // Generate an assembly language file for the bytecode.
295         if (Verbose) std::cout << "Generating Assembly Code\n";
296         GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp );
297         if (Verbose) std::cout << "Generating Native Code\n";
298         GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths, 
299                        gcc, envp );
300
301         // Remove the assembly language file.
302         removeFile (AssemblyFile);
303       } else if (NativeCBE) {
304         std::string CFile = OutputFilename + ".cbe.c";
305
306         // Mark the output files for removal if we get an interrupt.
307         sys::RemoveFileOnSignal(sys::Path(CFile));
308         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
309
310         // Determine the locations of the llc and gcc programs.
311         std::string llc = FindExecutable("llc", argv[0]).toString();
312         if (llc.empty())
313           return PrintAndReturn(argv[0], "Failed to find llc");
314
315         std::string gcc = FindExecutable("gcc", argv[0]).toString();
316         if (gcc.empty())
317           return PrintAndReturn(argv[0], "Failed to find gcc");
318
319         // Generate an assembly language file for the bytecode.
320         if (Verbose) std::cout << "Generating Assembly Code\n";
321         GenerateCFile(CFile, RealBytecodeOutput, llc, envp );
322         if (Verbose) std::cout << "Generating Native Code\n";
323         GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp );
324
325         // Remove the assembly language file.
326         removeFile(CFile);
327
328       } else {
329         EmitShellScript(argv);
330       }
331     
332       // Make the script executable...
333       sys::Path(OutputFilename).makeExecutable();
334
335       // Make the bytecode file readable and directly executable in LLEE as well
336       sys::Path(RealBytecodeOutput).makeExecutable();
337       sys::Path(RealBytecodeOutput).makeReadable();
338     }
339   } catch (const char*msg) {
340     std::cerr << argv[0] << ": " << msg << "\n";
341     exitCode = 1;
342   } catch (const std::string& msg) {
343     std::cerr << argv[0] << ": " << msg << "\n";
344     exitCode = 2;
345   } catch (...) {
346     // This really shouldn't happen, but just in case ....
347     std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
348     exitCode = 3;
349   }
350
351   return exitCode;
352 }