blob: 2aa6d18350edc373f62b7294e404348e9de3080c [file] [log] [blame]
Reid Spencerc0af3f02004-09-13 01:27:53 +00001//===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Reid Spencerc0af3f02004-09-13 01:27:53 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Reid Spencerc0af3f02004-09-13 01:27:53 +00008//===----------------------------------------------------------------------===//
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
Reid Spenceraf303d52006-06-07 23:03:13 +000023#include "llvm/LinkAllVMCore.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000024#include "llvm/Linker.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000025#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000026#include "llvm/Module.h"
27#include "llvm/PassManager.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000028#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer445564a2004-11-20 20:02:56 +000029#include "llvm/Bytecode/Writer.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000030#include "llvm/Target/TargetData.h"
Reid Spenceraefd04b2004-09-25 16:00:07 +000031#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetMachineRegistry.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/FileUtilities.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000035#include "llvm/Support/ManagedStatic.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000036#include "llvm/Support/MemoryBuffer.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000037#include "llvm/Support/Streams.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000038#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000039#include "llvm/System/Signals.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000040#include <fstream>
41#include <memory>
42using namespace llvm;
43
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000044cl::opt<bool> Bitcode("bitcode");
45
Reid Spencer445564a2004-11-20 20:02:56 +000046// Input/Output Options
47static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
48 cl::desc("<input bytecode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000049
Reid Spencer445564a2004-11-20 20:02:56 +000050static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000051 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000052 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000053
Misha Brukman3da94ae2005-04-22 00:00:37 +000054static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000055 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000056
Reid Spencer445564a2004-11-20 20:02:56 +000057static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000058 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000059 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000060
Reid Spencer445564a2004-11-20 20:02:56 +000061static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000062 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000063 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000064
Reid Spencer708585a2007-02-09 03:08:06 +000065// Options to control the linking, optimization, and code gen processes
Misha Brukman3da94ae2005-04-22 00:00:37 +000066static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000067 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000068
Reid Spencer445564a2004-11-20 20:02:56 +000069static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
70 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000071
Reid Spencer445564a2004-11-20 20:02:56 +000072static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
Reid Spenceraefd04b2004-09-25 16:00:07 +000073 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
74
Reid Spencer445564a2004-11-20 20:02:56 +000075static cl::opt<bool> Native("native",
76 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000077
Reid Spencer445564a2004-11-20 20:02:56 +000078static cl::opt<bool>NativeCBE("native-cbe",
79 cl::desc("Generate a native binary with the C backend and GCC"));
80
Chris Lattner17be6792007-01-21 06:34:18 +000081static cl::opt<bool>DisableCompression("disable-compression", cl::init(true),
Reid Spencer445564a2004-11-20 20:02:56 +000082 cl::desc("Disable writing of compressed bytecode files"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000083
Reid Spencer73a74be2005-12-21 05:03:23 +000084static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000085 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000086 cl::desc("Run one or more optimization programs after linking"));
87
Reid Spenceraf303d52006-06-07 23:03:13 +000088static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
89 cl::desc("Pass options to the system linker"));
90
Reid Spencer708585a2007-02-09 03:08:06 +000091// Compatibility options that llvm-ld ignores but are supported for
92// compatibility with LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000093static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000094 cl::desc("Compatibility option: ignored"));
95
Misha Brukman3da94ae2005-04-22 00:00:37 +000096static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000097 cl::desc("Compatibility option: ignored"));
98
Misha Brukman3da94ae2005-04-22 00:00:37 +000099static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000100 cl::desc("Compatibility option: ignored"));
101
Misha Brukman3da94ae2005-04-22 00:00:37 +0000102static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000103 cl::desc("Compatibility option: ignored"));
104
Reid Spencer98a030c2007-02-08 19:03:11 +0000105static cl::opt<bool> CO7("start-group", cl::Hidden,
106 cl::desc("Compatibility option: ignored"));
107
108static cl::opt<bool> CO8("end-group", cl::Hidden,
109 cl::desc("Compatibility option: ignored"));
Reid Spenceraf303d52006-06-07 23:03:13 +0000110
Reid Spencer445564a2004-11-20 20:02:56 +0000111/// This is just for convenience so it doesn't have to be passed around
112/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000113static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000114
Reid Spencer708585a2007-02-09 03:08:06 +0000115/// PrintAndExit - Prints a message to standard error and exits with error code
Reid Spencerc0af3f02004-09-13 01:27:53 +0000116///
117/// Inputs:
Reid Spencerc0af3f02004-09-13 01:27:53 +0000118/// Message - The message to print to standard error.
119///
Reid Spencer708585a2007-02-09 03:08:06 +0000120static void PrintAndExit(const std::string &Message, int errcode = 1) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000121 cerr << progname << ": " << Message << "\n";
Reid Spencer708585a2007-02-09 03:08:06 +0000122 llvm_shutdown();
123 exit(errcode);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000124}
125
Reid Spencer3b726392007-04-29 23:59:47 +0000126static void PrintCommand(const std::vector<const char*> &args) {
127 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
128 for (; I != E; ++I)
129 if (*I)
130 cout << "'" << *I << "'" << " ";
131 cout << "\n" << std::flush;
132}
133
Reid Spencer445564a2004-11-20 20:02:56 +0000134/// CopyEnv - This function takes an array of environment variables and makes a
135/// copy of it. This copy can then be manipulated any way the caller likes
136/// without affecting the process's real environment.
137///
138/// Inputs:
139/// envp - An array of C strings containing an environment.
140///
141/// Return value:
142/// NULL - An error occurred.
143///
144/// Otherwise, a pointer to a new array of C strings is returned. Every string
145/// in the array is a duplicate of the one in the original array (i.e. we do
146/// not copy the char *'s from one array to another).
147///
148static char ** CopyEnv(char ** const envp) {
149 // Count the number of entries in the old list;
150 unsigned entries; // The number of entries in the old environment list
151 for (entries = 0; envp[entries] != NULL; entries++)
152 /*empty*/;
153
154 // Add one more entry for the NULL pointer that ends the list.
155 ++entries;
156
157 // If there are no entries at all, just return NULL.
158 if (entries == 0)
159 return NULL;
160
161 // Allocate a new environment list.
162 char **newenv = new char* [entries];
163 if ((newenv = new char* [entries]) == NULL)
164 return NULL;
165
166 // Make a copy of the list. Don't forget the NULL that ends the list.
167 entries = 0;
168 while (envp[entries] != NULL) {
169 newenv[entries] = new char[strlen (envp[entries]) + 1];
170 strcpy (newenv[entries], envp[entries]);
171 ++entries;
172 }
173 newenv[entries] = NULL;
174
175 return newenv;
176}
177
178
179/// RemoveEnv - Remove the specified environment variable from the environment
180/// array.
181///
182/// Inputs:
183/// name - The name of the variable to remove. It cannot be NULL.
184/// envp - The array of environment variables. It cannot be NULL.
185///
186/// Notes:
187/// This is mainly done because functions to remove items from the environment
188/// are not available across all platforms. In particular, Solaris does not
189/// seem to have an unsetenv() function or a setenv() function (or they are
190/// undocumented if they do exist).
191///
192static void RemoveEnv(const char * name, char ** const envp) {
193 for (unsigned index=0; envp[index] != NULL; index++) {
194 // Find the first equals sign in the array and make it an EOS character.
195 char *p = strchr (envp[index], '=');
196 if (p == NULL)
197 continue;
198 else
199 *p = '\0';
200
201 // Compare the two strings. If they are equal, zap this string.
202 // Otherwise, restore it.
203 if (!strcmp(name, envp[index]))
204 *envp[index] = '\0';
205 else
206 *p = '=';
207 }
208
209 return;
210}
211
212/// GenerateBytecode - generates a bytecode file from the module provided
213void GenerateBytecode(Module* M, const std::string& FileName) {
214
Reid Spencer3b726392007-04-29 23:59:47 +0000215 if (Verbose)
216 cout << "Generating Bytecode To " << FileName << '\n';
217
Reid Spencer445564a2004-11-20 20:02:56 +0000218 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000219 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
220 std::ios::binary;
221 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer708585a2007-02-09 03:08:06 +0000222 if (!Out.good())
223 PrintAndExit("error opening '" + FileName + "' for writing!");
Reid Spencer445564a2004-11-20 20:02:56 +0000224
225 // Ensure that the bytecode file gets removed from the disk if we get a
226 // terminating signal.
227 sys::RemoveFileOnSignal(sys::Path(FileName));
228
229 // Write it out
Chris Lattnerbb3f3d32007-05-06 05:56:58 +0000230 if (Bitcode) {
231 WriteBitcodeToFile(M, Out);
232 } else {
233 OStream L(Out);
234 WriteBytecodeToFile(M, L, !DisableCompression);
235 }
Reid Spencer445564a2004-11-20 20:02:56 +0000236
237 // Close the bytecode file.
238 Out.close();
239}
240
241/// GenerateAssembly - generates a native assembly language source file from the
242/// specified bytecode file.
243///
244/// Inputs:
Devang Patele2f8ad82006-06-27 18:07:29 +0000245/// InputFilename - The name of the input bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000246/// OutputFilename - The name of the file to generate.
247/// llc - The pathname to use for LLC.
248/// envp - The environment to use when running LLC.
249///
250/// Return non-zero value on error.
251///
252static int GenerateAssembly(const std::string &OutputFilename,
253 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000254 const sys::Path &llc,
255 std::string &ErrMsg ) {
Reid Spencer445564a2004-11-20 20:02:56 +0000256 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000257 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000258 args.push_back(llc.c_str());
259 args.push_back("-f");
260 args.push_back("-o");
261 args.push_back(OutputFilename.c_str());
262 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000263 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000264
Reid Spencer3b726392007-04-29 23:59:47 +0000265 if (Verbose) {
266 cout << "Generating Assembly With: \n";
267 PrintCommand(args);
268 }
269
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000270 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000271}
272
Devang Patele2f8ad82006-06-27 18:07:29 +0000273/// GenerateCFile - generates a C source file from the specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000274static int GenerateCFile(const std::string &OutputFile,
275 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000276 const sys::Path &llc,
277 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000278 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000279 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000280 args.push_back(llc.c_str());
281 args.push_back("-march=c");
282 args.push_back("-f");
283 args.push_back("-o");
284 args.push_back(OutputFile.c_str());
285 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000286 args.push_back(0);
Reid Spencer3b726392007-04-29 23:59:47 +0000287
288 if (Verbose) {
289 cout << "Generating C Source With: \n";
290 PrintCommand(args);
291 }
292
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000293 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000294}
295
Devang Patele2f8ad82006-06-27 18:07:29 +0000296/// GenerateNative - generates a native object file from the
297/// specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000298///
299/// Inputs:
Reid Spencerc82a5da2007-04-04 06:34:22 +0000300/// InputFilename - The name of the input bytecode file.
301/// OutputFilename - The name of the file to generate.
302/// NativeLinkItems - The native libraries, files, code with which to link
303/// LibPaths - The list of directories in which to find libraries.
304/// gcc - The pathname to use for GGC.
305/// envp - A copy of the process's current environment.
Reid Spencer445564a2004-11-20 20:02:56 +0000306///
307/// Outputs:
308/// None.
309///
310/// Returns non-zero value on error.
311///
312static int GenerateNative(const std::string &OutputFilename,
313 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000314 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000315 const sys::Path &gcc, char ** const envp,
316 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000317 // Remove these environment variables from the environment of the
318 // programs that we will execute. It appears that GCC sets these
319 // environment variables so that the programs it uses can configure
320 // themselves identically.
321 //
322 // However, when we invoke GCC below, we want it to use its normal
323 // configuration. Hence, we must sanitize its environment.
324 char ** clean_env = CopyEnv(envp);
325 if (clean_env == NULL)
326 return 1;
327 RemoveEnv("LIBRARY_PATH", clean_env);
328 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
329 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
330 RemoveEnv("COMPILER_PATH", clean_env);
331 RemoveEnv("COLLECT_GCC", clean_env);
332
Reid Spencer445564a2004-11-20 20:02:56 +0000333
334 // Run GCC to assemble and link the program into native code.
335 //
336 // Note:
337 // We can't just assemble and link the file with the system assembler
338 // and linker because we don't know where to put the _start symbol.
339 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000340 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000341 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000342 args.push_back("-fno-strict-aliasing");
343 args.push_back("-O3");
344 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000345 args.push_back(OutputFilename.c_str());
346 args.push_back(InputFilename.c_str());
Reid Spencer445564a2004-11-20 20:02:56 +0000347
Reid Spenceraf303d52006-06-07 23:03:13 +0000348 // Add in the library paths
349 for (unsigned index = 0; index < LibPaths.size(); index++) {
350 args.push_back("-L");
351 args.push_back(LibPaths[index].c_str());
352 }
353
354 // Add the requested options
355 for (unsigned index = 0; index < XLinker.size(); index++) {
356 args.push_back(XLinker[index].c_str());
357 args.push_back(Libraries[index].c_str());
358 }
359
Reid Spencer445564a2004-11-20 20:02:56 +0000360 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000361 for (unsigned index = 0; index < LinkItems.size(); index++)
362 if (LinkItems[index].first != "crtend") {
363 if (LinkItems[index].second) {
Reid Spencer2803b4c2006-11-11 19:59:25 +0000364 std::string lib_name = "-l" + LinkItems[index].first;
365 args.push_back(lib_name.c_str());
Reid Spencer49521432006-11-11 11:54:25 +0000366 } else
Reid Spencer2803b4c2006-11-11 19:59:25 +0000367 args.push_back(LinkItems[index].first.c_str());
Reid Spencerf6358c72004-12-19 18:00:56 +0000368 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000369
Chris Lattner7456e3c2005-02-13 23:10:45 +0000370 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000371
Reid Spencer3b726392007-04-29 23:59:47 +0000372 if (Verbose) {
373 cout << "Generating Native Executable With:\n";
374 PrintCommand(args);
375 }
376
Reid Spencer445564a2004-11-20 20:02:56 +0000377 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000378 int R = sys::Program::ExecuteAndWait(
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000379 gcc, &args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000380 delete [] clean_env;
381 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000382}
383
Reid Spencerc0af3f02004-09-13 01:27:53 +0000384/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
385/// bytecode file for the program.
386static void EmitShellScript(char **argv) {
Reid Spencer3b726392007-04-29 23:59:47 +0000387 if (Verbose)
388 cout << "Emitting Shell Script\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000389#if defined(_WIN32) || defined(__CYGWIN__)
390 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
391 // support windows systems, we copy the llvm-stub.exe executable from the
392 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000393 std::string ErrMsg;
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000394 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
Reid Spencer708585a2007-02-09 03:08:06 +0000395 if (llvmstub.isEmpty())
396 PrintAndExit("Could not find llvm-stub.exe executable!");
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000397
Reid Spencer708585a2007-02-09 03:08:06 +0000398 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
399 PrintAndExit(ErrMsg);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000400
Reid Spencerc0af3f02004-09-13 01:27:53 +0000401 return;
402#endif
403
404 // Output the script to start the program...
405 std::ofstream Out2(OutputFilename.c_str());
406 if (!Out2.good())
Reid Spencer708585a2007-02-09 03:08:06 +0000407 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000408
409 Out2 << "#!/bin/sh\n";
410 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
411 Out2 << "lli=${LLVMINTERP-lli}\n";
412 Out2 << "exec $lli \\\n";
413 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
414 LibPaths.push_back("/lib");
415 LibPaths.push_back("/usr/lib");
416 LibPaths.push_back("/usr/X11R6/lib");
417 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
418 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000419 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000420 std::find(Libraries.begin(), Libraries.end(), "c");
421 if (libc != Libraries.end()) Libraries.erase(libc);
422 // List all the shared object (native) libraries this executable will need
423 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000424 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000425 e = Libraries.end(); i != e; ++i) {
Reid Spencerc4064132004-12-13 03:01:14 +0000426 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
427 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
428 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000429 }
430 Out2 << " $0.bc ${1+\"$@\"}\n";
431 Out2.close();
432}
433
Reid Spencerc4064132004-12-13 03:01:14 +0000434// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
435// linker function by combining the Files and Libraries in the order they were
436// declared on the command line.
437static void BuildLinkItems(
438 Linker::ItemList& Items,
439 const cl::list<std::string>& Files,
440 const cl::list<std::string>& Libraries) {
441
Misha Brukman3da94ae2005-04-22 00:00:37 +0000442 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000443
444 cl::list<std::string>::const_iterator fileIt = Files.begin();
445 cl::list<std::string>::const_iterator libIt = Libraries.begin();
446
447 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000448 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000449 if (libIt != Libraries.end())
450 libPos = Libraries.getPosition(libIt - Libraries.begin());
451 else
452 libPos = -1;
453 if (fileIt != Files.end())
454 filePos = Files.getPosition(fileIt - Files.begin());
455 else
456 filePos = -1;
457
458 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
459 // Add a source file
460 Items.push_back(std::make_pair(*fileIt++, false));
461 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
462 // Add a library
463 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000464 }
465 }
466}
467
Reid Spencer445564a2004-11-20 20:02:56 +0000468// Rightly this should go in a header file but it just seems such a waste.
469namespace llvm {
470extern void Optimize(Module*);
471}
472
Reid Spencerc0af3f02004-09-13 01:27:53 +0000473int main(int argc, char **argv, char **envp) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000474 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000475 try {
476 // Initial global variable above for convenience printing of program name.
477 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000478
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000479 // Parse the command line options
480 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
481 sys::PrintStackTraceOnErrorSignal();
Reid Spencerc0af3f02004-09-13 01:27:53 +0000482
Reid Spencer49521432006-11-11 11:54:25 +0000483 // Construct a Linker (now that Verbose is set)
484 Linker TheLinker(progname, OutputFilename, Verbose);
Reid Spencerc82a5da2007-04-04 06:34:22 +0000485
486 // Keep track of the native link items (versus the bytecode items)
487 Linker::ItemList NativeLinkItems;
Reid Spencer49521432006-11-11 11:54:25 +0000488
489 // Add library paths to the linker
Reid Spencer78df5c32006-03-06 06:38:19 +0000490 TheLinker.addPaths(LibPaths);
491 TheLinker.addSystemPaths();
492
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000493 // Remove any consecutive duplicates of the same library...
494 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
495 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000496
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000497 if (LinkAsLibrary) {
498 std::vector<sys::Path> Files;
499 for (unsigned i = 0; i < InputFilenames.size(); ++i )
500 Files.push_back(sys::Path(InputFilenames[i]));
501 if (TheLinker.LinkInFiles(Files))
502 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000503
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000504 // The libraries aren't linked in but are noted as "dependent" in the
505 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000506 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000507 E = Libraries.end(); I != E ; ++I) {
508 TheLinker.getModule()->addLibrary(*I);
509 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000510 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000511 // Build a list of the items from our command line
512 Linker::ItemList Items;
513 BuildLinkItems(Items, InputFilenames, Libraries);
514
515 // Link all the items together
Reid Spencerc82a5da2007-04-04 06:34:22 +0000516 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
Reid Spencer708585a2007-02-09 03:08:06 +0000517 return 1; // Error already printed
Reid Spencerc0af3f02004-09-13 01:27:53 +0000518 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000519
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000520 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
521
522 // Optimize the module
523 Optimize(Composite.get());
524
525 // Generate the bytecode for the optimized module.
526 std::string RealBytecodeOutput = OutputFilename;
527 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
528 GenerateBytecode(Composite.get(), RealBytecodeOutput);
529
530 // If we are not linking a library, generate either a native executable
531 // or a JIT shell script, depending upon what the user wants.
532 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000533 // If the user wants to run a post-link optimization, run it now.
534 if (!PostLinkOpts.empty()) {
535 std::vector<std::string> opts = PostLinkOpts;
536 for (std::vector<std::string>::iterator I = opts.begin(),
537 E = opts.end(); I != E; ++I) {
538 sys::Path prog(*I);
539 if (!prog.canExecute()) {
540 prog = sys::Program::FindProgramByName(*I);
541 if (prog.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000542 PrintAndExit(std::string("Optimization program '") + *I +
Reid Spencer73a74be2005-12-21 05:03:23 +0000543 "' is not found or not executable.");
544 }
545 // Get the program arguments
546 sys::Path tmp_output("opt_result");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000547 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000548 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
549 PrintAndExit(ErrMsg);
550
Reid Spencer73a74be2005-12-21 05:03:23 +0000551 const char* args[4];
552 args[0] = I->c_str();
553 args[1] = RealBytecodeOutput.c_str();
554 args[2] = tmp_output.c_str();
555 args[3] = 0;
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000556 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
Chris Lattnerbb3f3d32007-05-06 05:56:58 +0000557 if (tmp_output.isBytecodeFile() || tmp_output.isBitcodeFile()) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000558 sys::Path target(RealBytecodeOutput);
559 target.eraseFromDisk();
Reid Spencer708585a2007-02-09 03:08:06 +0000560 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
561 PrintAndExit(ErrMsg, 2);
Reid Spencer73a74be2005-12-21 05:03:23 +0000562 } else
Reid Spencer708585a2007-02-09 03:08:06 +0000563 PrintAndExit("Post-link optimization output is not bytecode");
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000564 } else {
Reid Spencer708585a2007-02-09 03:08:06 +0000565 PrintAndExit(ErrMsg);
Reid Spencer73a74be2005-12-21 05:03:23 +0000566 }
567 }
568 }
569
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000570 // If the user wants to generate a native executable, compile it from the
571 // bytecode file.
572 //
573 // Otherwise, create a script that will run the bytecode through the JIT.
574 if (Native) {
575 // Name of the Assembly Language output file
576 sys::Path AssemblyFile ( OutputFilename);
577 AssemblyFile.appendSuffix("s");
578
579 // Mark the output files for removal if we get an interrupt.
580 sys::RemoveFileOnSignal(AssemblyFile);
581 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
582
583 // Determine the locations of the llc and gcc programs.
584 sys::Path llc = FindExecutable("llc", argv[0]);
585 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000586 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000587
588 sys::Path gcc = FindExecutable("gcc", argv[0]);
589 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000590 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000591
592 // Generate an assembly language file for the bytecode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000593 std::string ErrMsg;
594 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
Reid Spencer708585a2007-02-09 03:08:06 +0000595 llc, ErrMsg))
596 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000597
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000598 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
Reid Spencerc82a5da2007-04-04 06:34:22 +0000599 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000600 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000601
602 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000603 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000604 } else if (NativeCBE) {
605 sys::Path CFile (OutputFilename);
606 CFile.appendSuffix("cbe.c");
607
608 // Mark the output files for removal if we get an interrupt.
609 sys::RemoveFileOnSignal(CFile);
610 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
611
612 // Determine the locations of the llc and gcc programs.
613 sys::Path llc = FindExecutable("llc", argv[0]);
614 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000615 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000616
617 sys::Path gcc = FindExecutable("gcc", argv[0]);
618 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000619 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000620
621 // Generate an assembly language file for the bytecode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000622 std::string ErrMsg;
623 if (0 != GenerateCFile(
Reid Spencer708585a2007-02-09 03:08:06 +0000624 CFile.toString(), RealBytecodeOutput, llc, ErrMsg))
625 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000626
Reid Spencerc82a5da2007-04-04 06:34:22 +0000627 if (0 != GenerateNative(OutputFilename, CFile.toString(),
628 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000629 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000630
631 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000632 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000633
634 } else {
635 EmitShellScript(argv);
636 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000637
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000638 // Make the script executable...
Reid Spencere1647f42006-08-22 23:27:23 +0000639 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000640 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
641 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000642
643 // Make the bytecode file readable and directly executable in LLEE as well
Reid Spencer708585a2007-02-09 03:08:06 +0000644 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg))
645 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000646
Reid Spencer708585a2007-02-09 03:08:06 +0000647 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg))
648 PrintAndExit(ErrMsg);
649 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000650 } catch (const std::string& msg) {
Reid Spencer708585a2007-02-09 03:08:06 +0000651 PrintAndExit(msg,2);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000652 } catch (...) {
Reid Spencer708585a2007-02-09 03:08:06 +0000653 PrintAndExit("Unexpected unknown exception occurred.", 2);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000654 }
Reid Spencer708585a2007-02-09 03:08:06 +0000655
656 // Graceful exit
657 return 0;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000658}