blob: db03b208b917003c3b2c02c10a81fcb030745fe8 [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));
Reid Spencerc4064132004-12-13 03:01:14 +0000101
Chris Lattnerf3d4f172003-04-18 23:01:25 +0000102}
Chris Lattnere7fca512002-01-24 19:12:12 +0000103
Chris Lattner0ebee742004-06-02 00:22:24 +0000104/// PrintAndReturn - Prints a message to standard error and returns true.
Misha Brukman98399692003-11-20 06:21:54 +0000105///
106/// Inputs:
107/// progname - The name of the program (i.e. argv[0]).
108/// Message - The message to print to standard error.
Misha Brukman98399692003-11-20 06:21:54 +0000109///
Chris Lattner0ebee742004-06-02 00:22:24 +0000110static int PrintAndReturn(const char *progname, const std::string &Message) {
111 std::cerr << progname << ": " << Message << "\n";
John Criswell71478b72003-09-19 20:24:23 +0000112 return 1;
Chris Lattner10970eb2003-04-19 22:44:38 +0000113}
114
Chris Lattner7e88d412004-06-02 00:10:19 +0000115/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
116/// bytecode file for the program.
117static void EmitShellScript(char **argv) {
Chris Lattner681692d2004-06-02 00:53:57 +0000118#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]);
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
Chris Lattner7e88d412004-06-02 00:10:19 +0000134 // 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";
Reid Spencerc4064132004-12-13 03:01:14 +0000144
Chris Lattner7e88d412004-06-02 00:10:19 +0000145 // 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) {
Reid Spencerc4064132004-12-13 03:01:14 +0000154 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
155 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
156 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Chris Lattner7e88d412004-06-02 00:10:19 +0000157 }
158 Out2 << " $0.bc ${1+\"$@\"}\n";
159 Out2.close();
160}
Chris Lattner10970eb2003-04-19 22:44:38 +0000161
Reid Spencerc4064132004-12-13 03:01:14 +0000162// 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.
165static 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 ( 1 ) {
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 } else {
193 break; // we're done with the list
194 }
195 }
196}
Misha Brukmane97fbed2003-09-30 17:59:25 +0000197int main(int argc, char **argv, char **envp) {
Chris Lattner5ff62e92002-07-22 02:10:13 +0000198 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
Reid Spencer9de7b332004-08-29 19:28:55 +0000199 sys::PrintStackTraceOnErrorSignal();
Chris Lattnere7fca512002-01-24 19:12:12 +0000200
Reid Spencer4c1af902004-11-14 22:17:03 +0000201 int exitCode = 0;
Chris Lattnere7fca512002-01-24 19:12:12 +0000202
Reid Spencerc4064132004-12-13 03:01:14 +0000203 std::string ProgName = sys::Path(argv[0]).getBasename();
204 Linker TheLinker(ProgName, Verbose);
205
Reid Spencer4c1af902004-11-14 22:17:03 +0000206 try {
Reid Spencer4c1af902004-11-14 22:17:03 +0000207 // Remove any consecutive duplicates of the same library...
208 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
209 Libraries.end());
Chris Lattnerfd35c642003-11-03 17:27:17 +0000210
Reid Spencerc4064132004-12-13 03:01:14 +0000211 TheLinker.addPaths(LibPaths);
212 TheLinker.addSystemPaths();
John Criswell71478b72003-09-19 20:24:23 +0000213
Reid Spencerc191d492004-12-05 19:15:29 +0000214 if (LinkAsLibrary) {
Reid Spencerc4064132004-12-13 03:01:14 +0000215 std::vector<sys::Path> Files;
216 for (unsigned i = 0; i < InputFilenames.size(); ++i )
217 Files.push_back(sys::Path(InputFilenames[i]));
218
219 if (TheLinker.LinkInFiles(Files))
220 return 1; // Error already printed by linker
221
Reid Spencer6b463b22004-12-08 05:17:40 +0000222 // The libraries aren't linked in but are noted as "dependent" in the
223 // module.
224 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
225 E = Libraries.end(); I != E ; ++I) {
Reid Spencerc4064132004-12-13 03:01:14 +0000226 TheLinker.getModule()->addLibrary(*I);
Reid Spencer6b463b22004-12-08 05:17:40 +0000227 }
228
Reid Spencerc191d492004-12-05 19:15:29 +0000229 } else {
230 // Build a list of the items from our command line
Reid Spencerc4064132004-12-13 03:01:14 +0000231 Linker::ItemList Items;
Reid Spencerc191d492004-12-05 19:15:29 +0000232 BuildLinkItems(Items, InputFilenames, Libraries);
Chris Lattnere7fca512002-01-24 19:12:12 +0000233
Reid Spencerc191d492004-12-05 19:15:29 +0000234 // Link all the items together
Reid Spencerc4064132004-12-13 03:01:14 +0000235 if (TheLinker.LinkInItems(Items))
Reid Spencerc191d492004-12-05 19:15:29 +0000236 return 1; // Error already printed
237 }
Chris Lattnere7fca512002-01-24 19:12:12 +0000238
Reid Spencerc4064132004-12-13 03:01:14 +0000239 // We're done with the Linker, so tell it to release its module
240 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
241
Reid Spencer4c1af902004-11-14 22:17:03 +0000242 // Create the output file.
243 std::string RealBytecodeOutput = OutputFilename;
244 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
245 std::ofstream Out(RealBytecodeOutput.c_str());
246 if (!Out.good())
247 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
248 "' for writing!");
Chris Lattner76d12292002-04-18 19:55:25 +0000249
Reid Spencer4c1af902004-11-14 22:17:03 +0000250 // Ensure that the bytecode file gets removed from the disk if we get a
251 // SIGINT signal.
252 sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
John Criswelldc0de4f2003-09-18 16:22:26 +0000253
Chris Lattnerbcfe1e22004-12-12 07:53:51 +0000254 // Strip everything if Strip is set, otherwise if stripdebug is set, just
255 // strip debug info.
Chris Lattner3f14fb12004-12-02 21:26:10 +0000256 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
Chris Lattnerbcfe1e22004-12-12 07:53:51 +0000257
258 // Internalize the module if neither -disable-internalize nor
259 // -link-as-library are passed in.
260 bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
261
262 // Generate the bytecode file.
263 if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
Reid Spencer4c1af902004-11-14 22:17:03 +0000264 Out.close();
265 return PrintAndReturn(argv[0], "error generating bytecode");
John Criswelldabaf7d2003-09-16 21:27:35 +0000266 }
Misha Brukmanc1fdca82003-08-20 20:38:15 +0000267
Reid Spencer4c1af902004-11-14 22:17:03 +0000268 // Close the bytecode file.
269 Out.close();
270
271 // If we are not linking a library, generate either a native executable
272 // or a JIT shell script, depending upon what the user wants.
273 if (!LinkAsLibrary) {
274 // If the user wants to generate a native executable, compile it from the
275 // bytecode file.
276 //
277 // Otherwise, create a script that will run the bytecode through the JIT.
278 if (Native) {
279 // Name of the Assembly Language output file
280 std::string AssemblyFile = OutputFilename + ".s";
281
282 // Mark the output files for removal if we get an interrupt.
283 sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
284 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
285
286 // Determine the locations of the llc and gcc programs.
287 std::string llc = FindExecutable("llc", argv[0]);
288 std::string gcc = FindExecutable("gcc", argv[0]);
289 if (llc.empty())
290 return PrintAndReturn(argv[0], "Failed to find llc");
291
292 if (gcc.empty())
293 return PrintAndReturn(argv[0], "Failed to find gcc");
294
295 // Generate an assembly language file for the bytecode.
296 if (Verbose) std::cout << "Generating Assembly Code\n";
297 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
298 if (Verbose) std::cout << "Generating Native Code\n";
299 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
300 gcc, envp);
301
302 // Remove the assembly language file.
303 removeFile (AssemblyFile);
304 } else if (NativeCBE) {
305 std::string CFile = OutputFilename + ".cbe.c";
306
307 // Mark the output files for removal if we get an interrupt.
308 sys::RemoveFileOnSignal(sys::Path(CFile));
309 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
310
311 // Determine the locations of the llc and gcc programs.
312 std::string llc = FindExecutable("llc", argv[0]);
313 std::string gcc = FindExecutable("gcc", argv[0]);
314 if (llc.empty())
315 return PrintAndReturn(argv[0], "Failed to find llc");
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 MakeFileExecutable(OutputFilename);
334
335 // Make the bytecode file readable and directly executable in LLEE as well
336 MakeFileExecutable(RealBytecodeOutput);
337 MakeFileReadable(RealBytecodeOutput);
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 ....
Reid Spencerc4064132004-12-13 03:01:14 +0000347 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
Reid Spencer4c1af902004-11-14 22:17:03 +0000348 exitCode = 3;
Chris Lattner10970eb2003-04-19 22:44:38 +0000349 }
Chris Lattnere7fca512002-01-24 19:12:12 +0000350
Reid Spencer4c1af902004-11-14 22:17:03 +0000351 return exitCode;
Chris Lattnere7fca512002-01-24 19:12:12 +0000352}