blob: 2b9d2550dc2af2b2db30b514decc06176a812bba [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//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gabor Greifa99be512007-07-05 17:07:56 +000014// example), is directly executable, whereas the bitcode file actually lives in
Reid Spencerc0af3f02004-09-13 01:27:53 +000015// 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"
Owen Anderson8b477ed2009-07-01 16:58:40 +000025#include "llvm/LLVMContext.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000026#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000027#include "llvm/Module.h"
28#include "llvm/PassManager.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000029#include "llvm/Bitcode/ReaderWriter.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"
Chris Lattnercc14d252009-03-06 05:34:10 +000037#include "llvm/Support/PrettyStackTrace.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000038#include "llvm/Support/Streams.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000039#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000040#include "llvm/System/Signals.h"
Chris Lattner5d5a8972009-01-05 19:01:32 +000041#include "llvm/Config/config.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000042#include <fstream>
43#include <memory>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000044#include <cstring>
Reid Spencerc0af3f02004-09-13 01:27:53 +000045using namespace llvm;
46
Reid Spencer445564a2004-11-20 20:02:56 +000047// Input/Output Options
48static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
Gabor Greifa99be512007-07-05 17:07:56 +000049 cl::desc("<input bitcode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000050
Reid Spencer445564a2004-11-20 20:02:56 +000051static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000052 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000053 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000054
Misha Brukman3da94ae2005-04-22 00:00:37 +000055static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000056 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000057
Reid Spencer445564a2004-11-20 20:02:56 +000058static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000059 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000060 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000061
Chris Lattner3992f522008-01-27 22:58:59 +000062static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
63 cl::desc("Specify a framework search path"),
64 cl::value_desc("directory"));
65
Reid Spencer445564a2004-11-20 20:02:56 +000066static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000067 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000068 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000069
Chris Lattner3992f522008-01-27 22:58:59 +000070static cl::list<std::string> Frameworks("framework",
71 cl::desc("Specify frameworks to link to"),
72 cl::value_desc("framework"));
73
Reid Spencer708585a2007-02-09 03:08:06 +000074// Options to control the linking, optimization, and code gen processes
Misha Brukman3da94ae2005-04-22 00:00:37 +000075static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000076 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000077
Reid Spencer445564a2004-11-20 20:02:56 +000078static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
79 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000080
Reid Spencer445564a2004-11-20 20:02:56 +000081static cl::opt<bool> Native("native",
82 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000083
Reid Spencer445564a2004-11-20 20:02:56 +000084static cl::opt<bool>NativeCBE("native-cbe",
85 cl::desc("Generate a native binary with the C backend and GCC"));
86
Reid Spencer73a74be2005-12-21 05:03:23 +000087static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000088 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000089 cl::desc("Run one or more optimization programs after linking"));
90
Reid Spenceraf303d52006-06-07 23:03:13 +000091static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
92 cl::desc("Pass options to the system linker"));
93
Reid Spencer708585a2007-02-09 03:08:06 +000094// Compatibility options that llvm-ld ignores but are supported for
95// compatibility with LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000096static cl::opt<std::string> CO3("soname", 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> CO4("version-script", 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<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000103 cl::desc("Compatibility option: ignored"));
104
Misha Brukman3da94ae2005-04-22 00:00:37 +0000105static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000106 cl::desc("Compatibility option: ignored"));
107
Reid Spencer98a030c2007-02-08 19:03:11 +0000108static cl::opt<bool> CO7("start-group", cl::Hidden,
109 cl::desc("Compatibility option: ignored"));
110
111static cl::opt<bool> CO8("end-group", cl::Hidden,
112 cl::desc("Compatibility option: ignored"));
Reid Spenceraf303d52006-06-07 23:03:13 +0000113
Andrew Lenharth0c6ba442008-11-19 17:00:08 +0000114static cl::opt<std::string> CO9("m", cl::Hidden,
115 cl::desc("Compatibility option: ignored"));
116
Reid Spencer445564a2004-11-20 20:02:56 +0000117/// This is just for convenience so it doesn't have to be passed around
118/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000119static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000120
Reid Spencer708585a2007-02-09 03:08:06 +0000121/// PrintAndExit - Prints a message to standard error and exits with error code
Reid Spencerc0af3f02004-09-13 01:27:53 +0000122///
123/// Inputs:
Reid Spencerc0af3f02004-09-13 01:27:53 +0000124/// Message - The message to print to standard error.
125///
Reid Spencer708585a2007-02-09 03:08:06 +0000126static void PrintAndExit(const std::string &Message, int errcode = 1) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000127 cerr << progname << ": " << Message << "\n";
Reid Spencer708585a2007-02-09 03:08:06 +0000128 llvm_shutdown();
129 exit(errcode);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000130}
131
Reid Spencer3b726392007-04-29 23:59:47 +0000132static void PrintCommand(const std::vector<const char*> &args) {
133 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
134 for (; I != E; ++I)
135 if (*I)
136 cout << "'" << *I << "'" << " ";
137 cout << "\n" << std::flush;
138}
139
Reid Spencer445564a2004-11-20 20:02:56 +0000140/// CopyEnv - This function takes an array of environment variables and makes a
141/// copy of it. This copy can then be manipulated any way the caller likes
142/// without affecting the process's real environment.
143///
144/// Inputs:
145/// envp - An array of C strings containing an environment.
146///
147/// Return value:
148/// NULL - An error occurred.
149///
150/// Otherwise, a pointer to a new array of C strings is returned. Every string
151/// in the array is a duplicate of the one in the original array (i.e. we do
152/// not copy the char *'s from one array to another).
153///
154static char ** CopyEnv(char ** const envp) {
155 // Count the number of entries in the old list;
156 unsigned entries; // The number of entries in the old environment list
157 for (entries = 0; envp[entries] != NULL; entries++)
158 /*empty*/;
159
160 // Add one more entry for the NULL pointer that ends the list.
161 ++entries;
162
163 // If there are no entries at all, just return NULL.
164 if (entries == 0)
165 return NULL;
166
167 // Allocate a new environment list.
168 char **newenv = new char* [entries];
169 if ((newenv = new char* [entries]) == NULL)
170 return NULL;
171
172 // Make a copy of the list. Don't forget the NULL that ends the list.
173 entries = 0;
174 while (envp[entries] != NULL) {
175 newenv[entries] = new char[strlen (envp[entries]) + 1];
176 strcpy (newenv[entries], envp[entries]);
177 ++entries;
178 }
179 newenv[entries] = NULL;
180
181 return newenv;
182}
183
184
185/// RemoveEnv - Remove the specified environment variable from the environment
186/// array.
187///
188/// Inputs:
189/// name - The name of the variable to remove. It cannot be NULL.
190/// envp - The array of environment variables. It cannot be NULL.
191///
192/// Notes:
193/// This is mainly done because functions to remove items from the environment
194/// are not available across all platforms. In particular, Solaris does not
195/// seem to have an unsetenv() function or a setenv() function (or they are
196/// undocumented if they do exist).
197///
198static void RemoveEnv(const char * name, char ** const envp) {
199 for (unsigned index=0; envp[index] != NULL; index++) {
200 // Find the first equals sign in the array and make it an EOS character.
201 char *p = strchr (envp[index], '=');
202 if (p == NULL)
203 continue;
204 else
205 *p = '\0';
206
207 // Compare the two strings. If they are equal, zap this string.
208 // Otherwise, restore it.
209 if (!strcmp(name, envp[index]))
210 *envp[index] = '\0';
211 else
212 *p = '=';
213 }
214
215 return;
216}
217
Gabor Greifa99be512007-07-05 17:07:56 +0000218/// GenerateBitcode - generates a bitcode file from the module provided
219void GenerateBitcode(Module* M, const std::string& FileName) {
Reid Spencer445564a2004-11-20 20:02:56 +0000220
Reid Spencer3b726392007-04-29 23:59:47 +0000221 if (Verbose)
Gabor Greifa99be512007-07-05 17:07:56 +0000222 cout << "Generating Bitcode To " << FileName << '\n';
Reid Spencer3b726392007-04-29 23:59:47 +0000223
Reid Spencer445564a2004-11-20 20:02:56 +0000224 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000225 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
226 std::ios::binary;
227 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer708585a2007-02-09 03:08:06 +0000228 if (!Out.good())
229 PrintAndExit("error opening '" + FileName + "' for writing!");
Reid Spencer445564a2004-11-20 20:02:56 +0000230
Gabor Greifa99be512007-07-05 17:07:56 +0000231 // Ensure that the bitcode file gets removed from the disk if we get a
Reid Spencer445564a2004-11-20 20:02:56 +0000232 // terminating signal.
233 sys::RemoveFileOnSignal(sys::Path(FileName));
234
235 // Write it out
Chris Lattner44dadff2007-05-06 09:29:57 +0000236 WriteBitcodeToFile(M, Out);
Reid Spencer445564a2004-11-20 20:02:56 +0000237
Gabor Greifa99be512007-07-05 17:07:56 +0000238 // Close the bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000239 Out.close();
240}
241
242/// GenerateAssembly - generates a native assembly language source file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000243/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000244///
245/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000246/// InputFilename - The name of the input bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000247/// OutputFilename - The name of the file to generate.
248/// llc - The pathname to use for LLC.
249/// envp - The environment to use when running LLC.
250///
251/// Return non-zero value on error.
252///
253static int GenerateAssembly(const std::string &OutputFilename,
254 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000255 const sys::Path &llc,
256 std::string &ErrMsg ) {
Gabor Greifa99be512007-07-05 17:07:56 +0000257 // Run LLC to convert the bitcode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000258 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000259 args.push_back(llc.c_str());
Argyrios Kyrtzidisca29dff2008-06-27 15:08:59 +0000260 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
261 // regardless of what the target in the bitcode file is.
262 args.push_back("-x86-asm-syntax=att");
Chris Lattnerbf9add42005-04-10 20:59:38 +0000263 args.push_back("-f");
264 args.push_back("-o");
265 args.push_back(OutputFilename.c_str());
266 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000267 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000268
Reid Spencer3b726392007-04-29 23:59:47 +0000269 if (Verbose) {
270 cout << "Generating Assembly With: \n";
271 PrintCommand(args);
272 }
273
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000274 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000275}
276
Gabor Greifa99be512007-07-05 17:07:56 +0000277/// GenerateCFile - generates a C source file from the specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000278static int GenerateCFile(const std::string &OutputFile,
279 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000280 const sys::Path &llc,
281 std::string& ErrMsg) {
Gabor Greifa99be512007-07-05 17:07:56 +0000282 // Run LLC to convert the bitcode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000283 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000284 args.push_back(llc.c_str());
285 args.push_back("-march=c");
286 args.push_back("-f");
287 args.push_back("-o");
288 args.push_back(OutputFile.c_str());
289 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000290 args.push_back(0);
Reid Spencer3b726392007-04-29 23:59:47 +0000291
292 if (Verbose) {
293 cout << "Generating C Source With: \n";
294 PrintCommand(args);
295 }
296
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000297 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000298}
299
Devang Patele2f8ad82006-06-27 18:07:29 +0000300/// GenerateNative - generates a native object file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000301/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000302///
303/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000304/// InputFilename - The name of the input bitcode file.
Reid Spencerc82a5da2007-04-04 06:34:22 +0000305/// OutputFilename - The name of the file to generate.
306/// NativeLinkItems - The native libraries, files, code with which to link
307/// LibPaths - The list of directories in which to find libraries.
Chris Lattner3992f522008-01-27 22:58:59 +0000308/// FrameworksPaths - The list of directories in which to find frameworks.
309/// Frameworks - The list of frameworks (dynamic libraries)
Reid Spencerc82a5da2007-04-04 06:34:22 +0000310/// gcc - The pathname to use for GGC.
311/// envp - A copy of the process's current environment.
Reid Spencer445564a2004-11-20 20:02:56 +0000312///
313/// Outputs:
314/// None.
315///
316/// Returns non-zero value on error.
317///
318static int GenerateNative(const std::string &OutputFilename,
319 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000320 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000321 const sys::Path &gcc, char ** const envp,
322 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000323 // Remove these environment variables from the environment of the
324 // programs that we will execute. It appears that GCC sets these
325 // environment variables so that the programs it uses can configure
326 // themselves identically.
327 //
328 // However, when we invoke GCC below, we want it to use its normal
329 // configuration. Hence, we must sanitize its environment.
330 char ** clean_env = CopyEnv(envp);
331 if (clean_env == NULL)
332 return 1;
333 RemoveEnv("LIBRARY_PATH", clean_env);
334 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
335 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
336 RemoveEnv("COMPILER_PATH", clean_env);
337 RemoveEnv("COLLECT_GCC", clean_env);
338
Reid Spencer445564a2004-11-20 20:02:56 +0000339
340 // Run GCC to assemble and link the program into native code.
341 //
342 // Note:
343 // We can't just assemble and link the file with the system assembler
344 // and linker because we don't know where to put the _start symbol.
345 // GCC mysteriously knows how to do it.
Chris Lattner3f931b82007-06-19 16:46:48 +0000346 std::vector<std::string> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000347 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000348 args.push_back("-fno-strict-aliasing");
349 args.push_back("-O3");
350 args.push_back("-o");
Chris Lattner3f931b82007-06-19 16:46:48 +0000351 args.push_back(OutputFilename);
352 args.push_back(InputFilename);
Reid Spencer445564a2004-11-20 20:02:56 +0000353
Chris Lattner3992f522008-01-27 22:58:59 +0000354 // Add in the library and framework paths
Reid Spenceraf303d52006-06-07 23:03:13 +0000355 for (unsigned index = 0; index < LibPaths.size(); index++) {
Chris Lattner3992f522008-01-27 22:58:59 +0000356 args.push_back("-L" + LibPaths[index]);
357 }
358 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
359 args.push_back("-F" + FrameworkPaths[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000360 }
361
362 // Add the requested options
Chris Lattner03a1c7a2008-01-09 01:01:17 +0000363 for (unsigned index = 0; index < XLinker.size(); index++)
Chris Lattner3f931b82007-06-19 16:46:48 +0000364 args.push_back(XLinker[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000365
Reid Spencer445564a2004-11-20 20:02:56 +0000366 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000367 for (unsigned index = 0; index < LinkItems.size(); index++)
368 if (LinkItems[index].first != "crtend") {
Chris Lattner3f931b82007-06-19 16:46:48 +0000369 if (LinkItems[index].second)
370 args.push_back("-l" + LinkItems[index].first);
371 else
372 args.push_back(LinkItems[index].first);
Reid Spencerf6358c72004-12-19 18:00:56 +0000373 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000374
Chris Lattner3992f522008-01-27 22:58:59 +0000375 // Add in frameworks to link.
376 for (unsigned index = 0; index < Frameworks.size(); index++) {
377 args.push_back("-framework");
378 args.push_back(Frameworks[index]);
379 }
Chris Lattner3f931b82007-06-19 16:46:48 +0000380
381 // Now that "args" owns all the std::strings for the arguments, call the c_str
382 // method to get the underlying string array. We do this game so that the
383 // std::string array is guaranteed to outlive the const char* array.
384 std::vector<const char *> Args;
385 for (unsigned i = 0, e = args.size(); i != e; ++i)
386 Args.push_back(args[i].c_str());
387 Args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000388
Reid Spencer3b726392007-04-29 23:59:47 +0000389 if (Verbose) {
390 cout << "Generating Native Executable With:\n";
Chris Lattner3f931b82007-06-19 16:46:48 +0000391 PrintCommand(Args);
Reid Spencer3b726392007-04-29 23:59:47 +0000392 }
393
Reid Spencer445564a2004-11-20 20:02:56 +0000394 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000395 int R = sys::Program::ExecuteAndWait(
Chris Lattner3f931b82007-06-19 16:46:48 +0000396 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000397 delete [] clean_env;
398 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000399}
400
Reid Spencerc0af3f02004-09-13 01:27:53 +0000401/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
Gabor Greifa99be512007-07-05 17:07:56 +0000402/// bitcode file for the program.
Reid Spencerc0af3f02004-09-13 01:27:53 +0000403static void EmitShellScript(char **argv) {
Reid Spencer3b726392007-04-29 23:59:47 +0000404 if (Verbose)
405 cout << "Emitting Shell Script\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000406#if defined(_WIN32) || defined(__CYGWIN__)
407 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
408 // support windows systems, we copy the llvm-stub.exe executable from the
409 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000410 std::string ErrMsg;
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000411 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
Reid Spencer708585a2007-02-09 03:08:06 +0000412 if (llvmstub.isEmpty())
413 PrintAndExit("Could not find llvm-stub.exe executable!");
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000414
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000415 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000416 PrintAndExit(ErrMsg);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000417
Reid Spencerc0af3f02004-09-13 01:27:53 +0000418 return;
419#endif
420
421 // Output the script to start the program...
422 std::ofstream Out2(OutputFilename.c_str());
423 if (!Out2.good())
Reid Spencer708585a2007-02-09 03:08:06 +0000424 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000425
426 Out2 << "#!/bin/sh\n";
427 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
428 Out2 << "lli=${LLVMINTERP-lli}\n";
429 Out2 << "exec $lli \\\n";
430 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
431 LibPaths.push_back("/lib");
432 LibPaths.push_back("/usr/lib");
433 LibPaths.push_back("/usr/X11R6/lib");
434 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
435 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000436 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000437 std::find(Libraries.begin(), Libraries.end(), "c");
438 if (libc != Libraries.end()) Libraries.erase(libc);
439 // List all the shared object (native) libraries this executable will need
440 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000441 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000442 e = Libraries.end(); i != e; ++i) {
Chris Lattner5d5a8972009-01-05 19:01:32 +0000443 // try explicit -L arguments first:
444 sys::Path FullLibraryPath;
445 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
446 E = LibPaths.end(); P != E; ++P) {
447 FullLibraryPath = *P;
448 FullLibraryPath.appendComponent("lib" + *i);
449 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
450 if (!FullLibraryPath.isEmpty()) {
451 if (!FullLibraryPath.isDynamicLibrary()) {
452 // Not a native shared library; mark as invalid
453 FullLibraryPath = sys::Path();
454 } else break;
455 }
456 }
457 if (FullLibraryPath.isEmpty())
458 FullLibraryPath = sys::Path::FindLibrary(*i);
459 if (!FullLibraryPath.isEmpty())
Reid Spencerc4064132004-12-13 03:01:14 +0000460 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000461 }
462 Out2 << " $0.bc ${1+\"$@\"}\n";
463 Out2.close();
464}
465
Reid Spencerc4064132004-12-13 03:01:14 +0000466// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
467// linker function by combining the Files and Libraries in the order they were
468// declared on the command line.
469static void BuildLinkItems(
470 Linker::ItemList& Items,
471 const cl::list<std::string>& Files,
472 const cl::list<std::string>& Libraries) {
473
Misha Brukman3da94ae2005-04-22 00:00:37 +0000474 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000475
476 cl::list<std::string>::const_iterator fileIt = Files.begin();
477 cl::list<std::string>::const_iterator libIt = Libraries.begin();
478
479 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000480 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000481 if (libIt != Libraries.end())
482 libPos = Libraries.getPosition(libIt - Libraries.begin());
483 else
484 libPos = -1;
485 if (fileIt != Files.end())
486 filePos = Files.getPosition(fileIt - Files.begin());
487 else
488 filePos = -1;
489
490 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
491 // Add a source file
492 Items.push_back(std::make_pair(*fileIt++, false));
493 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
494 // Add a library
495 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000496 }
497 }
498}
499
Reid Spencer445564a2004-11-20 20:02:56 +0000500// Rightly this should go in a header file but it just seems such a waste.
501namespace llvm {
502extern void Optimize(Module*);
503}
504
Reid Spencerc0af3f02004-09-13 01:27:53 +0000505int main(int argc, char **argv, char **envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000506 // Print a stack trace if we signal out.
507 sys::PrintStackTraceOnErrorSignal();
508 PrettyStackTraceProgram X(argc, argv);
Owen Anderson8b477ed2009-07-01 16:58:40 +0000509
510 LLVMContext Context;
Chris Lattnercc14d252009-03-06 05:34:10 +0000511 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000512 try {
513 // Initial global variable above for convenience printing of program name.
514 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000515
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000516 // Parse the command line options
Dan Gohman82a13c92007-10-08 15:45:12 +0000517 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000518
Reid Spencer49521432006-11-11 11:54:25 +0000519 // Construct a Linker (now that Verbose is set)
Owen Anderson31895e72009-07-01 21:22:36 +0000520 Linker TheLinker(progname, OutputFilename, Context, Verbose);
Reid Spencerc82a5da2007-04-04 06:34:22 +0000521
Gabor Greifa99be512007-07-05 17:07:56 +0000522 // Keep track of the native link items (versus the bitcode items)
Reid Spencerc82a5da2007-04-04 06:34:22 +0000523 Linker::ItemList NativeLinkItems;
Reid Spencer49521432006-11-11 11:54:25 +0000524
525 // Add library paths to the linker
Reid Spencer78df5c32006-03-06 06:38:19 +0000526 TheLinker.addPaths(LibPaths);
527 TheLinker.addSystemPaths();
528
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000529 // Remove any consecutive duplicates of the same library...
530 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
531 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000532
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000533 if (LinkAsLibrary) {
534 std::vector<sys::Path> Files;
535 for (unsigned i = 0; i < InputFilenames.size(); ++i )
536 Files.push_back(sys::Path(InputFilenames[i]));
537 if (TheLinker.LinkInFiles(Files))
538 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000539
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000540 // The libraries aren't linked in but are noted as "dependent" in the
541 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000542 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000543 E = Libraries.end(); I != E ; ++I) {
544 TheLinker.getModule()->addLibrary(*I);
545 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000546 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000547 // Build a list of the items from our command line
548 Linker::ItemList Items;
549 BuildLinkItems(Items, InputFilenames, Libraries);
550
551 // Link all the items together
Reid Spencerc82a5da2007-04-04 06:34:22 +0000552 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
Reid Spencer708585a2007-02-09 03:08:06 +0000553 return 1; // Error already printed
Reid Spencerc0af3f02004-09-13 01:27:53 +0000554 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000555
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000556 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
557
558 // Optimize the module
559 Optimize(Composite.get());
560
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000561#if defined(_WIN32) || defined(__CYGWIN__)
562 if (!LinkAsLibrary) {
Argyrios Kyrtzidis48cca1f2008-06-15 15:20:16 +0000563 // Default to "a.exe" instead of "a.out".
564 if (OutputFilename.getNumOccurrences() == 0)
565 OutputFilename = "a.exe";
566
567 // If there is no suffix add an "exe" one.
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000568 sys::Path ExeFile( OutputFilename );
Argyrios Kyrtzidis48cca1f2008-06-15 15:20:16 +0000569 if (ExeFile.getSuffix() == "") {
570 ExeFile.appendSuffix("exe");
571 OutputFilename = ExeFile.toString();
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000572 }
573 }
574#endif
575
Gabor Greifa99be512007-07-05 17:07:56 +0000576 // Generate the bitcode for the optimized module.
577 std::string RealBitcodeOutput = OutputFilename;
Argyrios Kyrtzidis5b90a722008-06-15 12:01:16 +0000578
Gabor Greifa99be512007-07-05 17:07:56 +0000579 if (!LinkAsLibrary) RealBitcodeOutput += ".bc";
580 GenerateBitcode(Composite.get(), RealBitcodeOutput);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000581
582 // If we are not linking a library, generate either a native executable
583 // or a JIT shell script, depending upon what the user wants.
584 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000585 // If the user wants to run a post-link optimization, run it now.
586 if (!PostLinkOpts.empty()) {
587 std::vector<std::string> opts = PostLinkOpts;
588 for (std::vector<std::string>::iterator I = opts.begin(),
589 E = opts.end(); I != E; ++I) {
590 sys::Path prog(*I);
591 if (!prog.canExecute()) {
592 prog = sys::Program::FindProgramByName(*I);
593 if (prog.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000594 PrintAndExit(std::string("Optimization program '") + *I +
Reid Spencer73a74be2005-12-21 05:03:23 +0000595 "' is not found or not executable.");
596 }
597 // Get the program arguments
598 sys::Path tmp_output("opt_result");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000599 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000600 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
601 PrintAndExit(ErrMsg);
602
Reid Spencer73a74be2005-12-21 05:03:23 +0000603 const char* args[4];
604 args[0] = I->c_str();
Gabor Greifa99be512007-07-05 17:07:56 +0000605 args[1] = RealBitcodeOutput.c_str();
Reid Spencer73a74be2005-12-21 05:03:23 +0000606 args[2] = tmp_output.c_str();
607 args[3] = 0;
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000608 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
Gabor Greifa99be512007-07-05 17:07:56 +0000609 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
610 sys::Path target(RealBitcodeOutput);
Reid Spencer73a74be2005-12-21 05:03:23 +0000611 target.eraseFromDisk();
Reid Spencer708585a2007-02-09 03:08:06 +0000612 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
613 PrintAndExit(ErrMsg, 2);
Reid Spencer73a74be2005-12-21 05:03:23 +0000614 } else
Gabor Greifa99be512007-07-05 17:07:56 +0000615 PrintAndExit("Post-link optimization output is not bitcode");
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000616 } else {
Reid Spencer708585a2007-02-09 03:08:06 +0000617 PrintAndExit(ErrMsg);
Reid Spencer73a74be2005-12-21 05:03:23 +0000618 }
619 }
620 }
621
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000622 // If the user wants to generate a native executable, compile it from the
Gabor Greifa99be512007-07-05 17:07:56 +0000623 // bitcode file.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000624 //
Gabor Greifa99be512007-07-05 17:07:56 +0000625 // Otherwise, create a script that will run the bitcode through the JIT.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000626 if (Native) {
627 // Name of the Assembly Language output file
628 sys::Path AssemblyFile ( OutputFilename);
629 AssemblyFile.appendSuffix("s");
630
631 // Mark the output files for removal if we get an interrupt.
632 sys::RemoveFileOnSignal(AssemblyFile);
633 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
634
635 // Determine the locations of the llc and gcc programs.
636 sys::Path llc = FindExecutable("llc", argv[0]);
637 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000638 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000639
640 sys::Path gcc = FindExecutable("gcc", argv[0]);
641 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000642 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000643
Gabor Greifa99be512007-07-05 17:07:56 +0000644 // Generate an assembly language file for the bitcode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000645 std::string ErrMsg;
Gabor Greifa99be512007-07-05 17:07:56 +0000646 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBitcodeOutput,
Reid Spencer708585a2007-02-09 03:08:06 +0000647 llc, ErrMsg))
648 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000649
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000650 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
Reid Spencerc82a5da2007-04-04 06:34:22 +0000651 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000652 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000653
654 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000655 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000656 } else if (NativeCBE) {
657 sys::Path CFile (OutputFilename);
658 CFile.appendSuffix("cbe.c");
659
660 // Mark the output files for removal if we get an interrupt.
661 sys::RemoveFileOnSignal(CFile);
662 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
663
664 // Determine the locations of the llc and gcc programs.
665 sys::Path llc = FindExecutable("llc", argv[0]);
666 if (llc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000667 PrintAndExit("Failed to find llc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000668
669 sys::Path gcc = FindExecutable("gcc", argv[0]);
670 if (gcc.isEmpty())
Reid Spencer708585a2007-02-09 03:08:06 +0000671 PrintAndExit("Failed to find gcc");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000672
Gabor Greifa99be512007-07-05 17:07:56 +0000673 // Generate an assembly language file for the bitcode.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000674 std::string ErrMsg;
675 if (0 != GenerateCFile(
Gabor Greifa99be512007-07-05 17:07:56 +0000676 CFile.toString(), RealBitcodeOutput, llc, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000677 PrintAndExit(ErrMsg);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000678
Reid Spencerc82a5da2007-04-04 06:34:22 +0000679 if (0 != GenerateNative(OutputFilename, CFile.toString(),
680 NativeLinkItems, gcc, envp, ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000681 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000682
683 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000684 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000685
686 } else {
687 EmitShellScript(argv);
688 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000689
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000690 // Make the script executable...
Reid Spencere1647f42006-08-22 23:27:23 +0000691 std::string ErrMsg;
Reid Spencer708585a2007-02-09 03:08:06 +0000692 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
693 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000694
Gabor Greifa99be512007-07-05 17:07:56 +0000695 // Make the bitcode file readable and directly executable in LLEE as well
696 if (sys::Path(RealBitcodeOutput).makeExecutableOnDisk(&ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000697 PrintAndExit(ErrMsg);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000698
Gabor Greifa99be512007-07-05 17:07:56 +0000699 if (sys::Path(RealBitcodeOutput).makeReadableOnDisk(&ErrMsg))
Reid Spencer708585a2007-02-09 03:08:06 +0000700 PrintAndExit(ErrMsg);
701 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000702 } catch (const std::string& msg) {
Reid Spencer708585a2007-02-09 03:08:06 +0000703 PrintAndExit(msg,2);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000704 } catch (...) {
Reid Spencer708585a2007-02-09 03:08:06 +0000705 PrintAndExit("Unexpected unknown exception occurred.", 2);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000706 }
Reid Spencer708585a2007-02-09 03:08:06 +0000707
708 // Graceful exit
709 return 0;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000710}