46e967aca0c4156485a0662a272db52406532380
[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/ADT/Triple.h"
28 #include "llvm/Analysis/Passes.h"
29 #include "llvm/Analysis/LoopPass.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Bitcode/ReaderWriter.h"
32 #include "llvm/CodeGen/FileWriters.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Program.h"
40 #include "llvm/System/Signals.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/SubtargetFeature.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetRegistry.h"
48 #include "llvm/Target/TargetSelect.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Config/config.h"
52 #include <cstdlib>
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), _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::setAssemblerPath(const char* path)
129 {
130     if ( _assemblerPath )
131         delete _assemblerPath;
132     _assemblerPath = new sys::Path(path);
133 }
134
135 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
136 {
137     _mustPreserveSymbols[sym] = 1;
138 }
139
140
141 bool LTOCodeGenerator::writeMergedModules(const char *path,
142                                           std::string &errMsg) {
143   if (determineTarget(errMsg))
144     return true;
145
146   // mark which symbols can not be internalized 
147   applyScopeRestrictions();
148
149   // create output file
150   std::string ErrInfo;
151   raw_fd_ostream Out(path, ErrInfo,
152                      raw_fd_ostream::F_Binary);
153   if (!ErrInfo.empty()) {
154     errMsg = "could not open bitcode file for writing: ";
155     errMsg += path;
156     return true;
157   }
158     
159   // write bitcode to it
160   WriteBitcodeToFile(_linker.getModule(), Out);
161   
162   if (Out.has_error()) {
163     errMsg = "could not write bitcode file: ";
164     errMsg += path;
165     return true;
166   }
167   
168   return false;
169 }
170
171
172 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
173 {
174     // make unique temp .s file to put generated assembly code
175     sys::Path uniqueAsmPath("lto-llvm.s");
176     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
177         return NULL;
178     sys::RemoveFileOnSignal(uniqueAsmPath);
179        
180     // generate assembly code
181     bool genResult = false;
182     {
183       raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
184       formatted_raw_ostream asmFile(asmFD);
185       if (!errMsg.empty())
186         return NULL;
187       genResult = this->generateAssemblyCode(asmFile, errMsg);
188     }
189     if ( genResult ) {
190         if ( uniqueAsmPath.exists() )
191             uniqueAsmPath.eraseFromDisk();
192         return NULL;
193     }
194     
195     // make unique temp .o file to put generated object file
196     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
197     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
198         if ( uniqueAsmPath.exists() )
199             uniqueAsmPath.eraseFromDisk();
200         return NULL;
201     }
202     sys::RemoveFileOnSignal(uniqueObjPath);
203
204     // assemble the assembly code
205     const std::string& uniqueObjStr = uniqueObjPath.str();
206     bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
207     if ( !asmResult ) {
208         // remove old buffer if compile() called twice
209         delete _nativeObjectFile;
210         
211         // read .o file into memory buffer
212         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
213     }
214
215     // remove temp files
216     uniqueAsmPath.eraseFromDisk();
217     uniqueObjPath.eraseFromDisk();
218
219     // return buffer, unless error
220     if ( _nativeObjectFile == NULL )
221         return NULL;
222     *length = _nativeObjectFile->getBufferSize();
223     return _nativeObjectFile->getBufferStart();
224 }
225
226
227 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
228                                 const std::string& objPath, std::string& errMsg)
229 {
230     sys::Path tool;
231     bool needsCompilerOptions = true;
232     if ( _assemblerPath ) {
233         tool = *_assemblerPath;
234         needsCompilerOptions = false;
235     } else {
236         // find compiler driver
237         tool = sys::Program::FindProgramByName("gcc");
238         if ( tool.isEmpty() ) {
239             errMsg = "can't locate gcc";
240             return true;
241         }
242     }
243
244     // build argument list
245     std::vector<const char*> args;
246     llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
247     const char *arch = targetTriple.getArchNameForAssembler();
248
249     args.push_back(tool.c_str());
250
251     if (targetTriple.getOS() == Triple::Darwin) {
252         // darwin specific command line options
253         if (arch != NULL) {
254             args.push_back("-arch");
255             args.push_back(arch);
256         }
257         // add -static to assembler command line when code model requires
258         if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
259             args.push_back("-static");
260     }
261     if ( needsCompilerOptions ) {
262         args.push_back("-c");
263         args.push_back("-x");
264         args.push_back("assembler");
265     }
266     args.push_back("-o");
267     args.push_back(objPath.c_str());
268     args.push_back(asmPath.c_str());
269     args.push_back(0);
270
271     // invoke assembler
272     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
273         errMsg = "error in assembly";    
274         return true;
275     }
276     return false; // success
277 }
278
279
280
281 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
282 {
283     if ( _target == NULL ) {
284         std::string Triple = _linker.getModule()->getTargetTriple();
285         if (Triple.empty())
286           Triple = sys::getHostTriple();
287
288         // create target machine from info for merged modules
289         const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
290         if ( march == NULL )
291             return true;
292
293         // The relocation model is actually a static member of TargetMachine
294         // and needs to be set before the TargetMachine is instantiated.
295         switch( _codeModel ) {
296         case LTO_CODEGEN_PIC_MODEL_STATIC:
297             TargetMachine::setRelocationModel(Reloc::Static);
298             break;
299         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
300             TargetMachine::setRelocationModel(Reloc::PIC_);
301             break;
302         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
303             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
304             break;
305         }
306
307         // construct LTModule, hand over ownership of module and target
308         const std::string FeatureStr =
309             SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
310         _target = march->createTargetMachine(Triple, FeatureStr);
311     }
312     return false;
313 }
314
315 void LTOCodeGenerator::applyScopeRestrictions()
316 {
317     if ( !_scopeRestrictionsDone ) {
318         Module* mergedModule = _linker.getModule();
319
320         // Start off with a verification pass.
321         PassManager passes;
322         passes.add(createVerifierPass());
323
324         // mark which symbols can not be internalized 
325         if ( !_mustPreserveSymbols.empty() ) {
326             Mangler mangler(*_target->getMCAsmInfo());
327             std::vector<const char*> mustPreserveList;
328             for (Module::iterator f = mergedModule->begin(), 
329                                         e = mergedModule->end(); f != e; ++f) {
330                 if ( !f->isDeclaration() 
331                   && _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)) )
332                   mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
333             }
334             for (Module::global_iterator v = mergedModule->global_begin(), 
335                                  e = mergedModule->global_end(); v !=  e; ++v) {
336                 if ( !v->isDeclaration()
337                   && _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)) )
338                   mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
339             }
340             passes.add(createInternalizePass(mustPreserveList));
341         }
342         // apply scope restrictions
343         passes.run(*mergedModule);
344         
345         _scopeRestrictionsDone = true;
346     }
347 }
348
349 /// Optimize merged modules using various IPO passes
350 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
351                                             std::string& errMsg)
352 {
353     if ( this->determineTarget(errMsg) ) 
354         return true;
355
356     // mark which symbols can not be internalized 
357     this->applyScopeRestrictions();
358
359     Module* mergedModule = _linker.getModule();
360
361     // If target supports exception handling then enable it now.
362     switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
363     case ExceptionHandling::Dwarf:
364       llvm::DwarfExceptionHandling = true;
365       break;
366     case ExceptionHandling::SjLj:
367       llvm::SjLjExceptionHandling = true;
368       break;
369     case ExceptionHandling::None:
370       break;
371     default:
372       assert (0 && "Unknown exception handling model!");
373     }
374
375     // if options were requested, set them
376     if ( !_codegenOptions.empty() )
377         cl::ParseCommandLineOptions(_codegenOptions.size(), 
378                                                 (char**)&_codegenOptions[0]);
379
380     // Instantiate the pass manager to organize the passes.
381     PassManager passes;
382
383     // Start off with a verification pass.
384     passes.add(createVerifierPass());
385
386     // Add an appropriate TargetData instance for this module...
387     passes.add(new TargetData(*_target->getTargetData()));
388     
389     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
390                             /*VerifyEach=*/ false);
391
392     // Make sure everything is still good.
393     passes.add(createVerifierPass());
394
395     FunctionPassManager* codeGenPasses =
396             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
397
398     codeGenPasses->add(new TargetData(*_target->getTargetData()));
399
400     ObjectCodeEmitter* oce = NULL;
401
402     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
403                                          TargetMachine::AssemblyFile,
404                                          CodeGenOpt::Aggressive)) {
405         case FileModel::ElfFile:
406             oce = AddELFWriter(*codeGenPasses, out, *_target);
407             break;
408         case FileModel::AsmFile:
409             break;
410         case FileModel::MachOFile:
411         case FileModel::Error:
412         case FileModel::None:
413             errMsg = "target file type not supported";
414             return true;
415     }
416
417     if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
418                                            CodeGenOpt::Aggressive)) {
419         errMsg = "target does not support generation of this file type";
420         return true;
421     }
422
423     // Run our queue of passes all at once now, efficiently.
424     passes.run(*mergedModule);
425
426     // Run the code generator, and write assembly file
427     codeGenPasses->doInitialization();
428
429     for (Module::iterator
430            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
431       if (!it->isDeclaration())
432         codeGenPasses->run(*it);
433
434     codeGenPasses->doFinalization();
435
436     return false; // success
437 }
438
439
440 /// Optimize merged modules using various IPO passes
441 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
442 {
443     for (std::pair<StringRef, StringRef> o = getToken(options);
444          !o.first.empty(); o = getToken(o.second)) {
445         // ParseCommandLineOptions() expects argv[0] to be program name.
446         // Lazily add that.
447         if ( _codegenOptions.empty() ) 
448             _codegenOptions.push_back("libLTO");
449         _codegenOptions.push_back(strdup(o.first.str().c_str()));
450     }
451 }