1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Linker.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/Passes.h"
27 #include "llvm/Bitcode/ReaderWriter.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/StandardPasses.h"
41 #include "llvm/Support/SystemUtils.h"
42 #include "llvm/Support/ToolOutputFile.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/system_error.h"
47 #include "llvm/Config/config.h"
55 static cl::opt<bool> DisableInline("disable-inlining",
56 cl::desc("Do not run the inliner pass"));
59 const char* LTOCodeGenerator::getVersionString()
61 #ifdef LLVM_VERSION_INFO
62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
64 return PACKAGE_NAME " version " PACKAGE_VERSION;
69 LTOCodeGenerator::LTOCodeGenerator()
70 : _context(getGlobalContext()),
71 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
72 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
73 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
74 _nativeObjectFile(NULL)
76 InitializeAllTargets();
77 InitializeAllAsmPrinters();
80 LTOCodeGenerator::~LTOCodeGenerator()
83 delete _nativeObjectFile;
88 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
91 if(mod->getLLVVMModule()->MaterializeAllPermanently(&errMsg))
94 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
96 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
97 for (int i = 0, e = undefs.size(); i != e; ++i)
98 _asmUndefinedRefs[undefs[i]] = 1;
104 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
107 case LTO_DEBUG_MODEL_NONE:
108 _emitDwarfDebugInfo = false;
111 case LTO_DEBUG_MODEL_DWARF:
112 _emitDwarfDebugInfo = true;
115 errMsg = "unknown debug format";
120 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
124 case LTO_CODEGEN_PIC_MODEL_STATIC:
125 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
126 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
130 errMsg = "unknown pic model";
134 void LTOCodeGenerator::setCpu(const char* mCpu)
139 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
141 _mustPreserveSymbols[sym] = 1;
145 bool LTOCodeGenerator::writeMergedModules(const char *path,
146 std::string &errMsg) {
147 if (determineTarget(errMsg))
150 // mark which symbols can not be internalized
151 applyScopeRestrictions();
153 // create output file
155 tool_output_file Out(path, ErrInfo,
156 raw_fd_ostream::F_Binary);
157 if (!ErrInfo.empty()) {
158 errMsg = "could not open bitcode file for writing: ";
163 // write bitcode to it
164 WriteBitcodeToFile(_linker.getModule(), Out.os());
167 if (Out.os().has_error()) {
168 errMsg = "could not write bitcode file: ";
170 Out.os().clear_error();
179 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
181 // make unique temp .o file to put generated object file
182 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
183 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
184 uniqueObjPath.eraseFromDisk();
187 sys::RemoveFileOnSignal(uniqueObjPath);
189 // generate object file
190 bool genResult = false;
191 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
194 genResult = this->generateObjectFile(objFile.os(), errMsg);
195 objFile.os().close();
196 if (objFile.os().has_error()) {
197 objFile.os().clear_error();
202 uniqueObjPath.eraseFromDisk();
206 const std::string& uniqueObjStr = uniqueObjPath.str();
207 // remove old buffer if compile() called twice
208 delete _nativeObjectFile;
210 // read .o file into memory buffer
211 OwningPtr<MemoryBuffer> BuffPtr;
212 if (error_code ec = MemoryBuffer::getFile(uniqueObjStr.c_str(), BuffPtr,
214 errMsg = ec.message();
217 _nativeObjectFile = BuffPtr.take();
220 uniqueObjPath.eraseFromDisk();
222 // return buffer, unless error
223 if ( _nativeObjectFile == NULL )
225 *length = _nativeObjectFile->getBufferSize();
226 return _nativeObjectFile->getBufferStart();
229 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
231 if ( _target == NULL ) {
232 std::string Triple = _linker.getModule()->getTargetTriple();
234 Triple = sys::getHostTriple();
236 // create target machine from info for merged modules
237 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
241 // The relocation model is actually a static member of TargetMachine
242 // and needs to be set before the TargetMachine is instantiated.
243 switch( _codeModel ) {
244 case LTO_CODEGEN_PIC_MODEL_STATIC:
245 TargetMachine::setRelocationModel(Reloc::Static);
247 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
248 TargetMachine::setRelocationModel(Reloc::PIC_);
250 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
251 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
255 // construct LTModule, hand over ownership of module and target
256 SubtargetFeatures Features;
257 Features.getDefaultSubtargetFeatures(_mCpu, llvm::Triple(Triple));
258 std::string FeatureStr = Features.getString();
259 _target = march->createTargetMachine(Triple, FeatureStr);
264 void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
265 std::vector<const char*> &mustPreserveList,
266 SmallPtrSet<GlobalValue*, 8> &asmUsed,
268 SmallString<64> Buffer;
269 mangler.getNameWithPrefix(Buffer, &GV, false);
271 if (GV.isDeclaration())
273 if (_mustPreserveSymbols.count(Buffer))
274 mustPreserveList.push_back(GV.getName().data());
275 if (_asmUndefinedRefs.count(Buffer))
279 static void findUsedValues(GlobalVariable *LLVMUsed,
280 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
281 if (LLVMUsed == 0) return;
283 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
284 if (Inits == 0) return;
286 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
287 if (GlobalValue *GV =
288 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
289 UsedValues.insert(GV);
292 void LTOCodeGenerator::applyScopeRestrictions() {
293 if (_scopeRestrictionsDone) return;
294 Module *mergedModule = _linker.getModule();
296 // Start off with a verification pass.
298 passes.add(createVerifierPass());
300 // mark which symbols can not be internalized
301 MCContext Context(*_target->getMCAsmInfo(), NULL);
302 Mangler mangler(Context, *_target->getTargetData());
303 std::vector<const char*> mustPreserveList;
304 SmallPtrSet<GlobalValue*, 8> asmUsed;
306 for (Module::iterator f = mergedModule->begin(),
307 e = mergedModule->end(); f != e; ++f)
308 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
309 for (Module::global_iterator v = mergedModule->global_begin(),
310 e = mergedModule->global_end(); v != e; ++v)
311 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
312 for (Module::alias_iterator a = mergedModule->alias_begin(),
313 e = mergedModule->alias_end(); a != e; ++a)
314 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
316 GlobalVariable *LLVMCompilerUsed =
317 mergedModule->getGlobalVariable("llvm.compiler.used");
318 findUsedValues(LLVMCompilerUsed, asmUsed);
319 if (LLVMCompilerUsed)
320 LLVMCompilerUsed->eraseFromParent();
322 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
323 std::vector<Constant*> asmUsed2;
324 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
325 e = asmUsed.end(); i !=e; ++i) {
326 GlobalValue *GV = *i;
327 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
328 asmUsed2.push_back(c);
331 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
333 new llvm::GlobalVariable(*mergedModule, ATy, false,
334 llvm::GlobalValue::AppendingLinkage,
335 llvm::ConstantArray::get(ATy, asmUsed2),
336 "llvm.compiler.used");
338 LLVMCompilerUsed->setSection("llvm.metadata");
340 passes.add(createInternalizePass(mustPreserveList));
342 // apply scope restrictions
343 passes.run(*mergedModule);
345 _scopeRestrictionsDone = true;
348 /// Optimize merged modules using various IPO passes
349 bool LTOCodeGenerator::generateObjectFile(raw_ostream& out,
352 if ( this->determineTarget(errMsg) )
355 // mark which symbols can not be internalized
356 this->applyScopeRestrictions();
358 Module* mergedModule = _linker.getModule();
360 // if options were requested, set them
361 if ( !_codegenOptions.empty() )
362 cl::ParseCommandLineOptions(_codegenOptions.size(),
363 const_cast<char **>(&_codegenOptions[0]));
365 // Instantiate the pass manager to organize the passes.
368 // Start off with a verification pass.
369 passes.add(createVerifierPass());
371 // Add an appropriate TargetData instance for this module...
372 passes.add(new TargetData(*_target->getTargetData()));
374 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
375 /*VerifyEach=*/ false);
377 // Make sure everything is still good.
378 passes.add(createVerifierPass());
380 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
382 codeGenPasses->add(new TargetData(*_target->getTargetData()));
384 formatted_raw_ostream Out(out);
386 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
387 TargetMachine::CGFT_ObjectFile,
388 CodeGenOpt::Aggressive)) {
389 errMsg = "target file type not supported";
393 // Run our queue of passes all at once now, efficiently.
394 passes.run(*mergedModule);
396 // Run the code generator, and write assembly file
397 codeGenPasses->doInitialization();
399 for (Module::iterator
400 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
401 if (!it->isDeclaration())
402 codeGenPasses->run(*it);
404 codeGenPasses->doFinalization();
405 delete codeGenPasses;
407 return false; // success
411 /// Optimize merged modules using various IPO passes
412 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
414 for (std::pair<StringRef, StringRef> o = getToken(options);
415 !o.first.empty(); o = getToken(o.second)) {
416 // ParseCommandLineOptions() expects argv[0] to be program name.
418 if ( _codegenOptions.empty() )
419 _codegenOptions.push_back("libLTO");
420 _codegenOptions.push_back(strdup(o.first.str().c_str()));