1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/Linker.h"
24 #include "llvm/System/Program.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/Writer.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/System/Signals.h"
42 // Input/Output Options
43 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44 cl::desc("<input bytecode files>"));
46 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
47 cl::desc("Override output filename"),
48 cl::value_desc("filename"));
50 static cl::opt<bool> Verbose("v",
51 cl::desc("Print information about actions taken"));
53 static cl::list<std::string> LibPaths("L", cl::Prefix,
54 cl::desc("Specify a library search path"),
55 cl::value_desc("directory"));
57 static cl::list<std::string> Libraries("l", cl::Prefix,
58 cl::desc("Specify libraries to link to"),
59 cl::value_desc("library prefix"));
61 static cl::opt<bool> LinkAsLibrary("link-as-library",
62 cl::desc("Link the .bc files together as a library, not an executable"));
64 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65 cl::desc("Alias for -link-as-library"));
67 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
68 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
70 static cl::opt<bool> Native("native",
71 cl::desc("Generate a native binary instead of a shell script"));
73 static cl::opt<bool>NativeCBE("native-cbe",
74 cl::desc("Generate a native binary with the C backend and GCC"));
76 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77 cl::desc("Disable writing of compressed bytecode files"));
79 // Compatibility options that are ignored but supported by LD
80 static cl::opt<std::string> CO3("soname", cl::Hidden,
81 cl::desc("Compatibility option: ignored"));
83 static cl::opt<std::string> CO4("version-script", cl::Hidden,
84 cl::desc("Compatibility option: ignored"));
86 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
87 cl::desc("Compatibility option: ignored"));
89 static cl::opt<std::string> CO6("h", cl::Hidden,
90 cl::desc("Compatibility option: ignored"));
92 /// This is just for convenience so it doesn't have to be passed around
94 static std::string progname;
96 /// PrintAndReturn - Prints a message to standard error and returns true.
99 /// progname - The name of the program (i.e. argv[0]).
100 /// Message - The message to print to standard error.
102 static int PrintAndReturn(const std::string &Message) {
103 std::cerr << progname << ": " << Message << "\n";
107 /// CopyEnv - This function takes an array of environment variables and makes a
108 /// copy of it. This copy can then be manipulated any way the caller likes
109 /// without affecting the process's real environment.
112 /// envp - An array of C strings containing an environment.
115 /// NULL - An error occurred.
117 /// Otherwise, a pointer to a new array of C strings is returned. Every string
118 /// in the array is a duplicate of the one in the original array (i.e. we do
119 /// not copy the char *'s from one array to another).
121 static char ** CopyEnv(char ** const envp) {
122 // Count the number of entries in the old list;
123 unsigned entries; // The number of entries in the old environment list
124 for (entries = 0; envp[entries] != NULL; entries++)
127 // Add one more entry for the NULL pointer that ends the list.
130 // If there are no entries at all, just return NULL.
134 // Allocate a new environment list.
135 char **newenv = new char* [entries];
136 if ((newenv = new char* [entries]) == NULL)
139 // Make a copy of the list. Don't forget the NULL that ends the list.
141 while (envp[entries] != NULL) {
142 newenv[entries] = new char[strlen (envp[entries]) + 1];
143 strcpy (newenv[entries], envp[entries]);
146 newenv[entries] = NULL;
152 /// RemoveEnv - Remove the specified environment variable from the environment
156 /// name - The name of the variable to remove. It cannot be NULL.
157 /// envp - The array of environment variables. It cannot be NULL.
160 /// This is mainly done because functions to remove items from the environment
161 /// are not available across all platforms. In particular, Solaris does not
162 /// seem to have an unsetenv() function or a setenv() function (or they are
163 /// undocumented if they do exist).
165 static void RemoveEnv(const char * name, char ** const envp) {
166 for (unsigned index=0; envp[index] != NULL; index++) {
167 // Find the first equals sign in the array and make it an EOS character.
168 char *p = strchr (envp[index], '=');
174 // Compare the two strings. If they are equal, zap this string.
175 // Otherwise, restore it.
176 if (!strcmp(name, envp[index]))
185 /// GenerateBytecode - generates a bytecode file from the module provided
186 void GenerateBytecode(Module* M, const std::string& FileName) {
188 // Create the output file.
189 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
191 std::ofstream Out(FileName.c_str(), io_mode);
193 PrintAndReturn("error opening '" + FileName + "' for writing!");
197 // Ensure that the bytecode file gets removed from the disk if we get a
198 // terminating signal.
199 sys::RemoveFileOnSignal(sys::Path(FileName));
202 WriteBytecodeToFile(M, Out, !DisableCompression);
204 // Close the bytecode file.
208 /// GenerateAssembly - generates a native assembly language source file from the
209 /// specified bytecode file.
212 /// InputFilename - The name of the output bytecode file.
213 /// OutputFilename - The name of the file to generate.
214 /// llc - The pathname to use for LLC.
215 /// envp - The environment to use when running LLC.
217 /// Return non-zero value on error.
219 static int GenerateAssembly(const std::string &OutputFilename,
220 const std::string &InputFilename,
221 const sys::Path &llc) {
222 // Run LLC to convert the bytecode file into assembly code.
223 std::vector<const char*> args;
224 args.push_back( "-f");
225 args.push_back( "-o");
226 args.push_back( OutputFilename.c_str() );
227 args.push_back( InputFilename.c_str() );
229 return sys::Program::ExecuteAndWait(llc,&args[0]);
232 /// GenerateAssembly - generates a native assembly language source file from the
233 /// specified bytecode file.
234 static int GenerateCFile(const std::string &OutputFile,
235 const std::string &InputFile,
236 const sys::Path &llc) {
237 // Run LLC to convert the bytecode file into C.
238 std::vector<const char*> args;
239 args.push_back( "-march=c");
240 args.push_back( "-f");
241 args.push_back( "-o");
242 args.push_back( OutputFile.c_str() );
243 args.push_back( InputFile.c_str() );
244 return sys::Program::ExecuteAndWait(llc, &args[0]);
247 /// GenerateNative - generates a native assembly language source file from the
248 /// specified assembly source file.
251 /// InputFilename - The name of the output bytecode file.
252 /// OutputFilename - The name of the file to generate.
253 /// Libraries - The list of libraries with which to link.
254 /// LibPaths - The list of directories in which to find libraries.
255 /// gcc - The pathname to use for GGC.
256 /// envp - A copy of the process's current environment.
261 /// Returns non-zero value on error.
263 static int GenerateNative(const std::string &OutputFilename,
264 const std::string &InputFilename,
265 const std::vector<std::string> &Libraries,
266 const sys::Path &gcc, char ** const envp) {
267 // Remove these environment variables from the environment of the
268 // programs that we will execute. It appears that GCC sets these
269 // environment variables so that the programs it uses can configure
270 // themselves identically.
272 // However, when we invoke GCC below, we want it to use its normal
273 // configuration. Hence, we must sanitize its environment.
274 char ** clean_env = CopyEnv(envp);
275 if (clean_env == NULL)
277 RemoveEnv("LIBRARY_PATH", clean_env);
278 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
279 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
280 RemoveEnv("COMPILER_PATH", clean_env);
281 RemoveEnv("COLLECT_GCC", clean_env);
284 // Run GCC to assemble and link the program into native code.
287 // We can't just assemble and link the file with the system assembler
288 // and linker because we don't know where to put the _start symbol.
289 // GCC mysteriously knows how to do it.
290 std::vector<const char*> args;
291 args.push_back("-fno-strict-aliasing");
292 args.push_back("-O3");
293 args.push_back("-o");
294 args.push_back(OutputFilename.c_str());
295 args.push_back(InputFilename.c_str());
297 // Add in the libraries to link.
298 for (unsigned index = 0; index < Libraries.size(); index++)
299 if (Libraries[index] != "crtend") {
300 args.push_back("-l");
301 args.push_back(Libraries[index].c_str());
304 // Run the compiler to assembly and link together the program.
305 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
308 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
309 /// bytecode file for the program.
310 static void EmitShellScript(char **argv) {
311 #if defined(_WIN32) || defined(__CYGWIN__)
312 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
313 // support windows systems, we copy the llvm-stub.exe executable from the
314 // build tree to the destination file.
315 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
316 if (llvmstub.isEmpty()) {
317 std::cerr << "Could not find llvm-stub.exe executable!\n";
320 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
324 // Output the script to start the program...
325 std::ofstream Out2(OutputFilename.c_str());
327 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
329 Out2 << "#!/bin/sh\n";
330 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
331 Out2 << "lli=${LLVMINTERP-lli}\n";
332 Out2 << "exec $lli \\\n";
333 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
334 LibPaths.push_back("/lib");
335 LibPaths.push_back("/usr/lib");
336 LibPaths.push_back("/usr/X11R6/lib");
337 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
338 // shared object at all! See RH 8: plain text.
339 std::vector<std::string>::iterator libc =
340 std::find(Libraries.begin(), Libraries.end(), "c");
341 if (libc != Libraries.end()) Libraries.erase(libc);
342 // List all the shared object (native) libraries this executable will need
343 // on the command line, so that we don't have to do this manually!
344 for (std::vector<std::string>::iterator i = Libraries.begin(),
345 e = Libraries.end(); i != e; ++i) {
346 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
347 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
348 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
350 Out2 << " $0.bc ${1+\"$@\"}\n";
354 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
355 // linker function by combining the Files and Libraries in the order they were
356 // declared on the command line.
357 static void BuildLinkItems(
358 Linker::ItemList& Items,
359 const cl::list<std::string>& Files,
360 const cl::list<std::string>& Libraries) {
362 // Build the list of linkage items for LinkItems.
364 cl::list<std::string>::const_iterator fileIt = Files.begin();
365 cl::list<std::string>::const_iterator libIt = Libraries.begin();
367 int libPos = -1, filePos = -1;
368 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
369 if (libIt != Libraries.end())
370 libPos = Libraries.getPosition(libIt - Libraries.begin());
373 if (fileIt != Files.end())
374 filePos = Files.getPosition(fileIt - Files.begin());
378 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
380 Items.push_back(std::make_pair(*fileIt++, false));
381 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
383 Items.push_back(std::make_pair(*libIt++, true));
388 // Rightly this should go in a header file but it just seems such a waste.
390 extern void Optimize(Module*);
393 int main(int argc, char **argv, char **envp) {
395 // Initial global variable above for convenience printing of program name.
396 progname = sys::Path(argv[0]).getBasename();
397 Linker TheLinker(progname, Verbose);
399 // Set up the library paths for the Linker
400 TheLinker.addPaths(LibPaths);
401 TheLinker.addSystemPaths();
403 // Parse the command line options
404 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
405 sys::PrintStackTraceOnErrorSignal();
407 // Remove any consecutive duplicates of the same library...
408 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
412 std::vector<sys::Path> Files;
413 for (unsigned i = 0; i < InputFilenames.size(); ++i )
414 Files.push_back(sys::Path(InputFilenames[i]));
415 if (TheLinker.LinkInFiles(Files))
416 return 1; // Error already printed
418 // The libraries aren't linked in but are noted as "dependent" in the
420 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
421 E = Libraries.end(); I != E ; ++I) {
422 TheLinker.getModule()->addLibrary(*I);
425 // Build a list of the items from our command line
426 Linker::ItemList Items;
427 BuildLinkItems(Items, InputFilenames, Libraries);
429 // Link all the items together
430 if (TheLinker.LinkInItems(Items) )
434 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
436 // Optimize the module
437 Optimize(Composite.get());
439 // Generate the bytecode for the optimized module.
440 std::string RealBytecodeOutput = OutputFilename;
441 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
442 GenerateBytecode(Composite.get(), RealBytecodeOutput);
444 // If we are not linking a library, generate either a native executable
445 // or a JIT shell script, depending upon what the user wants.
446 if (!LinkAsLibrary) {
447 // If the user wants to generate a native executable, compile it from the
450 // Otherwise, create a script that will run the bytecode through the JIT.
452 // Name of the Assembly Language output file
453 sys::Path AssemblyFile ( OutputFilename);
454 AssemblyFile.appendSuffix("s");
456 // Mark the output files for removal if we get an interrupt.
457 sys::RemoveFileOnSignal(AssemblyFile);
458 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
460 // Determine the locations of the llc and gcc programs.
461 sys::Path llc = FindExecutable("llc", argv[0]);
463 return PrintAndReturn("Failed to find llc");
465 sys::Path gcc = FindExecutable("gcc", argv[0]);
467 return PrintAndReturn("Failed to find gcc");
469 // Generate an assembly language file for the bytecode.
470 if (Verbose) std::cout << "Generating Assembly Code\n";
471 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
472 if (Verbose) std::cout << "Generating Native Code\n";
473 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
476 // Remove the assembly language file.
477 AssemblyFile.destroyFile();
478 } else if (NativeCBE) {
479 sys::Path CFile (OutputFilename);
480 CFile.appendSuffix("cbe.c");
482 // Mark the output files for removal if we get an interrupt.
483 sys::RemoveFileOnSignal(CFile);
484 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
486 // Determine the locations of the llc and gcc programs.
487 sys::Path llc = FindExecutable("llc", argv[0]);
489 return PrintAndReturn("Failed to find llc");
491 sys::Path gcc = FindExecutable("gcc", argv[0]);
493 return PrintAndReturn("Failed to find gcc");
495 // Generate an assembly language file for the bytecode.
496 if (Verbose) std::cout << "Generating Assembly Code\n";
497 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
498 if (Verbose) std::cout << "Generating Native Code\n";
499 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
501 // Remove the assembly language file.
505 EmitShellScript(argv);
508 // Make the script executable...
509 sys::Path(OutputFilename).makeExecutable();
511 // Make the bytecode file readable and directly executable in LLEE as well
512 sys::Path(RealBytecodeOutput).makeExecutable();
513 sys::Path(RealBytecodeOutput).makeReadable();
517 } catch (const std::string& msg) {
518 std::cerr << argv[0] << ": " << msg << "\n";
520 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";