blob: c1f430affa4f6eac1126ec37b04f7391c943b40c [file] [log] [blame]
Chris Lattner10970eb2003-04-19 22:44:38 +00001//===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattnere7fca512002-01-24 19:12:12 +00009//
10// This utility is intended to be compatible with GCC, and follows standard
Chris Lattner10970eb2003-04-19 22:44:38 +000011// system 'ld' conventions. As such, the default output file is ./a.out.
Chris Lattnere7fca512002-01-24 19:12:12 +000012// 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,
Brian Gaeke69a79602003-05-23 20:27:07 +000019// I'm not too worried about this.
Chris Lattnere7fca512002-01-24 19:12:12 +000020//
21//===----------------------------------------------------------------------===//
22
Chris Lattner6e271232003-09-22 20:21:34 +000023#include "gccld.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000024#include "llvm/Linker.h"
Chris Lattnere7fca512002-01-24 19:12:12 +000025#include "llvm/Module.h"
Chris Lattnerad202a02002-04-08 00:14:58 +000026#include "llvm/PassManager.h"
27#include "llvm/Bytecode/Reader.h"
28#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattner9c3b55e2003-04-24 19:13:02 +000029#include "llvm/Target/TargetData.h"
Chris Lattnerd9d8c072002-07-23 22:04:43 +000030#include "llvm/Transforms/IPO.h"
Chris Lattnerd9d8c072002-07-23 22:04:43 +000031#include "llvm/Transforms/Scalar.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileUtilities.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000034#include "llvm/System/Signals.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/SystemUtils.h"
Chris Lattnere7fca512002-01-24 19:12:12 +000036#include <fstream>
37#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000038using namespace llvm;
39
Chris Lattnerf3d4f172003-04-18 23:01:25 +000040namespace {
41 cl::list<std::string>
42 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
43 cl::OneOrMore);
Chris Lattner5ff62e92002-07-22 02:10:13 +000044
Chris Lattnerf3d4f172003-04-18 23:01:25 +000045 cl::opt<std::string>
46 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
47 cl::value_desc("filename"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000048
Chris Lattnerf3d4f172003-04-18 23:01:25 +000049 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"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000055
Chris Lattnerf3d4f172003-04-18 23:01:25 +000056 cl::list<std::string>
57 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
58 cl::value_desc("library prefix"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000059
Chris Lattnerf3d4f172003-04-18 23:01:25 +000060 cl::opt<bool>
Chris Lattner3f14fb12004-12-02 21:26:10 +000061 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"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000065
Chris Lattnerf3d4f172003-04-18 23:01:25 +000066 cl::opt<bool>
67 NoInternalize("disable-internalize",
68 cl::desc("Do not mark all symbols as internal"));
Chris Lattnerfe32bf52003-11-05 06:05:21 +000069 cl::alias
Chris Lattnera2b2dc92003-08-22 19:18:45 +000070 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71 cl::aliasopt(NoInternalize));
Chris Lattnera856db22003-04-18 23:38:22 +000072
Chris Lattner10970eb2003-04-19 22:44:38 +000073 cl::opt<bool>
74 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
75 " library, not an executable"));
Chris Lattnerfe32bf52003-11-05 06:05:21 +000076 cl::alias
77 Relink("r", cl::desc("Alias for -link-as-library"),
78 cl::aliasopt(LinkAsLibrary));
Chris Lattner10970eb2003-04-19 22:44:38 +000079
John Criswelldabaf7d2003-09-16 21:27:35 +000080 cl::opt<bool>
Chris Lattner6e271232003-09-22 20:21:34 +000081 Native("native",
82 cl::desc("Generate a native binary instead of a shell script"));
Chris Lattner69e8d282004-04-06 16:43:13 +000083 cl::opt<bool>
84 NativeCBE("native-cbe",
85 cl::desc("Generate a native binary with the C backend and GCC"));
John Criswelldabaf7d2003-09-16 21:27:35 +000086
John Criswelldc0de4f2003-09-18 16:22:26 +000087 // Compatibility options that are ignored but supported by LD
Chris Lattnera856db22003-04-18 23:38:22 +000088 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"));
John Criswellaa2a47d2003-12-09 15:39:11 +000094 cl::opt<std::string>
95 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
Chris Lattner3f14fb12004-12-02 21:26:10 +000096
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));
Chris Lattnerf3d4f172003-04-18 23:01:25 +0000101}
Chris Lattnere7fca512002-01-24 19:12:12 +0000102
Chris Lattner0ebee742004-06-02 00:22:24 +0000103/// PrintAndReturn - Prints a message to standard error and returns true.
Misha Brukman98399692003-11-20 06:21:54 +0000104///
105/// Inputs:
106/// progname - The name of the program (i.e. argv[0]).
107/// Message - The message to print to standard error.
Misha Brukman98399692003-11-20 06:21:54 +0000108///
Chris Lattner0ebee742004-06-02 00:22:24 +0000109static int PrintAndReturn(const char *progname, const std::string &Message) {
110 std::cerr << progname << ": " << Message << "\n";
John Criswell71478b72003-09-19 20:24:23 +0000111 return 1;
Chris Lattner10970eb2003-04-19 22:44:38 +0000112}
113
Chris Lattner7e88d412004-06-02 00:10:19 +0000114/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
115/// bytecode file for the program.
116static void EmitShellScript(char **argv) {
Chris Lattner681692d2004-06-02 00:53:57 +0000117#if defined(_WIN32) || defined(__CYGWIN__)
118 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
119 // support windows systems, we copy the llvm-stub.exe executable from the
120 // build tree to the destination file.
121 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
122 if (llvmstub.empty()) {
123 std::cerr << "Could not find llvm-stub.exe executable!\n";
124 exit(1);
125 }
126 if (CopyFile(OutputFilename, llvmstub)) {
127 std::cerr << "Could not copy the llvm-stub.exe executable!\n";
128 exit(1);
129 }
130 return;
131#endif
132
Chris Lattner7e88d412004-06-02 00:10:19 +0000133 // Output the script to start the program...
134 std::ofstream Out2(OutputFilename.c_str());
135 if (!Out2.good())
136 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
137 "' for writing!"));
138
139 Out2 << "#!/bin/sh\n";
140 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
141 Out2 << "lli=${LLVMINTERP-lli}\n";
142 Out2 << "exec $lli \\\n";
143 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
144 LibPaths.push_back("/lib");
145 LibPaths.push_back("/usr/lib");
146 LibPaths.push_back("/usr/X11R6/lib");
147 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
148 // shared object at all! See RH 8: plain text.
149 std::vector<std::string>::iterator libc =
150 std::find(Libraries.begin(), Libraries.end(), "c");
151 if (libc != Libraries.end()) Libraries.erase(libc);
152 // List all the shared object (native) libraries this executable will need
153 // on the command line, so that we don't have to do this manually!
154 for (std::vector<std::string>::iterator i = Libraries.begin(),
155 e = Libraries.end(); i != e; ++i) {
156 std::string FullLibraryPath = FindLib(*i, LibPaths, true);
157 if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
158 Out2 << " -load=" << FullLibraryPath << " \\\n";
159 }
160 Out2 << " $0.bc ${1+\"$@\"}\n";
161 Out2.close();
162}
Chris Lattner10970eb2003-04-19 22:44:38 +0000163
Misha Brukmane97fbed2003-09-30 17:59:25 +0000164int main(int argc, char **argv, char **envp) {
Chris Lattner5ff62e92002-07-22 02:10:13 +0000165 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
Reid Spencer9de7b332004-08-29 19:28:55 +0000166 sys::PrintStackTraceOnErrorSignal();
Chris Lattnere7fca512002-01-24 19:12:12 +0000167
Reid Spencer4c1af902004-11-14 22:17:03 +0000168 int exitCode = 0;
Chris Lattnere7fca512002-01-24 19:12:12 +0000169
Reid Spencer4c1af902004-11-14 22:17:03 +0000170 try {
171 std::string ModuleID("gccld-output");
172 std::auto_ptr<Module> Composite(new Module(ModuleID));
Brian Gaeke69a79602003-05-23 20:27:07 +0000173
Chris Lattner86f42db2004-11-17 16:41:19 +0000174 // We always look first in the current directory when searching for
175 // libraries.
Reid Spencer4c1af902004-11-14 22:17:03 +0000176 LibPaths.insert(LibPaths.begin(), ".");
Chris Lattnerd34a51d2003-04-21 19:53:24 +0000177
Reid Spencer4c1af902004-11-14 22:17:03 +0000178 // If the user specified an extra search path in their environment, respect
179 // it.
180 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
181 LibPaths.push_back(SearchPath);
Chris Lattnerc65b1042003-04-19 23:07:33 +0000182
Reid Spencer4c1af902004-11-14 22:17:03 +0000183 // Remove any consecutive duplicates of the same library...
184 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
185 Libraries.end());
Chris Lattnerfd35c642003-11-03 17:27:17 +0000186
Reid Spencer4c1af902004-11-14 22:17:03 +0000187 // Link in all of the files
188 if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
189 return 1; // Error already printed
John Criswell71478b72003-09-19 20:24:23 +0000190
Reid Spencer4c1af902004-11-14 22:17:03 +0000191 if (!LinkAsLibrary)
192 LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
193 Verbose, Native);
Chris Lattnere7fca512002-01-24 19:12:12 +0000194
Reid Spencer4c1af902004-11-14 22:17:03 +0000195 // Link in all of the libraries next...
Chris Lattnere7fca512002-01-24 19:12:12 +0000196
Reid Spencer4c1af902004-11-14 22:17:03 +0000197 // Create the output file.
198 std::string RealBytecodeOutput = OutputFilename;
199 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
200 std::ofstream Out(RealBytecodeOutput.c_str());
201 if (!Out.good())
202 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
203 "' for writing!");
Chris Lattner76d12292002-04-18 19:55:25 +0000204
Reid Spencer4c1af902004-11-14 22:17:03 +0000205 // Ensure that the bytecode file gets removed from the disk if we get a
206 // SIGINT signal.
207 sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
John Criswelldc0de4f2003-09-18 16:22:26 +0000208
Reid Spencer4c1af902004-11-14 22:17:03 +0000209 // Generate the bytecode file.
Chris Lattner3f14fb12004-12-02 21:26:10 +0000210 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
211 if (GenerateBytecode(Composite.get(), StripLevel, !NoInternalize, &Out)) {
Reid Spencer4c1af902004-11-14 22:17:03 +0000212 Out.close();
213 return PrintAndReturn(argv[0], "error generating bytecode");
John Criswelldabaf7d2003-09-16 21:27:35 +0000214 }
Misha Brukmanc1fdca82003-08-20 20:38:15 +0000215
Reid Spencer4c1af902004-11-14 22:17:03 +0000216 // Close the bytecode file.
217 Out.close();
218
219 // If we are not linking a library, generate either a native executable
220 // or a JIT shell script, depending upon what the user wants.
221 if (!LinkAsLibrary) {
222 // If the user wants to generate a native executable, compile it from the
223 // bytecode file.
224 //
225 // Otherwise, create a script that will run the bytecode through the JIT.
226 if (Native) {
227 // Name of the Assembly Language output file
228 std::string AssemblyFile = OutputFilename + ".s";
229
230 // Mark the output files for removal if we get an interrupt.
231 sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
232 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
233
234 // Determine the locations of the llc and gcc programs.
235 std::string llc = FindExecutable("llc", argv[0]);
236 std::string gcc = FindExecutable("gcc", argv[0]);
237 if (llc.empty())
238 return PrintAndReturn(argv[0], "Failed to find llc");
239
240 if (gcc.empty())
241 return PrintAndReturn(argv[0], "Failed to find gcc");
242
243 // Generate an assembly language file for the bytecode.
244 if (Verbose) std::cout << "Generating Assembly Code\n";
245 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
246 if (Verbose) std::cout << "Generating Native Code\n";
247 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
248 gcc, envp);
249
250 // Remove the assembly language file.
251 removeFile (AssemblyFile);
252 } else if (NativeCBE) {
253 std::string CFile = OutputFilename + ".cbe.c";
254
255 // Mark the output files for removal if we get an interrupt.
256 sys::RemoveFileOnSignal(sys::Path(CFile));
257 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
258
259 // Determine the locations of the llc and gcc programs.
260 std::string llc = FindExecutable("llc", argv[0]);
261 std::string gcc = FindExecutable("gcc", argv[0]);
262 if (llc.empty())
263 return PrintAndReturn(argv[0], "Failed to find llc");
264 if (gcc.empty())
265 return PrintAndReturn(argv[0], "Failed to find gcc");
266
267 // Generate an assembly language file for the bytecode.
268 if (Verbose) std::cout << "Generating Assembly Code\n";
269 GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
270 if (Verbose) std::cout << "Generating Native Code\n";
271 GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
272
273 // Remove the assembly language file.
274 removeFile(CFile);
275
276 } else {
277 EmitShellScript(argv);
278 }
279
280 // Make the script executable...
281 MakeFileExecutable(OutputFilename);
282
283 // Make the bytecode file readable and directly executable in LLEE as well
284 MakeFileExecutable(RealBytecodeOutput);
285 MakeFileReadable(RealBytecodeOutput);
286 }
287 } catch (const char*msg) {
288 std::cerr << argv[0] << ": " << msg << "\n";
289 exitCode = 1;
290 } catch (const std::string& msg) {
291 std::cerr << argv[0] << ": " << msg << "\n";
292 exitCode = 2;
293 } catch (...) {
294 // This really shouldn't happen, but just in case ....
295 std::cerr << argv[0] << ": An nexpected unknown exception occurred.\n";
296 exitCode = 3;
Chris Lattner10970eb2003-04-19 22:44:38 +0000297 }
Chris Lattnere7fca512002-01-24 19:12:12 +0000298
Reid Spencer4c1af902004-11-14 22:17:03 +0000299 return exitCode;
Chris Lattnere7fca512002-01-24 19:12:12 +0000300}