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/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/System/Program.h"
26 #include "llvm/Module.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Bytecode/Reader.h"
29 #include "llvm/Bytecode/Writer.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/Streams.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Signals.h"
43 // Input/Output Options
44 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bytecode files>"));
47 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
48 cl::desc("Override output filename"),
49 cl::value_desc("filename"));
51 static cl::opt<bool> Verbose("v",
52 cl::desc("Print information about actions taken"));
54 static cl::list<std::string> LibPaths("L", cl::Prefix,
55 cl::desc("Specify a library search path"),
56 cl::value_desc("directory"));
58 static cl::list<std::string> Libraries("l", cl::Prefix,
59 cl::desc("Specify libraries to link to"),
60 cl::value_desc("library prefix"));
62 static cl::opt<bool> LinkAsLibrary("link-as-library",
63 cl::desc("Link the .bc files together as a library, not an executable"));
65 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
66 cl::desc("Alias for -link-as-library"));
68 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
69 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
71 static cl::opt<bool> Native("native",
72 cl::desc("Generate a native binary instead of a shell script"));
74 static cl::opt<bool>NativeCBE("native-cbe",
75 cl::desc("Generate a native binary with the C backend and GCC"));
77 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
78 cl::desc("Disable writing of compressed bytecode files"));
80 static cl::list<std::string> PostLinkOpts("post-link-opts",
81 cl::value_desc("path"),
82 cl::desc("Run one or more optimization programs after linking"));
84 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
85 cl::desc("Pass options to the system linker"));
87 // Compatibility options that are ignored but supported by LD
88 static cl::opt<std::string> CO3("soname", cl::Hidden,
89 cl::desc("Compatibility option: ignored"));
91 static cl::opt<std::string> CO4("version-script", cl::Hidden,
92 cl::desc("Compatibility option: ignored"));
94 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
95 cl::desc("Compatibility option: ignored"));
97 static cl::opt<std::string> CO6("h", cl::Hidden,
98 cl::desc("Compatibility option: ignored"));
101 /// This is just for convenience so it doesn't have to be passed around
103 static std::string progname;
105 /// PrintAndReturn - Prints a message to standard error and returns true.
108 /// progname - The name of the program (i.e. argv[0]).
109 /// Message - The message to print to standard error.
111 static int PrintAndReturn(const std::string &Message) {
112 llvm_cerr << progname << ": " << Message << "\n";
116 /// CopyEnv - This function takes an array of environment variables and makes a
117 /// copy of it. This copy can then be manipulated any way the caller likes
118 /// without affecting the process's real environment.
121 /// envp - An array of C strings containing an environment.
124 /// NULL - An error occurred.
126 /// Otherwise, a pointer to a new array of C strings is returned. Every string
127 /// in the array is a duplicate of the one in the original array (i.e. we do
128 /// not copy the char *'s from one array to another).
130 static char ** CopyEnv(char ** const envp) {
131 // Count the number of entries in the old list;
132 unsigned entries; // The number of entries in the old environment list
133 for (entries = 0; envp[entries] != NULL; entries++)
136 // Add one more entry for the NULL pointer that ends the list.
139 // If there are no entries at all, just return NULL.
143 // Allocate a new environment list.
144 char **newenv = new char* [entries];
145 if ((newenv = new char* [entries]) == NULL)
148 // Make a copy of the list. Don't forget the NULL that ends the list.
150 while (envp[entries] != NULL) {
151 newenv[entries] = new char[strlen (envp[entries]) + 1];
152 strcpy (newenv[entries], envp[entries]);
155 newenv[entries] = NULL;
161 /// RemoveEnv - Remove the specified environment variable from the environment
165 /// name - The name of the variable to remove. It cannot be NULL.
166 /// envp - The array of environment variables. It cannot be NULL.
169 /// This is mainly done because functions to remove items from the environment
170 /// are not available across all platforms. In particular, Solaris does not
171 /// seem to have an unsetenv() function or a setenv() function (or they are
172 /// undocumented if they do exist).
174 static void RemoveEnv(const char * name, char ** const envp) {
175 for (unsigned index=0; envp[index] != NULL; index++) {
176 // Find the first equals sign in the array and make it an EOS character.
177 char *p = strchr (envp[index], '=');
183 // Compare the two strings. If they are equal, zap this string.
184 // Otherwise, restore it.
185 if (!strcmp(name, envp[index]))
194 /// GenerateBytecode - generates a bytecode file from the module provided
195 void GenerateBytecode(Module* M, const std::string& FileName) {
197 // Create the output file.
198 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
200 std::ofstream Out(FileName.c_str(), io_mode);
202 PrintAndReturn("error opening '" + FileName + "' for writing!");
206 // Ensure that the bytecode file gets removed from the disk if we get a
207 // terminating signal.
208 sys::RemoveFileOnSignal(sys::Path(FileName));
212 WriteBytecodeToFile(M, L, !DisableCompression);
214 // Close the bytecode file.
218 /// GenerateAssembly - generates a native assembly language source file from the
219 /// specified bytecode file.
222 /// InputFilename - The name of the input bytecode file.
223 /// OutputFilename - The name of the file to generate.
224 /// llc - The pathname to use for LLC.
225 /// envp - The environment to use when running LLC.
227 /// Return non-zero value on error.
229 static int GenerateAssembly(const std::string &OutputFilename,
230 const std::string &InputFilename,
231 const sys::Path &llc,
232 std::string &ErrMsg ) {
233 // Run LLC to convert the bytecode file into assembly code.
234 std::vector<const char*> args;
235 args.push_back(llc.c_str());
236 args.push_back("-f");
237 args.push_back("-o");
238 args.push_back(OutputFilename.c_str());
239 args.push_back(InputFilename.c_str());
242 return sys::Program::ExecuteAndWait(llc,&args[0],0,0,0,&ErrMsg);
245 /// GenerateCFile - generates a C source file from the specified bytecode file.
246 static int GenerateCFile(const std::string &OutputFile,
247 const std::string &InputFile,
248 const sys::Path &llc,
249 std::string& ErrMsg) {
250 // Run LLC to convert the bytecode file into C.
251 std::vector<const char*> args;
252 args.push_back(llc.c_str());
253 args.push_back("-march=c");
254 args.push_back("-f");
255 args.push_back("-o");
256 args.push_back(OutputFile.c_str());
257 args.push_back(InputFile.c_str());
259 return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
262 /// GenerateNative - generates a native object file from the
263 /// specified bytecode file.
266 /// InputFilename - The name of the input bytecode file.
267 /// OutputFilename - The name of the file to generate.
268 /// LinkItems - The native libraries, files, code with which to link
269 /// LibPaths - The list of directories in which to find libraries.
270 /// gcc - The pathname to use for GGC.
271 /// envp - A copy of the process's current environment.
276 /// Returns non-zero value on error.
278 static int GenerateNative(const std::string &OutputFilename,
279 const std::string &InputFilename,
280 const Linker::ItemList &LinkItems,
281 const sys::Path &gcc, char ** const envp,
282 std::string& ErrMsg) {
283 // Remove these environment variables from the environment of the
284 // programs that we will execute. It appears that GCC sets these
285 // environment variables so that the programs it uses can configure
286 // themselves identically.
288 // However, when we invoke GCC below, we want it to use its normal
289 // configuration. Hence, we must sanitize its environment.
290 char ** clean_env = CopyEnv(envp);
291 if (clean_env == NULL)
293 RemoveEnv("LIBRARY_PATH", clean_env);
294 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
295 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
296 RemoveEnv("COMPILER_PATH", clean_env);
297 RemoveEnv("COLLECT_GCC", clean_env);
300 // Run GCC to assemble and link the program into native code.
303 // We can't just assemble and link the file with the system assembler
304 // and linker because we don't know where to put the _start symbol.
305 // GCC mysteriously knows how to do it.
306 std::vector<const char*> args;
307 args.push_back(gcc.c_str());
308 args.push_back("-fno-strict-aliasing");
309 args.push_back("-O3");
310 args.push_back("-o");
311 args.push_back(OutputFilename.c_str());
312 args.push_back(InputFilename.c_str());
314 // Add in the library paths
315 for (unsigned index = 0; index < LibPaths.size(); index++) {
316 args.push_back("-L");
317 args.push_back(LibPaths[index].c_str());
320 // Add the requested options
321 for (unsigned index = 0; index < XLinker.size(); index++) {
322 args.push_back(XLinker[index].c_str());
323 args.push_back(Libraries[index].c_str());
326 // Add in the libraries to link.
327 for (unsigned index = 0; index < LinkItems.size(); index++)
328 if (LinkItems[index].first != "crtend") {
329 if (LinkItems[index].second) {
330 std::string lib_name = "-l" + LinkItems[index].first;
331 args.push_back(lib_name.c_str());
333 args.push_back(LinkItems[index].first.c_str());
338 // Run the compiler to assembly and link together the program.
339 int R = sys::Program::ExecuteAndWait(
340 gcc, &args[0], (const char**)clean_env,0,0,&ErrMsg);
345 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
346 /// bytecode file for the program.
347 static void EmitShellScript(char **argv) {
348 #if defined(_WIN32) || defined(__CYGWIN__)
349 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
350 // support windows systems, we copy the llvm-stub.exe executable from the
351 // build tree to the destination file.
353 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
354 if (llvmstub.isEmpty()) {
355 llvm_cerr << "Could not find llvm-stub.exe executable!\n";
359 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg)) {
360 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
367 // Output the script to start the program...
368 std::ofstream Out2(OutputFilename.c_str());
370 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
372 Out2 << "#!/bin/sh\n";
373 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
374 Out2 << "lli=${LLVMINTERP-lli}\n";
375 Out2 << "exec $lli \\\n";
376 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
377 LibPaths.push_back("/lib");
378 LibPaths.push_back("/usr/lib");
379 LibPaths.push_back("/usr/X11R6/lib");
380 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
381 // shared object at all! See RH 8: plain text.
382 std::vector<std::string>::iterator libc =
383 std::find(Libraries.begin(), Libraries.end(), "c");
384 if (libc != Libraries.end()) Libraries.erase(libc);
385 // List all the shared object (native) libraries this executable will need
386 // on the command line, so that we don't have to do this manually!
387 for (std::vector<std::string>::iterator i = Libraries.begin(),
388 e = Libraries.end(); i != e; ++i) {
389 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
390 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
391 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
393 Out2 << " $0.bc ${1+\"$@\"}\n";
397 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
398 // linker function by combining the Files and Libraries in the order they were
399 // declared on the command line.
400 static void BuildLinkItems(
401 Linker::ItemList& Items,
402 const cl::list<std::string>& Files,
403 const cl::list<std::string>& Libraries) {
405 // Build the list of linkage items for LinkItems.
407 cl::list<std::string>::const_iterator fileIt = Files.begin();
408 cl::list<std::string>::const_iterator libIt = Libraries.begin();
410 int libPos = -1, filePos = -1;
411 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
412 if (libIt != Libraries.end())
413 libPos = Libraries.getPosition(libIt - Libraries.begin());
416 if (fileIt != Files.end())
417 filePos = Files.getPosition(fileIt - Files.begin());
421 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
423 Items.push_back(std::make_pair(*fileIt++, false));
424 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
426 Items.push_back(std::make_pair(*libIt++, true));
431 // Rightly this should go in a header file but it just seems such a waste.
433 extern void Optimize(Module*);
436 int main(int argc, char **argv, char **envp) {
437 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
439 // Initial global variable above for convenience printing of program name.
440 progname = sys::Path(argv[0]).getBasename();
442 // Parse the command line options
443 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
444 sys::PrintStackTraceOnErrorSignal();
446 // Construct a Linker (now that Verbose is set)
447 Linker TheLinker(progname, OutputFilename, Verbose);
448 // Keep track of the native link items (vice the bytecode items)
449 Linker::ItemList LinkItems;
451 // Add library paths to the linker
452 TheLinker.addPaths(LibPaths);
453 TheLinker.addSystemPaths();
455 // Remove any consecutive duplicates of the same library...
456 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
460 std::vector<sys::Path> Files;
461 for (unsigned i = 0; i < InputFilenames.size(); ++i )
462 Files.push_back(sys::Path(InputFilenames[i]));
463 if (TheLinker.LinkInFiles(Files))
464 return 1; // Error already printed
466 // The libraries aren't linked in but are noted as "dependent" in the
468 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
469 E = Libraries.end(); I != E ; ++I) {
470 TheLinker.getModule()->addLibrary(*I);
473 // Build a list of the items from our command line
474 Linker::ItemList Items;
475 BuildLinkItems(Items, InputFilenames, Libraries);
477 // Link all the items together
478 if (TheLinker.LinkInItems(Items,LinkItems) )
482 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
484 // Optimize the module
485 Optimize(Composite.get());
487 // Generate the bytecode for the optimized module.
488 std::string RealBytecodeOutput = OutputFilename;
489 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
490 GenerateBytecode(Composite.get(), RealBytecodeOutput);
492 // If we are not linking a library, generate either a native executable
493 // or a JIT shell script, depending upon what the user wants.
494 if (!LinkAsLibrary) {
495 // If the user wants to run a post-link optimization, run it now.
496 if (!PostLinkOpts.empty()) {
497 std::vector<std::string> opts = PostLinkOpts;
498 for (std::vector<std::string>::iterator I = opts.begin(),
499 E = opts.end(); I != E; ++I) {
501 if (!prog.canExecute()) {
502 prog = sys::Program::FindProgramByName(*I);
504 return PrintAndReturn(std::string("Optimization program '") + *I +
505 "' is not found or not executable.");
507 // Get the program arguments
508 sys::Path tmp_output("opt_result");
510 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg)) {
511 return PrintAndReturn(ErrMsg);
514 args[0] = I->c_str();
515 args[1] = RealBytecodeOutput.c_str();
516 args[2] = tmp_output.c_str();
518 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0, &ErrMsg)) {
519 if (tmp_output.isBytecodeFile()) {
520 sys::Path target(RealBytecodeOutput);
521 target.eraseFromDisk();
522 if (tmp_output.renamePathOnDisk(target, &ErrMsg)) {
523 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
527 return PrintAndReturn(
528 "Post-link optimization output is not bytecode");
530 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
536 // If the user wants to generate a native executable, compile it from the
539 // Otherwise, create a script that will run the bytecode through the JIT.
541 // Name of the Assembly Language output file
542 sys::Path AssemblyFile ( OutputFilename);
543 AssemblyFile.appendSuffix("s");
545 // Mark the output files for removal if we get an interrupt.
546 sys::RemoveFileOnSignal(AssemblyFile);
547 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
549 // Determine the locations of the llc and gcc programs.
550 sys::Path llc = FindExecutable("llc", argv[0]);
552 return PrintAndReturn("Failed to find llc");
554 sys::Path gcc = FindExecutable("gcc", argv[0]);
556 return PrintAndReturn("Failed to find gcc");
558 // Generate an assembly language file for the bytecode.
559 if (Verbose) llvm_cout << "Generating Assembly Code\n";
561 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
563 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
567 if (Verbose) llvm_cout << "Generating Native Code\n";
568 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
569 LinkItems,gcc,envp,ErrMsg)) {
570 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
574 // Remove the assembly language file.
575 AssemblyFile.eraseFromDisk();
576 } else if (NativeCBE) {
577 sys::Path CFile (OutputFilename);
578 CFile.appendSuffix("cbe.c");
580 // Mark the output files for removal if we get an interrupt.
581 sys::RemoveFileOnSignal(CFile);
582 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
584 // Determine the locations of the llc and gcc programs.
585 sys::Path llc = FindExecutable("llc", argv[0]);
587 return PrintAndReturn("Failed to find llc");
589 sys::Path gcc = FindExecutable("gcc", argv[0]);
591 return PrintAndReturn("Failed to find gcc");
593 // Generate an assembly language file for the bytecode.
594 if (Verbose) llvm_cout << "Generating Assembly Code\n";
596 if (0 != GenerateCFile(
597 CFile.toString(), RealBytecodeOutput, llc, ErrMsg)) {
598 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
602 if (Verbose) llvm_cout << "Generating Native Code\n";
603 if (0 != GenerateNative(OutputFilename, CFile.toString(), LinkItems,
604 gcc, envp, ErrMsg)) {
605 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
609 // Remove the assembly language file.
610 CFile.eraseFromDisk();
613 EmitShellScript(argv);
616 // Make the script executable...
618 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
619 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
623 // Make the bytecode file readable and directly executable in LLEE as well
624 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
625 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
628 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
629 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
635 } catch (const std::string& msg) {
636 llvm_cerr << argv[0] << ": " << msg << "\n";
638 llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";