1 //===- gccld.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 //===----------------------------------------------------------------------===//
24 #include "llvm/Module.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Bytecode/Reader.h"
27 #include "llvm/Bytecode/WriteBytecodePass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Support/Linker.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/System/Signals.h"
35 #include "llvm/Support/SystemUtils.h"
42 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
46 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
47 cl::value_desc("filename"));
50 Verbose("v", cl::desc("Print information about actions taken"));
53 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
54 cl::value_desc("directory"));
57 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
58 cl::value_desc("library prefix"));
61 Strip("s", cl::desc("Strip symbol info from executable"));
64 NoInternalize("disable-internalize",
65 cl::desc("Do not mark all symbols as internal"));
67 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
68 cl::aliasopt(NoInternalize));
71 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
72 " library, not an executable"));
74 Relink("r", cl::desc("Alias for -link-as-library"),
75 cl::aliasopt(LinkAsLibrary));
79 cl::desc("Generate a native binary instead of a shell script"));
81 NativeCBE("native-cbe",
82 cl::desc("Generate a native binary with the C backend and GCC"));
84 // Compatibility options that are ignored but supported by LD
86 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
88 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
90 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
92 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
95 /// PrintAndReturn - Prints a message to standard error and returns true.
98 /// progname - The name of the program (i.e. argv[0]).
99 /// Message - The message to print to standard error.
101 static int PrintAndReturn(const char *progname, const std::string &Message) {
102 std::cerr << progname << ": " << Message << "\n";
106 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
107 /// bytecode file for the program.
108 static void EmitShellScript(char **argv) {
109 #if defined(_WIN32) || defined(__CYGWIN__)
110 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
111 // support windows systems, we copy the llvm-stub.exe executable from the
112 // build tree to the destination file.
113 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
114 if (llvmstub.empty()) {
115 std::cerr << "Could not find llvm-stub.exe executable!\n";
118 if (CopyFile(OutputFilename, llvmstub)) {
119 std::cerr << "Could not copy the llvm-stub.exe executable!\n";
125 // Output the script to start the program...
126 std::ofstream Out2(OutputFilename.c_str());
128 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
131 Out2 << "#!/bin/sh\n";
132 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
133 Out2 << "lli=${LLVMINTERP-lli}\n";
134 Out2 << "exec $lli \\\n";
135 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
136 LibPaths.push_back("/lib");
137 LibPaths.push_back("/usr/lib");
138 LibPaths.push_back("/usr/X11R6/lib");
139 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
140 // shared object at all! See RH 8: plain text.
141 std::vector<std::string>::iterator libc =
142 std::find(Libraries.begin(), Libraries.end(), "c");
143 if (libc != Libraries.end()) Libraries.erase(libc);
144 // List all the shared object (native) libraries this executable will need
145 // on the command line, so that we don't have to do this manually!
146 for (std::vector<std::string>::iterator i = Libraries.begin(),
147 e = Libraries.end(); i != e; ++i) {
148 std::string FullLibraryPath = FindLib(*i, LibPaths, true);
149 if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
150 Out2 << " -load=" << FullLibraryPath << " \\\n";
152 Out2 << " $0.bc ${1+\"$@\"}\n";
156 int main(int argc, char **argv, char **envp) {
157 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
158 sys::PrintStackTraceOnErrorSignal();
160 std::string ModuleID("gccld-output");
161 std::auto_ptr<Module> Composite(new Module(ModuleID));
163 // We always look first in the current directory when searching for libraries.
164 LibPaths.insert(LibPaths.begin(), ".");
166 // If the user specified an extra search path in their environment, respect
168 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
169 LibPaths.push_back(SearchPath);
171 // Remove any consecutive duplicates of the same library...
172 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
175 // Link in all of the files
176 if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
177 return 1; // Error already printed
180 LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
183 // Link in all of the libraries next...
185 // Create the output file.
186 std::string RealBytecodeOutput = OutputFilename;
187 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
188 std::ofstream Out(RealBytecodeOutput.c_str());
190 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
193 // Ensure that the bytecode file gets removed from the disk if we get a
195 sys::RemoveFileOnSignal(RealBytecodeOutput);
197 // Generate the bytecode file.
198 if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
200 return PrintAndReturn(argv[0], "error generating bytecode");
203 // Close the bytecode file.
206 // If we are not linking a library, generate either a native executable
207 // or a JIT shell script, depending upon what the user wants.
208 if (!LinkAsLibrary) {
209 // If the user wants to generate a native executable, compile it from the
212 // Otherwise, create a script that will run the bytecode through the JIT.
214 // Name of the Assembly Language output file
215 std::string AssemblyFile = OutputFilename + ".s";
217 // Mark the output files for removal if we get an interrupt.
218 sys::RemoveFileOnSignal(AssemblyFile);
219 sys::RemoveFileOnSignal(OutputFilename);
221 // Determine the locations of the llc and gcc programs.
222 std::string llc = FindExecutable("llc", argv[0]);
223 std::string gcc = FindExecutable("gcc", argv[0]);
225 return PrintAndReturn(argv[0], "Failed to find llc");
228 return PrintAndReturn(argv[0], "Failed to find gcc");
230 // Generate an assembly language file for the bytecode.
231 if (Verbose) std::cout << "Generating Assembly Code\n";
232 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
233 if (Verbose) std::cout << "Generating Native Code\n";
234 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
237 // Remove the assembly language file.
238 removeFile (AssemblyFile);
239 } else if (NativeCBE) {
240 std::string CFile = OutputFilename + ".cbe.c";
242 // Mark the output files for removal if we get an interrupt.
243 sys::RemoveFileOnSignal(CFile);
244 sys::RemoveFileOnSignal(OutputFilename);
246 // Determine the locations of the llc and gcc programs.
247 std::string llc = FindExecutable("llc", argv[0]);
248 std::string gcc = FindExecutable("gcc", argv[0]);
250 return PrintAndReturn(argv[0], "Failed to find llc");
252 return PrintAndReturn(argv[0], "Failed to find gcc");
254 // Generate an assembly language file for the bytecode.
255 if (Verbose) std::cout << "Generating Assembly Code\n";
256 GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
257 if (Verbose) std::cout << "Generating Native Code\n";
258 GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
260 // Remove the assembly language file.
264 EmitShellScript(argv);
267 // Make the script executable...
268 MakeFileExecutable(OutputFilename);
270 // Make the bytecode file readable and directly executable in LLEE as well
271 MakeFileExecutable(RealBytecodeOutput);
272 MakeFileReadable(RealBytecodeOutput);