-disable-opt is not -O0, it's okay for it to disable internalize.
[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("s", cl::desc("Strip symbol info from executable"));
62
63   cl::opt<bool>
64   NoInternalize("disable-internalize",
65                 cl::desc("Do not mark all symbols as internal"));
66   cl::alias
67   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
68                 cl::aliasopt(NoInternalize));
69
70   cl::opt<bool>
71   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
72                                             " library, not an executable"));
73   cl::alias
74   Relink("r", cl::desc("Alias for -link-as-library"),
75          cl::aliasopt(LinkAsLibrary));
76
77   cl::opt<bool>    
78   Native("native",
79          cl::desc("Generate a native binary instead of a shell script"));
80   cl::opt<bool>    
81   NativeCBE("native-cbe",
82             cl::desc("Generate a native binary with the C backend and GCC"));
83   
84   // Compatibility options that are ignored but supported by LD
85   cl::opt<std::string>
86   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
87   cl::opt<std::string>
88   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
89   cl::opt<bool>
90   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
91   cl::opt<std::string>
92   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
93 }
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 char *progname, const std::string &Message) {
102   std::cerr << progname << ": " << Message << "\n";
103   return 1;
104 }
105
106 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
107 /// bytecode file for the program.
108 static void EmitShellScript(char **argv) {
109 #if defined(_WIN32) || defined(__CYGWIN__)
110   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
111   // support windows systems, we copy the llvm-stub.exe executable from the
112   // build tree to the destination file.
113   std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
114   if (llvmstub.empty()) {
115     std::cerr << "Could not find llvm-stub.exe executable!\n";
116     exit(1);
117   }
118   if (CopyFile(OutputFilename, llvmstub)) {
119     std::cerr << "Could not copy the llvm-stub.exe executable!\n";
120     exit(1);
121   }
122   return;
123 #endif
124
125   // Output the script to start the program...
126   std::ofstream Out2(OutputFilename.c_str());
127   if (!Out2.good())
128     exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
129                                  "' for writing!"));
130
131   Out2 << "#!/bin/sh\n";
132   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
133   Out2 << "lli=${LLVMINTERP-lli}\n";
134   Out2 << "exec $lli \\\n";
135   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
136   LibPaths.push_back("/lib");
137   LibPaths.push_back("/usr/lib");
138   LibPaths.push_back("/usr/X11R6/lib");
139   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
140   // shared object at all! See RH 8: plain text.
141   std::vector<std::string>::iterator libc = 
142     std::find(Libraries.begin(), Libraries.end(), "c");
143   if (libc != Libraries.end()) Libraries.erase(libc);
144   // List all the shared object (native) libraries this executable will need
145   // on the command line, so that we don't have to do this manually!
146   for (std::vector<std::string>::iterator i = Libraries.begin(), 
147          e = Libraries.end(); i != e; ++i) {
148     std::string FullLibraryPath = FindLib(*i, LibPaths, true);
149     if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
150       Out2 << "    -load=" << FullLibraryPath << " \\\n";
151   }
152   Out2 << "    $0.bc ${1+\"$@\"}\n";
153   Out2.close();
154 }
155
156 int main(int argc, char **argv, char **envp) {
157   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
158   sys::PrintStackTraceOnErrorSignal();
159
160   int exitCode = 0;
161
162   try {
163     std::string ModuleID("gccld-output");
164     std::auto_ptr<Module> Composite(new Module(ModuleID));
165
166     // We always look first in the current directory when searching for
167     // libraries.
168     LibPaths.insert(LibPaths.begin(), ".");
169
170     // If the user specified an extra search path in their environment, respect
171     // it.
172     if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
173       LibPaths.push_back(SearchPath);
174
175     // Remove any consecutive duplicates of the same library...
176     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
177                     Libraries.end());
178
179     // Link in all of the files
180     if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
181       return 1; // Error already printed
182
183     if (!LinkAsLibrary)
184       LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
185                     Verbose, Native);
186
187     // Link in all of the libraries next...
188
189     // Create the output file.
190     std::string RealBytecodeOutput = OutputFilename;
191     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
192     std::ofstream Out(RealBytecodeOutput.c_str());
193     if (!Out.good())
194       return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
195                                      "' for writing!");
196
197     // Ensure that the bytecode file gets removed from the disk if we get a
198     // SIGINT signal.
199     sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
200
201     // Generate the bytecode file.
202     if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
203       Out.close();
204       return PrintAndReturn(argv[0], "error generating bytecode");
205     }
206
207     // Close the bytecode file.
208     Out.close();
209
210     // If we are not linking a library, generate either a native executable
211     // or a JIT shell script, depending upon what the user wants.
212     if (!LinkAsLibrary) {
213       // If the user wants to generate a native executable, compile it from the
214       // bytecode file.
215       //
216       // Otherwise, create a script that will run the bytecode through the JIT.
217       if (Native) {
218         // Name of the Assembly Language output file
219         std::string AssemblyFile = OutputFilename + ".s";
220
221         // Mark the output files for removal if we get an interrupt.
222         sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
223         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
224
225         // Determine the locations of the llc and gcc programs.
226         std::string llc = FindExecutable("llc", argv[0]);
227         std::string gcc = FindExecutable("gcc", argv[0]);
228         if (llc.empty())
229           return PrintAndReturn(argv[0], "Failed to find llc");
230
231         if (gcc.empty())
232           return PrintAndReturn(argv[0], "Failed to find gcc");
233
234         // Generate an assembly language file for the bytecode.
235         if (Verbose) std::cout << "Generating Assembly Code\n";
236         GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
237         if (Verbose) std::cout << "Generating Native Code\n";
238         GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
239                        gcc, envp);
240
241         // Remove the assembly language file.
242         removeFile (AssemblyFile);
243       } else if (NativeCBE) {
244         std::string CFile = OutputFilename + ".cbe.c";
245
246         // Mark the output files for removal if we get an interrupt.
247         sys::RemoveFileOnSignal(sys::Path(CFile));
248         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
249
250         // Determine the locations of the llc and gcc programs.
251         std::string llc = FindExecutable("llc", argv[0]);
252         std::string gcc = FindExecutable("gcc", argv[0]);
253         if (llc.empty())
254           return PrintAndReturn(argv[0], "Failed to find llc");
255         if (gcc.empty())
256           return PrintAndReturn(argv[0], "Failed to find gcc");
257
258         // Generate an assembly language file for the bytecode.
259         if (Verbose) std::cout << "Generating Assembly Code\n";
260         GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
261         if (Verbose) std::cout << "Generating Native Code\n";
262         GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
263
264         // Remove the assembly language file.
265         removeFile(CFile);
266
267       } else {
268         EmitShellScript(argv);
269       }
270     
271       // Make the script executable...
272       MakeFileExecutable(OutputFilename);
273
274       // Make the bytecode file readable and directly executable in LLEE as well
275       MakeFileExecutable(RealBytecodeOutput);
276       MakeFileReadable(RealBytecodeOutput);
277     }
278   } catch (const char*msg) {
279     std::cerr << argv[0] << ": " << msg << "\n";
280     exitCode = 1;
281   } catch (const std::string& msg) {
282     std::cerr << argv[0] << ": " << msg << "\n";
283     exitCode = 2;
284   } catch (...) {
285     // This really shouldn't happen, but just in case ....
286     std::cerr << argv[0] << ": An nexpected unknown exception occurred.\n";
287     exitCode = 3;
288   }
289
290   return exitCode;
291 }