a5023fb2f4fa6b2431cd14ebafeb21b1c1c3c028
[oota-llvm.git] / tools / lto / LTOCodeGenerator.cpp
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is 
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.h"
17
18
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Linker.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/Passes.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include "llvm/Bitcode/ReaderWriter.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Signals.h"
39 #include "llvm/Target/SubtargetFeature.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Config/config.h"
49
50
51 #include <cstdlib>
52 #include <fstream>
53 #include <unistd.h>
54 #include <fcntl.h>
55
56
57 using namespace llvm;
58
59 static cl::opt<bool> DisableInline("disable-inlining",
60   cl::desc("Do not run the inliner pass"));
61
62
63 const char* LTOCodeGenerator::getVersionString()
64 {
65 #ifdef LLVM_VERSION_INFO
66     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68     return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71
72
73 LTOCodeGenerator::LTOCodeGenerator() 
74     : _context(getGlobalContext()),
75       _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
76       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
77       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
78       _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
79 {
80     InitializeAllTargets();
81     InitializeAllAsmPrinters();
82 }
83
84 LTOCodeGenerator::~LTOCodeGenerator()
85 {
86     delete _target;
87     delete _nativeObjectFile;
88 }
89
90
91
92 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
93 {
94     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
95 }
96     
97
98 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
99 {
100     switch (debug) {
101         case LTO_DEBUG_MODEL_NONE:
102             _emitDwarfDebugInfo = false;
103             return false;
104             
105         case LTO_DEBUG_MODEL_DWARF:
106             _emitDwarfDebugInfo = true;
107             return false;
108     }
109     errMsg = "unknown debug format";
110     return true;
111 }
112
113
114 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
115                                        std::string& errMsg)
116 {
117     switch (model) {
118         case LTO_CODEGEN_PIC_MODEL_STATIC:
119         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
120         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
121             _codeModel = model;
122             return false;
123     }
124     errMsg = "unknown pic model";
125     return true;
126 }
127
128 void LTOCodeGenerator::setGccPath(const char* path)
129 {
130     if ( _gccPath )
131         delete _gccPath;
132     _gccPath = new sys::Path(path);
133 }
134
135 void LTOCodeGenerator::setAssemblerPath(const char* path)
136 {
137     if ( _assemblerPath )
138         delete _assemblerPath;
139     _assemblerPath = new sys::Path(path);
140 }
141
142 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
143 {
144     _mustPreserveSymbols[sym] = 1;
145 }
146
147
148 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
149 {
150     if ( this->determineTarget(errMsg) ) 
151         return true;
152
153     // mark which symbols can not be internalized 
154     this->applyScopeRestrictions();
155
156     // create output file
157     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
158     if ( out.fail() ) {
159         errMsg = "could not open bitcode file for writing: ";
160         errMsg += path;
161         return true;
162     }
163     
164     // write bitcode to it
165     WriteBitcodeToFile(_linker.getModule(), out);
166     if ( out.fail() ) {
167         errMsg = "could not write bitcode file: ";
168         errMsg += path;
169         return true;
170     }
171     
172     return false;
173 }
174
175
176 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
177 {
178     // make unique temp .s file to put generated assembly code
179     sys::Path uniqueAsmPath("lto-llvm.s");
180     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
181         return NULL;
182     sys::RemoveFileOnSignal(uniqueAsmPath);
183        
184     // generate assembly code
185     bool genResult = false;
186     {
187       raw_fd_ostream asmFD(raw_fd_ostream(uniqueAsmPath.c_str(),
188                                           /*Binary=*/false, /*Force=*/true,
189                                           errMsg));
190       formatted_raw_ostream asmFile(asmFD);
191       if (!errMsg.empty())
192         return NULL;
193       genResult = this->generateAssemblyCode(asmFile, errMsg);
194     }
195     if ( genResult ) {
196         if ( uniqueAsmPath.exists() )
197             uniqueAsmPath.eraseFromDisk();
198         return NULL;
199     }
200     
201     // make unique temp .o file to put generated object file
202     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
203     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
204         if ( uniqueAsmPath.exists() )
205             uniqueAsmPath.eraseFromDisk();
206         return NULL;
207     }
208     sys::RemoveFileOnSignal(uniqueObjPath);
209
210     // assemble the assembly code
211     const std::string& uniqueObjStr = uniqueObjPath.toString();
212     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
213                                                         uniqueObjStr, errMsg);
214     if ( !asmResult ) {
215         // remove old buffer if compile() called twice
216         delete _nativeObjectFile;
217         
218         // read .o file into memory buffer
219         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
220     }
221
222     // remove temp files
223     uniqueAsmPath.eraseFromDisk();
224     uniqueObjPath.eraseFromDisk();
225
226     // return buffer, unless error
227     if ( _nativeObjectFile == NULL )
228         return NULL;
229     *length = _nativeObjectFile->getBufferSize();
230     return _nativeObjectFile->getBufferStart();
231 }
232
233
234 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
235                                 const std::string& objPath, std::string& errMsg)
236 {
237     sys::Path tool;
238     bool needsCompilerOptions = true;
239     if ( _assemblerPath ) {
240         tool = *_assemblerPath;
241         needsCompilerOptions = false;
242     }
243     else if ( _gccPath ) {
244         tool = *_gccPath;
245     } else {
246         // find compiler driver
247         tool = sys::Program::FindProgramByName("gcc");
248         if ( tool.isEmpty() ) {
249             errMsg = "can't locate gcc";
250             return true;
251         }
252     }
253
254     // build argument list
255     std::vector<const char*> args;
256     std::string targetTriple = _linker.getModule()->getTargetTriple();
257     args.push_back(tool.c_str());
258     if ( targetTriple.find("darwin") != std::string::npos ) {
259         // darwin specific command line options
260         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
261             args.push_back("-arch");
262             args.push_back("i386");
263         }
264         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
265             args.push_back("-arch");
266             args.push_back("x86_64");
267         }
268         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
269             args.push_back("-arch");
270             args.push_back("ppc");
271         }
272         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
273             args.push_back("-arch");
274             args.push_back("ppc64");
275         }
276         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
277             args.push_back("-arch");
278             args.push_back("arm");
279         }
280         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
281                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
282             args.push_back("-arch");
283             args.push_back("armv4t");
284         }
285         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
286                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
287                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
288                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
289             args.push_back("-arch");
290             args.push_back("armv5");
291         }
292         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
293                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
294             args.push_back("-arch");
295             args.push_back("armv6");
296         }
297         else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
298                  (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
299             args.push_back("-arch");
300             args.push_back("armv7");
301         }
302         // add -static to assembler command line when code model requires
303         if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
304             args.push_back("-static");
305     }
306     if ( needsCompilerOptions ) {
307         args.push_back("-c");
308         args.push_back("-x");
309         args.push_back("assembler");
310     }
311     args.push_back("-o");
312     args.push_back(objPath.c_str());
313     args.push_back(asmPath.c_str());
314     args.push_back(0);
315
316     // invoke assembler
317     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
318         errMsg = "error in assembly";    
319         return true;
320     }
321     return false; // success
322 }
323
324
325
326 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
327 {
328     if ( _target == NULL ) {
329         // create target machine from info for merged modules
330         Module* mergedModule = _linker.getModule();
331         const Target *march = 
332           TargetRegistry::lookupTarget(mergedModule->getTargetTriple(), 
333                                        /*FallbackToHost=*/true,
334                                        /*RequireJIT=*/false,
335                                        errMsg);
336         if ( march == NULL )
337             return true;
338
339         // The relocation model is actually a static member of TargetMachine
340         // and needs to be set before the TargetMachine is instantiated.
341         switch( _codeModel ) {
342         case LTO_CODEGEN_PIC_MODEL_STATIC:
343             TargetMachine::setRelocationModel(Reloc::Static);
344             break;
345         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
346             TargetMachine::setRelocationModel(Reloc::PIC_);
347             break;
348         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
349             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
350             break;
351         }
352
353         // construct LTModule, hand over ownership of module and target
354         std::string FeatureStr =
355           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
356         _target = march->createTargetMachine(*mergedModule, FeatureStr.c_str());
357     }
358     return false;
359 }
360
361 void LTOCodeGenerator::applyScopeRestrictions()
362 {
363     if ( !_scopeRestrictionsDone ) {
364         Module* mergedModule = _linker.getModule();
365
366         // Start off with a verification pass.
367         PassManager passes;
368         passes.add(createVerifierPass());
369
370         // mark which symbols can not be internalized 
371         if ( !_mustPreserveSymbols.empty() ) {
372             Mangler mangler(*mergedModule, 
373                                 _target->getTargetAsmInfo()->getGlobalPrefix());
374             std::vector<const char*> mustPreserveList;
375             for (Module::iterator f = mergedModule->begin(), 
376                                         e = mergedModule->end(); f != e; ++f) {
377                 if ( !f->isDeclaration() 
378                   && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
379                   mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
380             }
381             for (Module::global_iterator v = mergedModule->global_begin(), 
382                                  e = mergedModule->global_end(); v !=  e; ++v) {
383                 if ( !v->isDeclaration()
384                   && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
385                   mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
386             }
387             passes.add(createInternalizePass(mustPreserveList));
388         }
389         // apply scope restrictions
390         passes.run(*mergedModule);
391         
392         _scopeRestrictionsDone = true;
393     }
394 }
395
396 /// Optimize merged modules using various IPO passes
397 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
398                                             std::string& errMsg)
399 {
400     if ( this->determineTarget(errMsg) ) 
401         return true;
402
403     // mark which symbols can not be internalized 
404     this->applyScopeRestrictions();
405
406     Module* mergedModule = _linker.getModule();
407
408      // If target supports exception handling then enable it now.
409     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
410         llvm::ExceptionHandling = true;
411
412     // if options were requested, set them
413     if ( !_codegenOptions.empty() )
414         cl::ParseCommandLineOptions(_codegenOptions.size(), 
415                                                 (char**)&_codegenOptions[0]);
416
417     // Instantiate the pass manager to organize the passes.
418     PassManager passes;
419
420     // Start off with a verification pass.
421     passes.add(createVerifierPass());
422
423     // Add an appropriate TargetData instance for this module...
424     passes.add(new TargetData(*_target->getTargetData()));
425     
426     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
427                             /*VerifyEach=*/ false);
428
429     // Make sure everything is still good.
430     passes.add(createVerifierPass());
431
432     FunctionPassManager* codeGenPasses =
433             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
434
435     codeGenPasses->add(new TargetData(*_target->getTargetData()));
436
437     ObjectCodeEmitter* oce = NULL;
438
439     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
440                                          TargetMachine::AssemblyFile,
441                                          CodeGenOpt::Aggressive)) {
442         case FileModel::MachOFile:
443             oce = AddMachOWriter(*codeGenPasses, out, *_target);
444             break;
445         case FileModel::ElfFile:
446             oce = AddELFWriter(*codeGenPasses, out, *_target);
447             break;
448         case FileModel::AsmFile:
449             break;
450         case FileModel::Error:
451         case FileModel::None:
452             errMsg = "target file type not supported";
453             return true;
454     }
455
456     if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
457                                            CodeGenOpt::Aggressive)) {
458         errMsg = "target does not support generation of this file type";
459         return true;
460     }
461
462     // Run our queue of passes all at once now, efficiently.
463     passes.run(*mergedModule);
464
465     // Run the code generator, and write assembly file
466     codeGenPasses->doInitialization();
467
468     for (Module::iterator
469            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
470       if (!it->isDeclaration())
471         codeGenPasses->run(*it);
472
473     codeGenPasses->doFinalization();
474
475     out.flush();
476
477     return false; // success
478 }
479
480
481 /// Optimize merged modules using various IPO passes
482 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
483 {
484     std::string ops(options);
485     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
486         // ParseCommandLineOptions() expects argv[0] to be program name.
487         // Lazily add that.
488         if ( _codegenOptions.empty() ) 
489             _codegenOptions.push_back("libLTO");
490         _codegenOptions.push_back(strdup(o.c_str()));
491     }
492 }