a53383cfb1d92c565e38b8c0a933308877e5c363
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
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
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.
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
23 #include "gccld.h"
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/Transforms/Utils/Linker.h"
32 #include "Support/CommandLine.h"
33 #include "Support/FileUtilities.h"
34 #include "Support/Signals.h"
35 #include "Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38
39 namespace {
40   cl::list<std::string> 
41   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
42                  cl::OneOrMore);
43
44   cl::opt<std::string> 
45   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
46                  cl::value_desc("filename"));
47
48   cl::opt<bool>    
49   Verbose("v", cl::desc("Print information about actions taken"));
50   
51   cl::list<std::string> 
52   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
53            cl::value_desc("directory"));
54
55   cl::list<std::string> 
56   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
57             cl::value_desc("library prefix"));
58
59   cl::opt<bool>
60   Strip("s", cl::desc("Strip symbol info from executable"));
61
62   cl::opt<bool>
63   NoInternalize("disable-internalize",
64                 cl::desc("Do not mark all symbols as internal"));
65   static cl::alias
66   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
67                 cl::aliasopt(NoInternalize));
68
69   cl::opt<bool>
70   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
71                                             " library, not an executable"));
72
73   cl::opt<bool>    
74   Native("native",
75          cl::desc("Generate a native binary instead of a shell script"));
76   
77   // Compatibility options that are ignored but supported by LD
78   cl::opt<std::string>
79   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
80   cl::opt<std::string>
81   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
82   cl::opt<bool>
83   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
84   cl::opt<bool>
85   CO6("r", cl::Hidden, cl::desc("Compatibility option: ignored"));
86 }
87
88 //
89 // Function: PrintAndReturn ()
90 //
91 // Description:
92 //  Prints a message (usually error message) to standard error (stderr) and
93 //  returns a value usable for an exit status.
94 //
95 // Inputs:
96 //  progname - The name of the program (i.e. argv[0]).
97 //  Message  - The message to print to standard error.
98 //  Extra    - Extra information to print between the program name and thei
99 //             message.  It is optional.
100 //
101 // Outputs:
102 //  None.
103 //
104 // Return value:
105 //  Returns a value that can be used as the exit status (i.e. for exit()).
106 //
107 int
108 PrintAndReturn (const char *progname,
109                 const std::string &Message,
110                 const std::string &Extra)
111 {
112   std::cerr << progname << Extra << ": " << Message << "\n";
113   return 1;
114 }
115
116 //
117 //
118 // Function: CopyEnv()
119 //
120 // Description:
121 //      This function takes an array of environment variables and makes a
122 //      copy of it.  This copy can then be manipulated any way the caller likes
123 //  without affecting the process's real environment.
124 //
125 // Inputs:
126 //  envp - An array of C strings containing an environment.
127 //
128 // Outputs:
129 //  None.
130 //
131 // Return value:
132 //  NULL - An error occurred.
133 //
134 //  Otherwise, a pointer to a new array of C strings is returned.  Every string
135 //  in the array is a duplicate of the one in the original array (i.e. we do
136 //  not copy the char *'s from one array to another).
137 //
138 char ** CopyEnv(char ** const envp) {
139   // Count the number of entries in the old list;
140   unsigned entries;   // The number of entries in the old environment list
141   for (entries = 0; envp[entries] != NULL; entries++)
142   {
143     ;
144   }
145
146   // Add one more entry for the NULL pointer that ends the list.
147   ++entries;
148
149   // If there are no entries at all, just return NULL.
150   if (entries == 0)
151     return NULL;
152
153   // Allocate a new environment list.
154   char **newenv;
155   if ((newenv = new (char *) [entries]) == NULL)
156     return NULL;
157
158   // Make a copy of the list.  Don't forget the NULL that ends the list.
159   entries = 0;
160   while (envp[entries] != NULL) {
161     newenv[entries] = new char[strlen (envp[entries]) + 1];
162     strcpy (newenv[entries], envp[entries]);
163     ++entries;
164   }
165   newenv[entries] = NULL;
166
167   return newenv;
168 }
169
170
171 //
172 // Function: RemoveEnv()
173 //
174 // Description:
175 //      Remove the specified environment variable from the environment array.
176 //
177 // Inputs:
178 //      name - The name of the variable to remove.  It cannot be NULL.
179 //      envp - The array of environment variables.  It cannot be NULL.
180 //
181 // Outputs:
182 //      envp - The pointer to the specified variable name is removed.
183 //
184 // Return value:
185 //      None.
186 //
187 // Notes:
188 //  This is mainly done because functions to remove items from the environment
189 //  are not available across all platforms.  In particular, Solaris does not
190 //  seem to have an unsetenv() function or a setenv() function (or they are
191 //  undocumented if they do exist).
192 //
193 void RemoveEnv(const char * name, char ** const envp) {
194   for (unsigned index=0; envp[index] != NULL; index++) {
195     // Find the first equals sign in the array and make it an EOS character.
196     char *p = strchr (envp[index], '=');
197     if (p == NULL)
198       continue;
199     else
200       *p = '\0';
201
202     // Compare the two strings.  If they are equal, zap this string.
203     // Otherwise, restore it.
204     if (!strcmp(name, envp[index]))
205       *envp[index] = '\0';
206     else
207       *p = '=';
208   }
209
210   return;
211 }
212
213
214 int main(int argc, char **argv, char **envp) {
215   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
216
217   std::string ErrorMessage;
218   std::auto_ptr<Module> Composite(LoadObject(InputFilenames[0], ErrorMessage));
219   if (Composite.get() == 0)
220     return PrintAndReturn(argv[0], ErrorMessage);
221
222   // We always look first in the current directory when searching for libraries.
223   LibPaths.insert(LibPaths.begin(), ".");
224
225   // If the user specified an extra search path in their environment, respect
226   // it.
227   if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
228     LibPaths.push_back(SearchPath);
229
230   // Remove any consecutive duplicates of the same library...
231   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
232                   Libraries.end());
233
234   // Link in all of the files
235   if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
236     return 1; // Error already printed
237   LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths, Verbose, Native);
238
239   // Link in all of the libraries next...
240
241   // Create the output file.
242   std::string RealBytecodeOutput = OutputFilename;
243   if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
244   std::ofstream Out(RealBytecodeOutput.c_str());
245   if (!Out.good())
246     return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
247                                    "' for writing!");
248
249   // Ensure that the bytecode file gets removed from the disk if we get a
250   // SIGINT signal.
251   RemoveFileOnSignal(RealBytecodeOutput);
252
253   // Generate the bytecode file.
254   if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
255     Out.close();
256     return PrintAndReturn(argv[0], "error generating bytcode");
257   }
258
259   // Close the bytecode file.
260   Out.close();
261
262   // If we are not linking a library, generate either a native executable
263   // or a JIT shell script, depending upon what the user wants.
264   if (!LinkAsLibrary) {
265     // If the user wants to generate a native executable, compile it from the
266     // bytecode file.
267     //
268     // Otherwise, create a script that will run the bytecode through the JIT.
269     if (Native) {
270       // Name of the Assembly Language output file
271       std::string AssemblyFile = OutputFilename + ".s";
272
273       // Mark the output files for removal if we get an interrupt.
274       RemoveFileOnSignal(AssemblyFile);
275       RemoveFileOnSignal(OutputFilename);
276
277       // Determine the locations of the llc and gcc programs.
278       std::string llc = FindExecutable("llc", argv[0]);
279       std::string gcc = FindExecutable("gcc", argv[0]);
280       if (llc.empty())
281         return PrintAndReturn(argv[0], "Failed to find llc");
282
283       if (gcc.empty())
284         return PrintAndReturn(argv[0], "Failed to find gcc");
285
286       // Generate an assembly language file for the bytecode.
287       if (Verbose) std::cout << "Generating Assembly Code\n";
288       GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
289       if (Verbose) std::cout << "Generating Native Code\n";
290       GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
291                      gcc, envp);
292
293       // Remove the assembly language file.
294       removeFile (AssemblyFile);
295     } else {
296       // Output the script to start the program...
297       std::ofstream Out2(OutputFilename.c_str());
298       if (!Out2.good())
299         return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
300                                        "' for writing!");
301       Out2 << "#!/bin/sh\nlli $0.bc $*\n";
302       Out2.close();
303     }
304   
305     // Make the script executable...
306     MakeFileExecutable(OutputFilename);
307
308     // Make the bytecode file readable and directly executable in LLEE as well
309     MakeFileExecutable(RealBytecodeOutput);
310     MakeFileReadable(RealBytecodeOutput);
311   }
312
313   return 0;
314 }