blob: 8698cc889910fa2fa1ed554666c2274446638a73 [file] [log] [blame]
Chris Lattner1d496172003-04-19 22:44:38 +00001//===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
John Criswell09344dc2003-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 Lattner5ff2e052002-01-24 19:12:12 +00009//
10// This utility is intended to be compatible with GCC, and follows standard
Chris Lattner1d496172003-04-19 22:44:38 +000011// system 'ld' conventions. As such, the default output file is ./a.out.
Chris Lattner5ff2e052002-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 Gaeke5bfa37f2003-05-23 20:27:07 +000019// I'm not too worried about this.
Chris Lattner5ff2e052002-01-24 19:12:12 +000020//
21//===----------------------------------------------------------------------===//
22
Chris Lattner65d93e22003-09-22 20:21:34 +000023#include "gccld.h"
Reid Spencer16c3bb32004-11-14 23:00:08 +000024#include "llvm/Linker.h"
Chris Lattner5ff2e052002-01-24 19:12:12 +000025#include "llvm/Module.h"
Chris Lattner3b08c2f2002-04-08 00:14:58 +000026#include "llvm/PassManager.h"
27#include "llvm/Bytecode/Reader.h"
28#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerd571e2a2003-04-24 19:13:02 +000029#include "llvm/Target/TargetData.h"
Chris Lattner35c45412002-07-23 22:04:43 +000030#include "llvm/Transforms/IPO.h"
Chris Lattner35c45412002-07-23 22:04:43 +000031#include "llvm/Transforms/Scalar.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileUtilities.h"
Chris Lattner278f5152004-05-27 05:41:36 +000034#include "llvm/System/Signals.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000035#include "llvm/Support/SystemUtils.h"
Chris Lattner5ff2e052002-01-24 19:12:12 +000036#include <fstream>
37#include <memory>
Brian Gaeke960707c2003-11-11 22:41:34 +000038using namespace llvm;
39
Chris Lattner2b3a5db2003-04-18 23:01:25 +000040namespace {
41 cl::list<std::string>
42 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
43 cl::OneOrMore);
Chris Lattnerf5cad152002-07-22 02:10:13 +000044
Chris Lattner2b3a5db2003-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 Lattnerf5cad152002-07-22 02:10:13 +000048
Chris Lattner2b3a5db2003-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 Lattnerf5cad152002-07-22 02:10:13 +000055
Chris Lattner2b3a5db2003-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 Lattnerf5cad152002-07-22 02:10:13 +000059
Chris Lattner2b3a5db2003-04-18 23:01:25 +000060 cl::opt<bool>
Chris Lattner4913b652004-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 Lattnerf5cad152002-07-22 02:10:13 +000065
Chris Lattner2b3a5db2003-04-18 23:01:25 +000066 cl::opt<bool>
67 NoInternalize("disable-internalize",
68 cl::desc("Do not mark all symbols as internal"));
Chris Lattnerc17fe1c2003-11-05 06:05:21 +000069 cl::alias
Chris Lattnerb4d99212003-08-22 19:18:45 +000070 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71 cl::aliasopt(NoInternalize));
Chris Lattner602d2092003-04-18 23:38:22 +000072
Chris Lattner1d496172003-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 Lattnerc17fe1c2003-11-05 06:05:21 +000076 cl::alias
77 Relink("r", cl::desc("Alias for -link-as-library"),
78 cl::aliasopt(LinkAsLibrary));
Chris Lattner1d496172003-04-19 22:44:38 +000079
John Criswell1997a342003-09-16 21:27:35 +000080 cl::opt<bool>
Chris Lattner65d93e22003-09-22 20:21:34 +000081 Native("native",
82 cl::desc("Generate a native binary instead of a shell script"));
Chris Lattnerad733e72004-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"));
Reid Spencer9947c422005-02-28 08:45:35 +000086
87 cl::opt<std::string>
88 RPath("rpath",
89 cl::desc("Set runtime shared library search path (requires -native or"
90 " -native-cbe)"),
91 cl::Prefix, cl::value_desc("directory"));
92
93 cl::opt<std::string>
94 SOName("soname",
95 cl::desc("Set internal name of shared library (requires -native or"
96 " -native-cbe)"),
97 cl::Prefix, cl::value_desc("name"));
John Criswell1997a342003-09-16 21:27:35 +000098
John Criswell8ecc3022003-09-18 16:22:26 +000099 // Compatibility options that are ignored but supported by LD
Chris Lattner602d2092003-04-18 23:38:22 +0000100 cl::opt<std::string>
Chris Lattner602d2092003-04-18 23:38:22 +0000101 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
102 cl::opt<bool>
103 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
John Criswell7dd71512003-12-09 15:39:11 +0000104 cl::opt<std::string>
105 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
Chris Lattner4913b652004-12-02 21:26:10 +0000106
107 cl::alias A0("s", cl::desc("Alias for --strip-all"),
108 cl::aliasopt(Strip));
109 cl::alias A1("S", cl::desc("Alias for --strip-debug"),
110 cl::aliasopt(StripDebug));
Reid Spencer8d206902004-12-13 03:01:14 +0000111
Chris Lattner2b3a5db2003-04-18 23:01:25 +0000112}
Chris Lattner5ff2e052002-01-24 19:12:12 +0000113
Chris Lattner85b943d2004-06-02 00:22:24 +0000114/// PrintAndReturn - Prints a message to standard error and returns true.
Misha Brukmand16a0372003-11-20 06:21:54 +0000115///
116/// Inputs:
117/// progname - The name of the program (i.e. argv[0]).
118/// Message - The message to print to standard error.
Misha Brukmand16a0372003-11-20 06:21:54 +0000119///
Chris Lattner85b943d2004-06-02 00:22:24 +0000120static int PrintAndReturn(const char *progname, const std::string &Message) {
121 std::cerr << progname << ": " << Message << "\n";
John Criswellb533bde2003-09-19 20:24:23 +0000122 return 1;
Chris Lattner1d496172003-04-19 22:44:38 +0000123}
124
Chris Lattnerfdcb8682004-06-02 00:10:19 +0000125/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
126/// bytecode file for the program.
127static void EmitShellScript(char **argv) {
Chris Lattner6662d332004-06-02 00:53:57 +0000128#if defined(_WIN32) || defined(__CYGWIN__)
129 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
130 // support windows systems, we copy the llvm-stub.exe executable from the
131 // build tree to the destination file.
Reid Spencer79dc8b72004-12-13 23:44:23 +0000132 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]).toString();
Chris Lattner6662d332004-06-02 00:53:57 +0000133 if (llvmstub.empty()) {
134 std::cerr << "Could not find llvm-stub.exe executable!\n";
135 exit(1);
136 }
Reid Spencer4acff402004-12-21 03:24:02 +0000137 sys::CopyFile(sys::Path(OutputFilename), sys::Path(llvmstub));
Chris Lattner6662d332004-06-02 00:53:57 +0000138 return;
139#endif
140
Chris Lattnerfdcb8682004-06-02 00:10:19 +0000141 // Output the script to start the program...
142 std::ofstream Out2(OutputFilename.c_str());
143 if (!Out2.good())
144 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
145 "' for writing!"));
146
147 Out2 << "#!/bin/sh\n";
148 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
149 Out2 << "lli=${LLVMINTERP-lli}\n";
150 Out2 << "exec $lli \\\n";
Reid Spencer8d206902004-12-13 03:01:14 +0000151
Chris Lattnerfdcb8682004-06-02 00:10:19 +0000152 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
153 // shared object at all! See RH 8: plain text.
154 std::vector<std::string>::iterator libc =
155 std::find(Libraries.begin(), Libraries.end(), "c");
156 if (libc != Libraries.end()) Libraries.erase(libc);
157 // List all the shared object (native) libraries this executable will need
158 // on the command line, so that we don't have to do this manually!
159 for (std::vector<std::string>::iterator i = Libraries.begin(),
160 e = Libraries.end(); i != e; ++i) {
Reid Spencer8d206902004-12-13 03:01:14 +0000161 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
162 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
163 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Chris Lattnerfdcb8682004-06-02 00:10:19 +0000164 }
165 Out2 << " $0.bc ${1+\"$@\"}\n";
166 Out2.close();
167}
Chris Lattner1d496172003-04-19 22:44:38 +0000168
Reid Spencer8d206902004-12-13 03:01:14 +0000169// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
170// linker function by combining the Files and Libraries in the order they were
171// declared on the command line.
172static void BuildLinkItems(
173 Linker::ItemList& Items,
174 const cl::list<std::string>& Files,
175 const cl::list<std::string>& Libraries) {
176
177 // Build the list of linkage items for LinkItems.
178
179 cl::list<std::string>::const_iterator fileIt = Files.begin();
180 cl::list<std::string>::const_iterator libIt = Libraries.begin();
181
182 int libPos = -1, filePos = -1;
Reid Spencer0afe1782004-12-13 17:18:19 +0000183 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencer8d206902004-12-13 03:01:14 +0000184 if (libIt != Libraries.end())
185 libPos = Libraries.getPosition(libIt - Libraries.begin());
186 else
187 libPos = -1;
188 if (fileIt != Files.end())
189 filePos = Files.getPosition(fileIt - Files.begin());
190 else
191 filePos = -1;
192
193 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
194 // Add a source file
195 Items.push_back(std::make_pair(*fileIt++, false));
196 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
197 // Add a library
198 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencer8d206902004-12-13 03:01:14 +0000199 }
200 }
201}
Reid Spencer0afe1782004-12-13 17:18:19 +0000202
Reid Spencer79dc8b72004-12-13 23:44:23 +0000203int main(int argc, char **argv, char **envp ) {
Chris Lattnerf5cad152002-07-22 02:10:13 +0000204 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
Reid Spencere3263ec2004-08-29 19:28:55 +0000205 sys::PrintStackTraceOnErrorSignal();
Chris Lattner5ff2e052002-01-24 19:12:12 +0000206
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000207 int exitCode = 0;
Chris Lattner5ff2e052002-01-24 19:12:12 +0000208
Reid Spencer8d206902004-12-13 03:01:14 +0000209 std::string ProgName = sys::Path(argv[0]).getBasename();
210 Linker TheLinker(ProgName, Verbose);
211
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000212 try {
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000213 // Remove any consecutive duplicates of the same library...
214 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
215 Libraries.end());
Chris Lattnercbf2aeb2003-11-03 17:27:17 +0000216
Reid Spencer8d206902004-12-13 03:01:14 +0000217 TheLinker.addPaths(LibPaths);
218 TheLinker.addSystemPaths();
John Criswellb533bde2003-09-19 20:24:23 +0000219
Reid Spenceref966652004-12-05 19:15:29 +0000220 if (LinkAsLibrary) {
Reid Spencer8d206902004-12-13 03:01:14 +0000221 std::vector<sys::Path> Files;
222 for (unsigned i = 0; i < InputFilenames.size(); ++i )
223 Files.push_back(sys::Path(InputFilenames[i]));
224
225 if (TheLinker.LinkInFiles(Files))
226 return 1; // Error already printed by linker
227
Reid Spencer359df302004-12-08 05:17:40 +0000228 // The libraries aren't linked in but are noted as "dependent" in the
229 // module.
230 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
231 E = Libraries.end(); I != E ; ++I) {
Reid Spencer8d206902004-12-13 03:01:14 +0000232 TheLinker.getModule()->addLibrary(*I);
Reid Spencer359df302004-12-08 05:17:40 +0000233 }
234
Reid Spenceref966652004-12-05 19:15:29 +0000235 } else {
236 // Build a list of the items from our command line
Reid Spencer8d206902004-12-13 03:01:14 +0000237 Linker::ItemList Items;
Reid Spenceref966652004-12-05 19:15:29 +0000238 BuildLinkItems(Items, InputFilenames, Libraries);
Chris Lattner5ff2e052002-01-24 19:12:12 +0000239
Reid Spenceref966652004-12-05 19:15:29 +0000240 // Link all the items together
Reid Spencer8d206902004-12-13 03:01:14 +0000241 if (TheLinker.LinkInItems(Items))
Reid Spenceref966652004-12-05 19:15:29 +0000242 return 1; // Error already printed
243 }
Chris Lattner5ff2e052002-01-24 19:12:12 +0000244
Reid Spencer8d206902004-12-13 03:01:14 +0000245 // We're done with the Linker, so tell it to release its module
246 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
247
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000248 // Create the output file.
249 std::string RealBytecodeOutput = OutputFilename;
Reid Spencer9947c422005-02-28 08:45:35 +0000250 if (!LinkAsLibrary || Native || NativeCBE) RealBytecodeOutput += ".bc";
Jeff Cohenc8f1f4b2005-01-22 17:36:17 +0000251 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
252 std::ios::binary;
253 std::ofstream Out(RealBytecodeOutput.c_str(), io_mode);
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000254 if (!Out.good())
255 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
256 "' for writing!");
Chris Lattnerc065ad82002-04-18 19:55:25 +0000257
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000258 // Ensure that the bytecode file gets removed from the disk if we get a
259 // SIGINT signal.
260 sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
John Criswell8ecc3022003-09-18 16:22:26 +0000261
Chris Lattnerb92fd602004-12-12 07:53:51 +0000262 // Strip everything if Strip is set, otherwise if stripdebug is set, just
263 // strip debug info.
Chris Lattner4913b652004-12-02 21:26:10 +0000264 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
Chris Lattnerb92fd602004-12-12 07:53:51 +0000265
266 // Internalize the module if neither -disable-internalize nor
267 // -link-as-library are passed in.
268 bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
269
270 // Generate the bytecode file.
271 if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000272 Out.close();
273 return PrintAndReturn(argv[0], "error generating bytecode");
John Criswell1997a342003-09-16 21:27:35 +0000274 }
Misha Brukman90869942003-08-20 20:38:15 +0000275
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000276 // Close the bytecode file.
277 Out.close();
278
Reid Spencer9947c422005-02-28 08:45:35 +0000279 // Generate either a native file or a JIT shell script. If the user wants
280 // to generate a native file, compile it from the bytecode file. Otherwise,
281 // if the target is not a library, create a script that will run the
282 // bytecode through the JIT.
283 if (Native) {
284 // Name of the Assembly Language output file
285 sys::Path AssemblyFile (OutputFilename);
286 AssemblyFile.appendSuffix("s");
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000287
Reid Spencer9947c422005-02-28 08:45:35 +0000288 // Mark the output files for removal if we get an interrupt.
289 sys::RemoveFileOnSignal(AssemblyFile);
290 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000291
Reid Spencer9947c422005-02-28 08:45:35 +0000292 // Determine the locations of the llc and gcc programs.
293 sys::Path llc = FindExecutable("llc", argv[0]);
294 if (llc.isEmpty())
295 return PrintAndReturn(argv[0], "Failed to find llc");
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000296
Reid Spencer9947c422005-02-28 08:45:35 +0000297 sys::Path gcc = FindExecutable("gcc", argv[0]);
298 if (gcc.isEmpty())
299 return PrintAndReturn(argv[0], "Failed to find gcc");
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000300
Reid Spencer9947c422005-02-28 08:45:35 +0000301 // Generate an assembly language file for the bytecode.
302 if (Verbose) std::cout << "Generating Assembly Code\n";
303 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
304 if (Verbose) std::cout << "Generating Native Code\n";
305 GenerateNative(OutputFilename, AssemblyFile.toString(),
306 LibPaths, Libraries, gcc, envp, LinkAsLibrary, RPath,
307 SOName );
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000308
Reid Spencer9947c422005-02-28 08:45:35 +0000309 // Remove the assembly language file.
310 AssemblyFile.destroyFile();
311 // Remove the bytecode language file.
312 sys::Path(RealBytecodeOutput).destroyFile();
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000313
Reid Spencer9947c422005-02-28 08:45:35 +0000314 } else if (NativeCBE) {
315 sys::Path CFile (OutputFilename);
316 CFile.appendSuffix("cbe.c");
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000317
Reid Spencer9947c422005-02-28 08:45:35 +0000318 // Mark the output files for removal if we get an interrupt.
319 sys::RemoveFileOnSignal(CFile);
320 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
321
322 // Determine the locations of the llc and gcc programs.
323 sys::Path llc = FindExecutable("llc", argv[0]);
324 if (llc.isEmpty())
325 return PrintAndReturn(argv[0], "Failed to find llc");
326
327 sys::Path gcc = FindExecutable("gcc", argv[0]);
328 if (gcc.isEmpty())
329 return PrintAndReturn(argv[0], "Failed to find gcc");
330
331 // Generate an assembly language file for the bytecode.
332 if (Verbose) std::cout << "Generating Assembly Code\n";
333 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
334 if (Verbose) std::cout << "Generating Native Code\n";
335 GenerateNative(OutputFilename, CFile.toString(),
336 LibPaths, Libraries, gcc, envp, LinkAsLibrary, RPath,
337 SOName );
338
339 // Remove the assembly language file.
340 CFile.destroyFile();
341
342 // Remove the bytecode language file.
343 sys::Path(RealBytecodeOutput).destroyFile();
344
345 } else if (!LinkAsLibrary) {
346 EmitShellScript(argv);
347
348 // Make the bytecode file readable and directly executable in LLEE
Reid Spencer249eb142004-12-13 20:03:02 +0000349 sys::Path(RealBytecodeOutput).makeExecutable();
350 sys::Path(RealBytecodeOutput).makeReadable();
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000351 }
Reid Spencer9947c422005-02-28 08:45:35 +0000352
353 // Make the output, whether native or script, executable as well...
354 sys::Path(OutputFilename).makeExecutable();
355
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000356 } catch (const char*msg) {
357 std::cerr << argv[0] << ": " << msg << "\n";
358 exitCode = 1;
359 } catch (const std::string& msg) {
360 std::cerr << argv[0] << ": " << msg << "\n";
361 exitCode = 2;
362 } catch (...) {
363 // This really shouldn't happen, but just in case ....
Reid Spencer8d206902004-12-13 03:01:14 +0000364 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000365 exitCode = 3;
Chris Lattner1d496172003-04-19 22:44:38 +0000366 }
Chris Lattner5ff2e052002-01-24 19:12:12 +0000367
Reid Spencer5ccfd9a2004-11-14 22:17:03 +0000368 return exitCode;
Chris Lattner5ff2e052002-01-24 19:12:12 +0000369}