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/Linker.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/WriteBytecodePass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/IPO.h"
31 #include "llvm/Transforms/Scalar.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("strip-all", cl::desc("Strip all symbol info from executable"));
63 StripDebug("strip-debug",
64 cl::desc("Strip debugger symbol info from executable"));
67 NoInternalize("disable-internalize",
68 cl::desc("Do not mark all symbols as internal"));
70 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71 cl::aliasopt(NoInternalize));
74 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
75 " library, not an executable"));
77 Relink("r", cl::desc("Alias for -link-as-library"),
78 cl::aliasopt(LinkAsLibrary));
82 cl::desc("Generate a native binary instead of a shell script"));
84 NativeCBE("native-cbe",
85 cl::desc("Generate a native binary with the C backend and GCC"));
87 // Compatibility options that are ignored but supported by LD
89 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
91 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
93 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
95 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
97 cl::alias A0("s", cl::desc("Alias for --strip-all"),
99 cl::alias A1("S", cl::desc("Alias for --strip-debug"),
100 cl::aliasopt(StripDebug));
104 /// PrintAndReturn - Prints a message to standard error and returns true.
107 /// progname - The name of the program (i.e. argv[0]).
108 /// Message - The message to print to standard error.
110 static int PrintAndReturn(const char *progname, const std::string &Message) {
111 std::cerr << progname << ": " << Message << "\n";
115 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
116 /// bytecode file for the program.
117 static void EmitShellScript(char **argv) {
118 #if defined(_WIN32) || defined(__CYGWIN__)
119 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
120 // support windows systems, we copy the llvm-stub.exe executable from the
121 // build tree to the destination file.
122 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
123 if (llvmstub.empty()) {
124 std::cerr << "Could not find llvm-stub.exe executable!\n";
127 if (CopyFile(OutputFilename, llvmstub)) {
128 std::cerr << "Could not copy the llvm-stub.exe executable!\n";
134 // Output the script to start the program...
135 std::ofstream Out2(OutputFilename.c_str());
137 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
140 Out2 << "#!/bin/sh\n";
141 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
142 Out2 << "lli=${LLVMINTERP-lli}\n";
143 Out2 << "exec $lli \\\n";
145 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
146 // shared object at all! See RH 8: plain text.
147 std::vector<std::string>::iterator libc =
148 std::find(Libraries.begin(), Libraries.end(), "c");
149 if (libc != Libraries.end()) Libraries.erase(libc);
150 // List all the shared object (native) libraries this executable will need
151 // on the command line, so that we don't have to do this manually!
152 for (std::vector<std::string>::iterator i = Libraries.begin(),
153 e = Libraries.end(); i != e; ++i) {
154 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
155 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
156 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
158 Out2 << " $0.bc ${1+\"$@\"}\n";
162 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
163 // linker function by combining the Files and Libraries in the order they were
164 // declared on the command line.
165 static void BuildLinkItems(
166 Linker::ItemList& Items,
167 const cl::list<std::string>& Files,
168 const cl::list<std::string>& Libraries) {
170 // Build the list of linkage items for LinkItems.
172 cl::list<std::string>::const_iterator fileIt = Files.begin();
173 cl::list<std::string>::const_iterator libIt = Libraries.begin();
175 int libPos = -1, filePos = -1;
177 if (libIt != Libraries.end())
178 libPos = Libraries.getPosition(libIt - Libraries.begin());
181 if (fileIt != Files.end())
182 filePos = Files.getPosition(fileIt - Files.begin());
186 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
188 Items.push_back(std::make_pair(*fileIt++, false));
189 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
191 Items.push_back(std::make_pair(*libIt++, true));
193 break; // we're done with the list
197 int main(int argc, char **argv, char **envp) {
198 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
199 sys::PrintStackTraceOnErrorSignal();
203 std::string ProgName = sys::Path(argv[0]).getBasename();
204 Linker TheLinker(ProgName, Verbose);
207 // Remove any consecutive duplicates of the same library...
208 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
211 TheLinker.addPaths(LibPaths);
212 TheLinker.addSystemPaths();
215 std::vector<sys::Path> Files;
216 for (unsigned i = 0; i < InputFilenames.size(); ++i )
217 Files.push_back(sys::Path(InputFilenames[i]));
219 if (TheLinker.LinkInFiles(Files))
220 return 1; // Error already printed by linker
222 // The libraries aren't linked in but are noted as "dependent" in the
224 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
225 E = Libraries.end(); I != E ; ++I) {
226 TheLinker.getModule()->addLibrary(*I);
230 // Build a list of the items from our command line
231 Linker::ItemList Items;
232 BuildLinkItems(Items, InputFilenames, Libraries);
234 // Link all the items together
235 if (TheLinker.LinkInItems(Items))
236 return 1; // Error already printed
239 // We're done with the Linker, so tell it to release its module
240 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
242 // Create the output file.
243 std::string RealBytecodeOutput = OutputFilename;
244 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
245 std::ofstream Out(RealBytecodeOutput.c_str());
247 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
250 // Ensure that the bytecode file gets removed from the disk if we get a
252 sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
254 // Strip everything if Strip is set, otherwise if stripdebug is set, just
256 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
258 // Internalize the module if neither -disable-internalize nor
259 // -link-as-library are passed in.
260 bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
262 // Generate the bytecode file.
263 if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
265 return PrintAndReturn(argv[0], "error generating bytecode");
268 // Close the bytecode file.
271 // If we are not linking a library, generate either a native executable
272 // or a JIT shell script, depending upon what the user wants.
273 if (!LinkAsLibrary) {
274 // If the user wants to generate a native executable, compile it from the
277 // Otherwise, create a script that will run the bytecode through the JIT.
279 // Name of the Assembly Language output file
280 std::string AssemblyFile = OutputFilename + ".s";
282 // Mark the output files for removal if we get an interrupt.
283 sys::RemoveFileOnSignal(sys::Path(AssemblyFile));
284 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
286 // Determine the locations of the llc and gcc programs.
287 std::string llc = FindExecutable("llc", argv[0]);
288 std::string gcc = FindExecutable("gcc", argv[0]);
290 return PrintAndReturn(argv[0], "Failed to find llc");
293 return PrintAndReturn(argv[0], "Failed to find gcc");
295 // Generate an assembly language file for the bytecode.
296 if (Verbose) std::cout << "Generating Assembly Code\n";
297 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
298 if (Verbose) std::cout << "Generating Native Code\n";
299 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
302 // Remove the assembly language file.
303 removeFile (AssemblyFile);
304 } else if (NativeCBE) {
305 std::string CFile = OutputFilename + ".cbe.c";
307 // Mark the output files for removal if we get an interrupt.
308 sys::RemoveFileOnSignal(sys::Path(CFile));
309 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
311 // Determine the locations of the llc and gcc programs.
312 std::string llc = FindExecutable("llc", argv[0]);
313 std::string gcc = FindExecutable("gcc", argv[0]);
315 return PrintAndReturn(argv[0], "Failed to find llc");
317 return PrintAndReturn(argv[0], "Failed to find gcc");
319 // Generate an assembly language file for the bytecode.
320 if (Verbose) std::cout << "Generating Assembly Code\n";
321 GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
322 if (Verbose) std::cout << "Generating Native Code\n";
323 GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
325 // Remove the assembly language file.
329 EmitShellScript(argv);
332 // Make the script executable...
333 MakeFileExecutable(OutputFilename);
335 // Make the bytecode file readable and directly executable in LLEE as well
336 MakeFileExecutable(RealBytecodeOutput);
337 MakeFileReadable(RealBytecodeOutput);
339 } catch (const char*msg) {
340 std::cerr << argv[0] << ": " << msg << "\n";
342 } catch (const std::string& msg) {
343 std::cerr << argv[0] << ": " << msg << "\n";
346 // This really shouldn't happen, but just in case ....
347 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";