blob: 207f0cbb4f422a43db0cfd3d248df3a166e62be3 [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"
28#include "llvm/Bytecode/Reader.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"
Bill Wendling68fe61d2006-11-29 00:19:40 +000036#include "llvm/Support/Streams.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000037#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000038#include "llvm/System/Signals.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000039#include <fstream>
40#include <memory>
41using namespace llvm;
42
Reid Spencer445564a2004-11-20 20:02:56 +000043// Input/Output Options
44static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bytecode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000046
Reid Spencer445564a2004-11-20 20:02:56 +000047static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000048 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000049 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000050
Misha Brukman3da94ae2005-04-22 00:00:37 +000051static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000052 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000053
Reid Spencer445564a2004-11-20 20:02:56 +000054static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000055 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000056 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000057
Reid Spencer445564a2004-11-20 20:02:56 +000058static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000059 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000060 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000061
Reid Spencer708585a2007-02-09 03:08:06 +000062// Options to control the linking, optimization, and code gen processes
Misha Brukman3da94ae2005-04-22 00:00:37 +000063static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000064 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000065
Reid Spencer445564a2004-11-20 20:02:56 +000066static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
67 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000068
Reid Spencer445564a2004-11-20 20:02:56 +000069static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
Reid Spenceraefd04b2004-09-25 16:00:07 +000070 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
71
Reid Spencer445564a2004-11-20 20:02:56 +000072static cl::opt<bool> Native("native",
73 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000074
Reid Spencer445564a2004-11-20 20:02:56 +000075static cl::opt<bool>NativeCBE("native-cbe",
76 cl::desc("Generate a native binary with the C backend and GCC"));
77
Chris Lattner17be6792007-01-21 06:34:18 +000078static cl::opt<bool>DisableCompression("disable-compression", cl::init(true),
Reid Spencer445564a2004-11-20 20:02:56 +000079 cl::desc("Disable writing of compressed bytecode files"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000080
Reid Spencer73a74be2005-12-21 05:03:23 +000081static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000082 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000083 cl::desc("Run one or more optimization programs after linking"));
84
Reid Spenceraf303d52006-06-07 23:03:13 +000085static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
86 cl::desc("Pass options to the system linker"));
87
Reid Spencer708585a2007-02-09 03:08:06 +000088// Compatibility options that llvm-ld ignores but are supported for
89// compatibility with LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000090static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000091 cl::desc("Compatibility option: ignored"));
92
Misha Brukman3da94ae2005-04-22 00:00:37 +000093static cl::opt<std::string> CO4("version-script", 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<bool> CO5("eh-frame-hdr", 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<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000100 cl::desc("Compatibility option: ignored"));
101
Reid Spencer98a030c2007-02-08 19:03:11 +0000102static cl::opt<bool> CO7("start-group", cl::Hidden,
103 cl::desc("Compatibility option: ignored"));
104
105static cl::opt<bool> CO8("end-group", cl::Hidden,
106 cl::desc("Compatibility option: ignored"));
Reid Spenceraf303d52006-06-07 23:03:13 +0000107
Reid Spencer445564a2004-11-20 20:02:56 +0000108/// This is just for convenience so it doesn't have to be passed around
109/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000110static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000111
Reid Spencer708585a2007-02-09 03:08:06 +0000112/// PrintAndExit - Prints a message to standard error and exits with error code
Reid Spencerc0af3f02004-09-13 01:27:53 +0000113///
114/// Inputs:
Reid Spencerc0af3f02004-09-13 01:27:53 +0000115/// Message - The message to print to standard error.
116///
Reid Spencer708585a2007-02-09 03:08:06 +0000117static void PrintAndExit(const std::string &Message, int errcode = 1) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000118 cerr << progname << ": " << Message << "\n";
Reid Spencer708585a2007-02-09 03:08:06 +0000119 llvm_shutdown();
120 exit(errcode);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000121}
122
Reid Spencer445564a2004-11-20 20:02:56 +0000123/// CopyEnv - This function takes an array of environment variables and makes a
124/// copy of it. This copy can then be manipulated any way the caller likes
125/// without affecting the process's real environment.
126///
127/// Inputs:
128/// envp - An array of C strings containing an environment.
129///
130/// Return value:
131/// NULL - An error occurred.
132///
133/// Otherwise, a pointer to a new array of C strings is returned. Every string
134/// in the array is a duplicate of the one in the original array (i.e. we do
135/// not copy the char *'s from one array to another).
136///
137static char ** CopyEnv(char ** const envp) {
138 // Count the number of entries in the old list;
139 unsigned entries; // The number of entries in the old environment list
140 for (entries = 0; envp[entries] != NULL; entries++)
141 /*empty*/;
142
143 // Add one more entry for the NULL pointer that ends the list.
144 ++entries;
145
146 // If there are no entries at all, just return NULL.
147 if (entries == 0)
148 return NULL;
149
150 // Allocate a new environment list.
151 char **newenv = new char* [entries];
152 if ((newenv = new char* [entries]) == NULL)
153 return NULL;
154
155 // Make a copy of the list. Don't forget the NULL that ends the list.
156 entries = 0;
157 while (envp[entries] != NULL) {
158 newenv[entries] = new char[strlen (envp[entries]) + 1];
159 strcpy (newenv[entries], envp[entries]);
160 ++entries;
161 }
162 newenv[entries] = NULL;
163
164 return newenv;
165}
166
167
168/// RemoveEnv - Remove the specified environment variable from the environment
169/// array.
170///
171/// Inputs:
172/// name - The name of the variable to remove. It cannot be NULL.
173/// envp - The array of environment variables. It cannot be NULL.
174///
175/// Notes:
176/// This is mainly done because functions to remove items from the environment
177/// are not available across all platforms. In particular, Solaris does not
178/// seem to have an unsetenv() function or a setenv() function (or they are
179/// undocumented if they do exist).
180///
181static void RemoveEnv(const char * name, char ** const envp) {
182 for (unsigned index=0; envp[index] != NULL; index++) {
183 // Find the first equals sign in the array and make it an EOS character.
184 char *p = strchr (envp[index], '=');
185 if (p == NULL)
186 continue;
187 else
188 *p = '\0';
189
190 // Compare the two strings. If they are equal, zap this string.
191 // Otherwise, restore it.
192 if (!strcmp(name, envp[index]))
193 *envp[index] = '\0';
194 else
195 *p = '=';
196 }
197
198 return;
199}
200
201/// GenerateBytecode - generates a bytecode file from the module provided
202void GenerateBytecode(Module* M, const std::string& FileName) {
203
204 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000205 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
206 std::ios::binary;
207 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer708585a2007-02-09 03:08:06 +0000208 if (!Out.good())
209 PrintAndExit("error opening '" + FileName + "' for writing!");
Reid Spencer445564a2004-11-20 20:02:56 +0000210
211 // Ensure that the bytecode file gets removed from the disk if we get a
212 // terminating signal.
213 sys::RemoveFileOnSignal(sys::Path(FileName));
214
215 // Write it out
Bill Wendlinge8156192006-12-07 01:30:32 +0000216 OStream L(Out);
Bill Wendling68fe61d2006-11-29 00:19:40 +0000217 WriteBytecodeToFile(M, L, !DisableCompression);
Reid Spencer445564a2004-11-20 20:02:56 +0000218
219 // Close the bytecode file.
220 Out.close();
221}
222
223/// GenerateAssembly - generates a native assembly language source file from the
224/// specified bytecode file.
225///
226/// Inputs:
Devang Patele2f8ad82006-06-27 18:07:29 +0000227/// InputFilename - The name of the input bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000228/// OutputFilename - The name of the file to generate.
229/// llc - The pathname to use for LLC.
230/// envp - The environment to use when running LLC.
231///
232/// Return non-zero value on error.
233///
234static int GenerateAssembly(const std::string &OutputFilename,
235 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000236 const sys::Path &llc,
237 std::string &ErrMsg ) {
Reid Spencer445564a2004-11-20 20:02:56 +0000238 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000239 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000240 args.push_back(llc.c_str());
241 args.push_back("-f");
242 args.push_back("-o");
243 args.push_back(OutputFilename.c_str());
244 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000245 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000246
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000247 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000248}
249
Devang Patele2f8ad82006-06-27 18:07:29 +0000250/// GenerateCFile - generates a C source file from the specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000251static int GenerateCFile(const std::string &OutputFile,
252 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000253 const sys::Path &llc,
254 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000255 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000256 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000257 args.push_back(llc.c_str());
258 args.push_back("-march=c");
259 args.push_back("-f");
260 args.push_back("-o");
261 args.push_back(OutputFile.c_str());
262 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000263 args.push_back(0);
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000264 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000265}
266
Devang Patele2f8ad82006-06-27 18:07:29 +0000267/// GenerateNative - generates a native object file from the
268/// specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000269///
270/// Inputs:
Devang Patele2f8ad82006-06-27 18:07:29 +0000271/// InputFilename - The name of the input bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000272/// OutputFilename - The name of the file to generate.
Reid Spencer49521432006-11-11 11:54:25 +0000273/// LinkItems - The native libraries, files, code with which to link
Reid Spencer445564a2004-11-20 20:02:56 +0000274/// LibPaths - The list of directories in which to find libraries.
275/// gcc - The pathname to use for GGC.
276/// envp - A copy of the process's current environment.
277///
278/// Outputs:
279/// None.
280///
281/// Returns non-zero value on error.
282///
283static int GenerateNative(const std::string &OutputFilename,
284 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000285 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000286 const sys::Path &gcc, char ** const envp,
287 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000288 // Remove these environment variables from the environment of the
289 // programs that we will execute. It appears that GCC sets these
290 // environment variables so that the programs it uses can configure
291 // themselves identically.
292 //
293 // However, when we invoke GCC below, we want it to use its normal
294 // configuration. Hence, we must sanitize its environment.
295 char ** clean_env = CopyEnv(envp);
296 if (clean_env == NULL)
297 return 1;
298 RemoveEnv("LIBRARY_PATH", clean_env);
299 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
300 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
301 RemoveEnv("COMPILER_PATH", clean_env);
302 RemoveEnv("COLLECT_GCC", clean_env);
303
Reid Spencer445564a2004-11-20 20:02:56 +0000304
305 // Run GCC to assemble and link the program into native code.
306 //
307 // Note:
308 // We can't just assemble and link the file with the system assembler
309 // and linker because we don't know where to put the _start symbol.
310 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000311 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000312 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000313 args.push_back("-fno-strict-aliasing");
314 args.push_back("-O3");
315 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000316 args.push_back(OutputFilename.c_str());
317 args.push_back(InputFilename.c_str());
Reid Spencer445564a2004-11-20 20:02:56 +0000318
Reid Spenceraf303d52006-06-07 23:03:13 +0000319 // Add in the library paths
320 for (unsigned index = 0; index < LibPaths.size(); index++) {
321 args.push_back("-L");
322 args.push_back(LibPaths[index].c_str());
323 }
324
325 // Add the requested options
326 for (unsigned index = 0; index < XLinker.size(); index++) {
327 args.push_back(XLinker[index].c_str());
328 args.push_back(Libraries[index].c_str());
329 }
330
Reid Spencer445564a2004-11-20 20:02:56 +0000331 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000332 for (unsigned index = 0; index < LinkItems.size(); index++)
333 if (LinkItems[index].first != "crtend") {
334 if (LinkItems[index].second) {
Reid Spencer2803b4c2006-11-11 19:59:25 +0000335 std::string lib_name = "-l" + LinkItems[index].first;
336 args.push_back(lib_name.c_str());
Reid Spencer49521432006-11-11 11:54:25 +0000337 } else
Reid Spencer2803b4c2006-11-11 19:59:25 +0000338 args.push_back(LinkItems[index].first.c_str());
Reid Spencerf6358c72004-12-19 18:00:56 +0000339 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000340
Chris Lattner7456e3c2005-02-13 23:10:45 +0000341 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000342
343 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000344 int R = sys::Program::ExecuteAndWait(
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000345 gcc, &args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000346 delete [] clean_env;
347 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000348}
349
Reid Spencerc0af3f02004-09-13 01:27:53 +0000350/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
351/// bytecode file for the program.
352static void EmitShellScript(char **argv) {
353#if defined(_WIN32) || defined(__CYGWIN__)
354 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
355 // support windows systems, we copy the llvm-stub.exe executable from the
356 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000357 std::string ErrMsg;
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000358 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
Reid Spencer708585a2007-02-09 03:08:06 +0000359 if (llvmstub.isEmpty())
360 PrintAndExit("Could not find llvm-stub.exe executable!");
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000361
Reid Spencer708585a2007-02-09 03:08:06 +0000362 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
363 PrintAndExit(ErrMsg);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000364
Reid Spencerc0af3f02004-09-13 01:27:53 +0000365 return;
366#endif
367
368 // Output the script to start the program...
369 std::ofstream Out2(OutputFilename.c_str());
370 if (!Out2.good())
Reid Spencer708585a2007-02-09 03:08:06 +0000371 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000372
373 Out2 << "#!/bin/sh\n";
374 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
375 Out2 << "lli=${LLVMINTERP-lli}\n";
376 Out2 << "exec $lli \\\n";
377 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
378 LibPaths.push_back("/lib");
379 LibPaths.push_back("/usr/lib");
380 LibPaths.push_back("/usr/X11R6/lib");
381 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
382 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000383 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000384 std::find(Libraries.begin(), Libraries.end(), "c");
385 if (libc != Libraries.end()) Libraries.erase(libc);
386 // List all the shared object (native) libraries this executable will need
387 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000388 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000389 e = Libraries.end(); i != e; ++i) {
Reid Spencerc4064132004-12-13 03:01:14 +0000390 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
391 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
392 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000393 }
394 Out2 << " $0.bc ${1+\"$@\"}\n";
395 Out2.close();
396}
397
Reid Spencerc4064132004-12-13 03:01:14 +0000398// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
399// linker function by combining the Files and Libraries in the order they were
400// declared on the command line.
401static void BuildLinkItems(
402 Linker::ItemList& Items,
403 const cl::list<std::string>& Files,
404 const cl::list<std::string>& Libraries) {
405
Misha Brukman3da94ae2005-04-22 00:00:37 +0000406 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000407
408 cl::list<std::string>::const_iterator fileIt = Files.begin();
409 cl::list<std::string>::const_iterator libIt = Libraries.begin();
410
411 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000412 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000413 if (libIt != Libraries.end())
414 libPos = Libraries.getPosition(libIt - Libraries.begin());
415 else
416 libPos = -1;
417 if (fileIt != Files.end())
418 filePos = Files.getPosition(fileIt - Files.begin());
419 else
420 filePos = -1;
421
422 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
423 // Add a source file
424 Items.push_back(std::make_pair(*fileIt++, false));
425 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
426 // Add a library
427 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000428 }
429 }
430}
431
Reid Spencer445564a2004-11-20 20:02:56 +0000432// Rightly this should go in a header file but it just seems such a waste.
433namespace llvm {
434extern void Optimize(Module*);
435}
436
Reid Spencerc0af3f02004-09-13 01:27:53 +0000437int main(int argc, char **argv, char **envp) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000438 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000439 try {
440 // Initial global variable above for convenience printing of program name.
441 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000442
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000443 // Parse the command line options
444 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
445 sys::PrintStackTraceOnErrorSignal();
Reid Spencerc0af3f02004-09-13 01:27:53 +0000446
Reid Spencer49521432006-11-11 11:54:25 +0000447 // Construct a Linker (now that Verbose is set)
448 Linker TheLinker(progname, OutputFilename, Verbose);
449 // Keep track of the native link items (vice the bytecode items)
450 Linker::ItemList LinkItems;
451
452 // Add library paths to the linker
Reid Spencer78df5c32006-03-06 06:38:19 +0000453 TheLinker.addPaths(LibPaths);
454 TheLinker.addSystemPaths();
455
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000456 // Remove any consecutive duplicates of the same library...
457 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
458 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000459
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000460 if (LinkAsLibrary) {
461 std::vector<sys::Path> Files;
462 for (unsigned i = 0; i < InputFilenames.size(); ++i )
463 Files.push_back(sys::Path(InputFilenames[i]));
464 if (TheLinker.LinkInFiles(Files))
465 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000466
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000467 // The libraries aren't linked in but are noted as "dependent" in the
468 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000469 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000470 E = Libraries.end(); I != E ; ++I) {
471 TheLinker.getModule()->addLibrary(*I);
472 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000473 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000474 // Build a list of the items from our command line
475 Linker::ItemList Items;
476 BuildLinkItems(Items, InputFilenames, Libraries);
477
478 // Link all the items together
Reid Spencer49521432006-11-11 11:54:25 +0000479 if (TheLinker.LinkInItems(Items,LinkItems) )
Reid Spencer708585a2007-02-09 03:08:06 +0000480 return 1; // Error already printed
Reid Spencerc0af3f02004-09-13 01:27:53 +0000481 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000482
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000483 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
484
485 // Optimize the module
486 Optimize(Composite.get());
487
488 // Generate the bytecode for the optimized module.
489 std::string RealBytecodeOutput = OutputFilename;
490 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
491 GenerateBytecode(Composite.get(), RealBytecodeOutput);
492
493 // If we are not linking a library, generate either a native executable
494 // or a JIT shell script, depending upon what the user wants.
495 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000496 // If the user wants to run a post-link optimization, run it now.
497 if (!PostLinkOpts.empty()) {
498 std::vector<std::string> opts = PostLinkOpts;
499 for (std::vector<std::string>::iterator I = opts.begin(),
500 E = opts.end(); I != E; ++I) {
501 sys::Path prog(*I);
502 if (!prog.canExecute()) {
503 prog = sys::Program::FindProgramByName(*I);
504 if (prog.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000505 PrintAndExit(std::string("Optimization program '") + *I +
Reid Spencer73a74be2005-12-21 05:03:23 +0000506 "' is not found or not executable.");
507 }
508 // Get the program arguments
509 sys::Path tmp_output("opt_result");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000510 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000511 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
512 PrintAndExit(ErrMsg);
513
Reid Spencer73a74be2005-12-21 05:03:23 +0000514 const char* args[4];
515 args[0] = I->c_str();
516 args[1] = RealBytecodeOutput.c_str();
517 args[2] = tmp_output.c_str();
518 args[3] = 0;
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000519 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000520 if (tmp_output.isBytecodeFile()) {
521 sys::Path target(RealBytecodeOutput);
522 target.eraseFromDisk();
Reid Spencer708585a2007-02-09 03:08:06 +0000523 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
524 PrintAndExit(ErrMsg, 2);
Reid Spencer73a74be2005-12-21 05:03:23 +0000525 } else
Reid Spencer708585a2007-02-09 03:08:06 +0000526 PrintAndExit("Post-link optimization output is not bytecode");
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000527 } else {
Reid Spencer708585a2007-02-09 03:08:06 +0000528 PrintAndExit(ErrMsg);
Reid Spencer73a74be2005-12-21 05:03:23 +0000529 }
530 }
531 }
532
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000533 // If the user wants to generate a native executable, compile it from the
534 // bytecode file.
535 //
536 // Otherwise, create a script that will run the bytecode through the JIT.
537 if (Native) {
538 // Name of the Assembly Language output file
539 sys::Path AssemblyFile ( OutputFilename);
540 AssemblyFile.appendSuffix("s");
541
542 // Mark the output files for removal if we get an interrupt.
543 sys::RemoveFileOnSignal(AssemblyFile);
544 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
545
546 // Determine the locations of the llc and gcc programs.
547 sys::Path llc = FindExecutable("llc", argv[0]);
548 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000549 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000550
551 sys::Path gcc = FindExecutable("gcc", argv[0]);
552 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000553 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000554
555 // Generate an assembly language file for the bytecode.
Reid Spencer708585a2007-02-09 03:08:06 +0000556 if (Verbose)
557 cout << "Generating Assembly Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000558 std::string ErrMsg;
559 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
Reid Spencer708585a2007-02-09 03:08:06 +0000560 llc, ErrMsg))
561 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000562
Reid Spencer708585a2007-02-09 03:08:06 +0000563 if (Verbose)
564 cout << "Generating Native Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000565 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
Reid Spencer708585a2007-02-09 03:08:06 +0000566 LinkItems,gcc,envp,ErrMsg))
567 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000568
569 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000570 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000571 } else if (NativeCBE) {
572 sys::Path CFile (OutputFilename);
573 CFile.appendSuffix("cbe.c");
574
575 // Mark the output files for removal if we get an interrupt.
576 sys::RemoveFileOnSignal(CFile);
577 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
578
579 // Determine the locations of the llc and gcc programs.
580 sys::Path llc = FindExecutable("llc", argv[0]);
581 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000582 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000583
584 sys::Path gcc = FindExecutable("gcc", argv[0]);
585 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000586 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000587
588 // Generate an assembly language file for the bytecode.
Reid Spencer708585a2007-02-09 03:08:06 +0000589 if (Verbose)
590 cout << "Generating Assembly Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000591 std::string ErrMsg;
592 if (0 != GenerateCFile(
Reid Spencer708585a2007-02-09 03:08:06 +0000593 CFile.toString(), RealBytecodeOutput, llc, ErrMsg))
594 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000595
Reid Spencer708585a2007-02-09 03:08:06 +0000596 if (Verbose)
597 cout << "Generating Native Code\n";
Reid Spencer49521432006-11-11 11:54:25 +0000598 if (0 != GenerateNative(OutputFilename, CFile.toString(), LinkItems,
Reid Spencer708585a2007-02-09 03:08:06 +0000599 gcc, envp, ErrMsg))
600 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000601
602 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000603 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000604
605 } else {
606 EmitShellScript(argv);
607 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000608
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000609 // Make the script executable...
Reid Spencere1647f42006-08-22 23:27:23 +0000610 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000611 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
612 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000613
614 // Make the bytecode file readable and directly executable in LLEE as well
Reid Spencer708585a2007-02-09 03:08:06 +0000615 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg))
616 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000617
Reid Spencer708585a2007-02-09 03:08:06 +0000618 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg))
619 PrintAndExit(ErrMsg);
620 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000621 } catch (const std::string& msg) {
Reid Spencer708585a2007-02-09 03:08:06 +0000622 PrintAndExit(msg,2);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000623 } catch (...) {
Reid Spencer708585a2007-02-09 03:08:06 +0000624 PrintAndExit("Unexpected unknown exception occurred.", 2);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000625 }
Reid Spencer708585a2007-02-09 03:08:06 +0000626
627 // Graceful exit
628 return 0;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000629}