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