• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Linker.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/Passes.h"
26 #include "llvm/Analysis/Verifier.h"
27 #include "llvm/Bitcode/ReaderWriter.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SystemUtils.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/system_error.h"
47 #include "llvm/Config/config.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
50 #include <cstdlib>
51 #include <unistd.h>
52 #include <fcntl.h>
53 
54 
55 using namespace llvm;
56 
57 static cl::opt<bool> DisableInline("disable-inlining",
58   cl::desc("Do not run the inliner pass"));
59 
60 
getVersionString()61 const char* LTOCodeGenerator::getVersionString()
62 {
63 #ifdef LLVM_VERSION_INFO
64     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
65 #else
66     return PACKAGE_NAME " version " PACKAGE_VERSION;
67 #endif
68 }
69 
70 
LTOCodeGenerator()71 LTOCodeGenerator::LTOCodeGenerator()
72     : _context(getGlobalContext()),
73       _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
74       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
75       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
76       _nativeObjectFile(NULL)
77 {
78     InitializeAllTargets();
79     InitializeAllTargetMCs();
80     InitializeAllAsmPrinters();
81 }
82 
~LTOCodeGenerator()83 LTOCodeGenerator::~LTOCodeGenerator()
84 {
85     delete _target;
86     delete _nativeObjectFile;
87 }
88 
89 
90 
addModule(LTOModule * mod,std::string & errMsg)91 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
92 {
93 
94   if(mod->getLLVVMModule()->MaterializeAllPermanently(&errMsg))
95     return true;
96 
97   bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
98 
99   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
100   for (int i = 0, e = undefs.size(); i != e; ++i)
101     _asmUndefinedRefs[undefs[i]] = 1;
102 
103   return ret;
104 }
105 
106 
setDebugInfo(lto_debug_model debug,std::string & errMsg)107 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
108 {
109     switch (debug) {
110         case LTO_DEBUG_MODEL_NONE:
111             _emitDwarfDebugInfo = false;
112             return false;
113 
114         case LTO_DEBUG_MODEL_DWARF:
115             _emitDwarfDebugInfo = true;
116             return false;
117     }
118     errMsg = "unknown debug format";
119     return true;
120 }
121 
122 
setCodePICModel(lto_codegen_model model,std::string & errMsg)123 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
124                                        std::string& errMsg)
125 {
126     switch (model) {
127         case LTO_CODEGEN_PIC_MODEL_STATIC:
128         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
129         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
130             _codeModel = model;
131             return false;
132     }
133     errMsg = "unknown pic model";
134     return true;
135 }
136 
setCpu(const char * mCpu)137 void LTOCodeGenerator::setCpu(const char* mCpu)
138 {
139   _mCpu = mCpu;
140 }
141 
addMustPreserveSymbol(const char * sym)142 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
143 {
144     _mustPreserveSymbols[sym] = 1;
145 }
146 
147 
writeMergedModules(const char * path,std::string & errMsg)148 bool LTOCodeGenerator::writeMergedModules(const char *path,
149                                           std::string &errMsg) {
150   if (determineTarget(errMsg))
151     return true;
152 
153   // mark which symbols can not be internalized
154   applyScopeRestrictions();
155 
156   // create output file
157   std::string ErrInfo;
158   tool_output_file Out(path, ErrInfo,
159                        raw_fd_ostream::F_Binary);
160   if (!ErrInfo.empty()) {
161     errMsg = "could not open bitcode file for writing: ";
162     errMsg += path;
163     return true;
164   }
165 
166   // write bitcode to it
167   WriteBitcodeToFile(_linker.getModule(), Out.os());
168   Out.os().close();
169 
170   if (Out.os().has_error()) {
171     errMsg = "could not write bitcode file: ";
172     errMsg += path;
173     Out.os().clear_error();
174     return true;
175   }
176 
177   Out.keep();
178   return false;
179 }
180 
181 
compile_to_file(const char ** name,std::string & errMsg)182 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg)
183 {
184   // make unique temp .o file to put generated object file
185   sys::PathWithStatus uniqueObjPath("lto-llvm.o");
186   if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
187     uniqueObjPath.eraseFromDisk();
188     return true;
189   }
190   sys::RemoveFileOnSignal(uniqueObjPath);
191 
192   // generate object file
193   bool genResult = false;
194   tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
195   if (!errMsg.empty())
196     return true;
197   genResult = this->generateObjectFile(objFile.os(), errMsg);
198   objFile.os().close();
199   if (objFile.os().has_error()) {
200     objFile.os().clear_error();
201     return true;
202   }
203   objFile.keep();
204   if ( genResult ) {
205     uniqueObjPath.eraseFromDisk();
206     return true;
207   }
208 
209   _nativeObjectPath = uniqueObjPath.str();
210   *name = _nativeObjectPath.c_str();
211   return false;
212 }
213 
compile(size_t * length,std::string & errMsg)214 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
215 {
216   const char *name;
217   if (compile_to_file(&name, errMsg))
218     return NULL;
219 
220   // remove old buffer if compile() called twice
221   delete _nativeObjectFile;
222 
223   // read .o file into memory buffer
224   OwningPtr<MemoryBuffer> BuffPtr;
225   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
226     errMsg = ec.message();
227     return NULL;
228   }
229   _nativeObjectFile = BuffPtr.take();
230 
231   // remove temp files
232   sys::Path(_nativeObjectPath).eraseFromDisk();
233 
234   // return buffer, unless error
235   if ( _nativeObjectFile == NULL )
236     return NULL;
237   *length = _nativeObjectFile->getBufferSize();
238   return _nativeObjectFile->getBufferStart();
239 }
240 
determineTarget(std::string & errMsg)241 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
242 {
243     if ( _target == NULL ) {
244         std::string Triple = _linker.getModule()->getTargetTriple();
245         if (Triple.empty())
246           Triple = sys::getHostTriple();
247 
248         // create target machine from info for merged modules
249         const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
250         if ( march == NULL )
251             return true;
252 
253         // The relocation model is actually a static member of TargetMachine
254         // and needs to be set before the TargetMachine is instantiated.
255         Reloc::Model RelocModel = Reloc::Default;
256         switch( _codeModel ) {
257         case LTO_CODEGEN_PIC_MODEL_STATIC:
258             RelocModel = Reloc::Static;
259             break;
260         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
261             RelocModel = Reloc::PIC_;
262             break;
263         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
264             RelocModel = Reloc::DynamicNoPIC;
265             break;
266         }
267 
268         // construct LTOModule, hand over ownership of module and target
269         SubtargetFeatures Features;
270         Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
271         std::string FeatureStr = Features.getString();
272         _target = march->createTargetMachine(Triple, _mCpu, FeatureStr,
273                                              RelocModel);
274     }
275     return false;
276 }
277 
applyRestriction(GlobalValue & GV,std::vector<const char * > & mustPreserveList,SmallPtrSet<GlobalValue *,8> & asmUsed,Mangler & mangler)278 void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
279                                      std::vector<const char*> &mustPreserveList,
280                                         SmallPtrSet<GlobalValue*, 8> &asmUsed,
281                                         Mangler &mangler) {
282   SmallString<64> Buffer;
283   mangler.getNameWithPrefix(Buffer, &GV, false);
284 
285   if (GV.isDeclaration())
286     return;
287   if (_mustPreserveSymbols.count(Buffer))
288     mustPreserveList.push_back(GV.getName().data());
289   if (_asmUndefinedRefs.count(Buffer))
290     asmUsed.insert(&GV);
291 }
292 
findUsedValues(GlobalVariable * LLVMUsed,SmallPtrSet<GlobalValue *,8> & UsedValues)293 static void findUsedValues(GlobalVariable *LLVMUsed,
294                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
295   if (LLVMUsed == 0) return;
296 
297   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
298   if (Inits == 0) return;
299 
300   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
301     if (GlobalValue *GV =
302           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
303       UsedValues.insert(GV);
304 }
305 
applyScopeRestrictions()306 void LTOCodeGenerator::applyScopeRestrictions() {
307   if (_scopeRestrictionsDone) return;
308   Module *mergedModule = _linker.getModule();
309 
310   // Start off with a verification pass.
311   PassManager passes;
312   passes.add(createVerifierPass());
313 
314   // mark which symbols can not be internalized
315   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL);
316   Mangler mangler(Context, *_target->getTargetData());
317   std::vector<const char*> mustPreserveList;
318   SmallPtrSet<GlobalValue*, 8> asmUsed;
319 
320   for (Module::iterator f = mergedModule->begin(),
321          e = mergedModule->end(); f != e; ++f)
322     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
323   for (Module::global_iterator v = mergedModule->global_begin(),
324          e = mergedModule->global_end(); v !=  e; ++v)
325     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
326   for (Module::alias_iterator a = mergedModule->alias_begin(),
327          e = mergedModule->alias_end(); a != e; ++a)
328     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
329 
330   GlobalVariable *LLVMCompilerUsed =
331     mergedModule->getGlobalVariable("llvm.compiler.used");
332   findUsedValues(LLVMCompilerUsed, asmUsed);
333   if (LLVMCompilerUsed)
334     LLVMCompilerUsed->eraseFromParent();
335 
336   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
337   std::vector<Constant*> asmUsed2;
338   for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
339          e = asmUsed.end(); i !=e; ++i) {
340     GlobalValue *GV = *i;
341     Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
342     asmUsed2.push_back(c);
343   }
344 
345   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
346   LLVMCompilerUsed =
347     new llvm::GlobalVariable(*mergedModule, ATy, false,
348                              llvm::GlobalValue::AppendingLinkage,
349                              llvm::ConstantArray::get(ATy, asmUsed2),
350                              "llvm.compiler.used");
351 
352   LLVMCompilerUsed->setSection("llvm.metadata");
353 
354   passes.add(createInternalizePass(mustPreserveList));
355 
356   // apply scope restrictions
357   passes.run(*mergedModule);
358 
359   _scopeRestrictionsDone = true;
360 }
361 
362 /// Optimize merged modules using various IPO passes
generateObjectFile(raw_ostream & out,std::string & errMsg)363 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
364                                           std::string &errMsg) {
365     if ( this->determineTarget(errMsg) )
366         return true;
367 
368     // mark which symbols can not be internalized
369     this->applyScopeRestrictions();
370 
371     Module* mergedModule = _linker.getModule();
372 
373     // if options were requested, set them
374     if ( !_codegenOptions.empty() )
375         cl::ParseCommandLineOptions(_codegenOptions.size(),
376                                     const_cast<char **>(&_codegenOptions[0]));
377 
378     // Instantiate the pass manager to organize the passes.
379     PassManager passes;
380 
381     // Start off with a verification pass.
382     passes.add(createVerifierPass());
383 
384     // Add an appropriate TargetData instance for this module...
385     passes.add(new TargetData(*_target->getTargetData()));
386 
387     PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false,
388                                                 !DisableInline);
389 
390     // Make sure everything is still good.
391     passes.add(createVerifierPass());
392 
393     FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
394 
395     codeGenPasses->add(new TargetData(*_target->getTargetData()));
396 
397     formatted_raw_ostream Out(out);
398 
399     if (_target->addPassesToEmitFile(*codeGenPasses, Out,
400                                      TargetMachine::CGFT_ObjectFile,
401                                      CodeGenOpt::Aggressive)) {
402       errMsg = "target file type not supported";
403       return true;
404     }
405 
406     // Run our queue of passes all at once now, efficiently.
407     passes.run(*mergedModule);
408 
409     // Run the code generator, and write assembly file
410     codeGenPasses->doInitialization();
411 
412     for (Module::iterator
413            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
414       if (!it->isDeclaration())
415         codeGenPasses->run(*it);
416 
417     codeGenPasses->doFinalization();
418     delete codeGenPasses;
419 
420     return false; // success
421 }
422 
423 
424 /// Optimize merged modules using various IPO passes
setCodeGenDebugOptions(const char * options)425 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
426 {
427     for (std::pair<StringRef, StringRef> o = getToken(options);
428          !o.first.empty(); o = getToken(o.second)) {
429         // ParseCommandLineOptions() expects argv[0] to be program name.
430         // Lazily add that.
431         if ( _codegenOptions.empty() )
432             _codegenOptions.push_back("libLTO");
433         _codegenOptions.push_back(strdup(o.first.str().c_str()));
434     }
435 }
436