LTOCodeGenerator.cpp revision 0e6a052331f674dd70e28af41f654a7874405eab
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/Bitcode/ReaderWriter.h" 27#include "llvm/MC/MCAsmInfo.h" 28#include "llvm/MC/MCContext.h" 29#include "llvm/MC/SubtargetFeature.h" 30#include "llvm/Target/Mangler.h" 31#include "llvm/Target/TargetOptions.h" 32#include "llvm/Target/TargetData.h" 33#include "llvm/Target/TargetMachine.h" 34#include "llvm/Target/TargetRegisterInfo.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/PassManagerBuilder.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" 48#include <cstdlib> 49#include <unistd.h> 50#include <fcntl.h> 51 52 53using namespace llvm; 54 55static cl::opt<bool> DisableInline("disable-inlining", 56 cl::desc("Do not run the inliner pass")); 57 58 59const char* LTOCodeGenerator::getVersionString() 60{ 61#ifdef LLVM_VERSION_INFO 62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; 63#else 64 return PACKAGE_NAME " version " PACKAGE_VERSION; 65#endif 66} 67 68 69LTOCodeGenerator::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) 75{ 76 InitializeAllTargets(); 77 InitializeAllMCAsmInfos(); 78 InitializeAllMCRegisterInfos(); 79 InitializeAllMCSubtargetInfos(); 80 InitializeAllAsmPrinters(); 81} 82 83LTOCodeGenerator::~LTOCodeGenerator() 84{ 85 delete _target; 86 delete _nativeObjectFile; 87} 88 89 90 91bool 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 107bool 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 123bool 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 137void LTOCodeGenerator::setCpu(const char* mCpu) 138{ 139 _mCpu = mCpu; 140} 141 142void LTOCodeGenerator::addMustPreserveSymbol(const char* sym) 143{ 144 _mustPreserveSymbols[sym] = 1; 145} 146 147 148bool 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 182bool 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 NULL; 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 214const 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 241bool 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 switch( _codeModel ) { 256 case LTO_CODEGEN_PIC_MODEL_STATIC: 257 TargetMachine::setRelocationModel(Reloc::Static); 258 break; 259 case LTO_CODEGEN_PIC_MODEL_DYNAMIC: 260 TargetMachine::setRelocationModel(Reloc::PIC_); 261 break; 262 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC: 263 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC); 264 break; 265 } 266 267 // construct LTModule, hand over ownership of module and target 268 SubtargetFeatures Features; 269 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple)); 270 std::string FeatureStr = Features.getString(); 271 _target = march->createTargetMachine(Triple, _mCpu, FeatureStr); 272 } 273 return false; 274} 275 276void LTOCodeGenerator::applyRestriction(GlobalValue &GV, 277 std::vector<const char*> &mustPreserveList, 278 SmallPtrSet<GlobalValue*, 8> &asmUsed, 279 Mangler &mangler) { 280 SmallString<64> Buffer; 281 mangler.getNameWithPrefix(Buffer, &GV, false); 282 283 if (GV.isDeclaration()) 284 return; 285 if (_mustPreserveSymbols.count(Buffer)) 286 mustPreserveList.push_back(GV.getName().data()); 287 if (_asmUndefinedRefs.count(Buffer)) 288 asmUsed.insert(&GV); 289} 290 291static void findUsedValues(GlobalVariable *LLVMUsed, 292 SmallPtrSet<GlobalValue*, 8> &UsedValues) { 293 if (LLVMUsed == 0) return; 294 295 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer()); 296 if (Inits == 0) return; 297 298 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) 299 if (GlobalValue *GV = 300 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) 301 UsedValues.insert(GV); 302} 303 304void LTOCodeGenerator::applyScopeRestrictions() { 305 if (_scopeRestrictionsDone) return; 306 Module *mergedModule = _linker.getModule(); 307 308 // Start off with a verification pass. 309 PassManager passes; 310 passes.add(createVerifierPass()); 311 312 // mark which symbols can not be internalized 313 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), 314 NULL); 315 Mangler mangler(Context, *_target->getTargetData()); 316 std::vector<const char*> mustPreserveList; 317 SmallPtrSet<GlobalValue*, 8> asmUsed; 318 319 for (Module::iterator f = mergedModule->begin(), 320 e = mergedModule->end(); f != e; ++f) 321 applyRestriction(*f, mustPreserveList, asmUsed, mangler); 322 for (Module::global_iterator v = mergedModule->global_begin(), 323 e = mergedModule->global_end(); v != e; ++v) 324 applyRestriction(*v, mustPreserveList, asmUsed, mangler); 325 for (Module::alias_iterator a = mergedModule->alias_begin(), 326 e = mergedModule->alias_end(); a != e; ++a) 327 applyRestriction(*a, mustPreserveList, asmUsed, mangler); 328 329 GlobalVariable *LLVMCompilerUsed = 330 mergedModule->getGlobalVariable("llvm.compiler.used"); 331 findUsedValues(LLVMCompilerUsed, asmUsed); 332 if (LLVMCompilerUsed) 333 LLVMCompilerUsed->eraseFromParent(); 334 335 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context); 336 std::vector<Constant*> asmUsed2; 337 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(), 338 e = asmUsed.end(); i !=e; ++i) { 339 GlobalValue *GV = *i; 340 Constant *c = ConstantExpr::getBitCast(GV, i8PTy); 341 asmUsed2.push_back(c); 342 } 343 344 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size()); 345 LLVMCompilerUsed = 346 new llvm::GlobalVariable(*mergedModule, ATy, false, 347 llvm::GlobalValue::AppendingLinkage, 348 llvm::ConstantArray::get(ATy, asmUsed2), 349 "llvm.compiler.used"); 350 351 LLVMCompilerUsed->setSection("llvm.metadata"); 352 353 passes.add(createInternalizePass(mustPreserveList)); 354 355 // apply scope restrictions 356 passes.run(*mergedModule); 357 358 _scopeRestrictionsDone = true; 359} 360 361/// Optimize merged modules using various IPO passes 362bool LTOCodeGenerator::generateObjectFile(raw_ostream &out, 363 std::string &errMsg) { 364 if ( this->determineTarget(errMsg) ) 365 return true; 366 367 // mark which symbols can not be internalized 368 this->applyScopeRestrictions(); 369 370 Module* mergedModule = _linker.getModule(); 371 372 // if options were requested, set them 373 if ( !_codegenOptions.empty() ) 374 cl::ParseCommandLineOptions(_codegenOptions.size(), 375 const_cast<char **>(&_codegenOptions[0])); 376 377 // Instantiate the pass manager to organize the passes. 378 PassManager passes; 379 380 // Start off with a verification pass. 381 passes.add(createVerifierPass()); 382 383 // Add an appropriate TargetData instance for this module... 384 passes.add(new TargetData(*_target->getTargetData())); 385 386 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false, 387 !DisableInline); 388 389 // Make sure everything is still good. 390 passes.add(createVerifierPass()); 391 392 FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule); 393 394 codeGenPasses->add(new TargetData(*_target->getTargetData())); 395 396 formatted_raw_ostream Out(out); 397 398 if (_target->addPassesToEmitFile(*codeGenPasses, Out, 399 TargetMachine::CGFT_ObjectFile, 400 CodeGenOpt::Aggressive)) { 401 errMsg = "target file type not supported"; 402 return true; 403 } 404 405 // Run our queue of passes all at once now, efficiently. 406 passes.run(*mergedModule); 407 408 // Run the code generator, and write assembly file 409 codeGenPasses->doInitialization(); 410 411 for (Module::iterator 412 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it) 413 if (!it->isDeclaration()) 414 codeGenPasses->run(*it); 415 416 codeGenPasses->doFinalization(); 417 delete codeGenPasses; 418 419 return false; // success 420} 421 422 423/// Optimize merged modules using various IPO passes 424void LTOCodeGenerator::setCodeGenDebugOptions(const char* options) 425{ 426 for (std::pair<StringRef, StringRef> o = getToken(options); 427 !o.first.empty(); o = getToken(o.second)) { 428 // ParseCommandLineOptions() expects argv[0] to be program name. 429 // Lazily add that. 430 if ( _codegenOptions.empty() ) 431 _codegenOptions.push_back("libLTO"); 432 _codegenOptions.push_back(strdup(o.first.str().c_str())); 433 } 434} 435