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 "llvm/LTO/LTOCodeGenerator.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/Analysis/Passes.h" 18 #include "llvm/Bitcode/ReaderWriter.h" 19 #include "llvm/CodeGen/RuntimeLibcalls.h" 20 #include "llvm/Config/config.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/DiagnosticInfo.h" 25 #include "llvm/IR/DiagnosticPrinter.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/Mangler.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/Verifier.h" 30 #include "llvm/InitializePasses.h" 31 #include "llvm/LTO/LTOModule.h" 32 #include "llvm/Linker/Linker.h" 33 #include "llvm/MC/MCAsmInfo.h" 34 #include "llvm/MC/MCContext.h" 35 #include "llvm/MC/SubtargetFeature.h" 36 #include "llvm/PassManager.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/FormattedStream.h" 40 #include "llvm/Support/Host.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/Signals.h" 43 #include "llvm/Support/TargetRegistry.h" 44 #include "llvm/Support/TargetSelect.h" 45 #include "llvm/Support/ToolOutputFile.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetLibraryInfo.h" 48 #include "llvm/Target/TargetLowering.h" 49 #include "llvm/Target/TargetOptions.h" 50 #include "llvm/Target/TargetRegisterInfo.h" 51 #include "llvm/Transforms/IPO.h" 52 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 53 #include "llvm/Transforms/ObjCARC.h" 54 #include <system_error> 55 using namespace llvm; 56 57 const char* LTOCodeGenerator::getVersionString() { 58 #ifdef LLVM_VERSION_INFO 59 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; 60 #else 61 return PACKAGE_NAME " version " PACKAGE_VERSION; 62 #endif 63 } 64 65 LTOCodeGenerator::LTOCodeGenerator() 66 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)), 67 TargetMach(nullptr), EmitDwarfDebugInfo(false), 68 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT), 69 NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) { 70 initializeLTOPasses(); 71 } 72 73 LTOCodeGenerator::~LTOCodeGenerator() { 74 delete TargetMach; 75 delete NativeObjectFile; 76 TargetMach = nullptr; 77 NativeObjectFile = nullptr; 78 79 IRLinker.deleteModule(); 80 81 for (std::vector<char *>::iterator I = CodegenOptions.begin(), 82 E = CodegenOptions.end(); 83 I != E; ++I) 84 free(*I); 85 } 86 87 // Initialize LTO passes. Please keep this funciton in sync with 88 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO 89 // passes are initialized. 90 void LTOCodeGenerator::initializeLTOPasses() { 91 PassRegistry &R = *PassRegistry::getPassRegistry(); 92 93 initializeInternalizePassPass(R); 94 initializeIPSCCPPass(R); 95 initializeGlobalOptPass(R); 96 initializeConstantMergePass(R); 97 initializeDAHPass(R); 98 initializeInstCombinerPass(R); 99 initializeSimpleInlinerPass(R); 100 initializePruneEHPass(R); 101 initializeGlobalDCEPass(R); 102 initializeArgPromotionPass(R); 103 initializeJumpThreadingPass(R); 104 initializeSROAPass(R); 105 initializeSROA_DTPass(R); 106 initializeSROA_SSAUpPass(R); 107 initializeFunctionAttrsPass(R); 108 initializeGlobalsModRefPass(R); 109 initializeLICMPass(R); 110 initializeGVNPass(R); 111 initializeMemCpyOptPass(R); 112 initializeDCEPass(R); 113 initializeCFGSimplifyPassPass(R); 114 } 115 116 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) { 117 bool ret = IRLinker.linkInModule(&mod->getModule(), &errMsg); 118 119 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs(); 120 for (int i = 0, e = undefs.size(); i != e; ++i) 121 AsmUndefinedRefs[undefs[i]] = 1; 122 123 return !ret; 124 } 125 126 void LTOCodeGenerator::setTargetOptions(TargetOptions options) { 127 Options = options; 128 } 129 130 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) { 131 switch (debug) { 132 case LTO_DEBUG_MODEL_NONE: 133 EmitDwarfDebugInfo = false; 134 return; 135 136 case LTO_DEBUG_MODEL_DWARF: 137 EmitDwarfDebugInfo = true; 138 return; 139 } 140 llvm_unreachable("Unknown debug format!"); 141 } 142 143 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) { 144 switch (model) { 145 case LTO_CODEGEN_PIC_MODEL_STATIC: 146 case LTO_CODEGEN_PIC_MODEL_DYNAMIC: 147 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC: 148 case LTO_CODEGEN_PIC_MODEL_DEFAULT: 149 CodeModel = model; 150 return; 151 } 152 llvm_unreachable("Unknown PIC model!"); 153 } 154 155 bool LTOCodeGenerator::writeMergedModules(const char *path, 156 std::string &errMsg) { 157 if (!determineTarget(errMsg)) 158 return false; 159 160 // mark which symbols can not be internalized 161 applyScopeRestrictions(); 162 163 // create output file 164 std::string ErrInfo; 165 tool_output_file Out(path, ErrInfo, sys::fs::F_None); 166 if (!ErrInfo.empty()) { 167 errMsg = "could not open bitcode file for writing: "; 168 errMsg += path; 169 return false; 170 } 171 172 // write bitcode to it 173 WriteBitcodeToFile(IRLinker.getModule(), Out.os()); 174 Out.os().close(); 175 176 if (Out.os().has_error()) { 177 errMsg = "could not write bitcode file: "; 178 errMsg += path; 179 Out.os().clear_error(); 180 return false; 181 } 182 183 Out.keep(); 184 return true; 185 } 186 187 bool LTOCodeGenerator::compile_to_file(const char** name, 188 bool disableOpt, 189 bool disableInline, 190 bool disableGVNLoadPRE, 191 std::string& errMsg) { 192 // make unique temp .o file to put generated object file 193 SmallString<128> Filename; 194 int FD; 195 std::error_code EC = 196 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename); 197 if (EC) { 198 errMsg = EC.message(); 199 return false; 200 } 201 202 // generate object file 203 tool_output_file objFile(Filename.c_str(), FD); 204 205 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline, 206 disableGVNLoadPRE, errMsg); 207 objFile.os().close(); 208 if (objFile.os().has_error()) { 209 objFile.os().clear_error(); 210 sys::fs::remove(Twine(Filename)); 211 return false; 212 } 213 214 objFile.keep(); 215 if (!genResult) { 216 sys::fs::remove(Twine(Filename)); 217 return false; 218 } 219 220 NativeObjectPath = Filename.c_str(); 221 *name = NativeObjectPath.c_str(); 222 return true; 223 } 224 225 const void* LTOCodeGenerator::compile(size_t* length, 226 bool disableOpt, 227 bool disableInline, 228 bool disableGVNLoadPRE, 229 std::string& errMsg) { 230 const char *name; 231 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE, 232 errMsg)) 233 return nullptr; 234 235 // remove old buffer if compile() called twice 236 delete NativeObjectFile; 237 238 // read .o file into memory buffer 239 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 240 MemoryBuffer::getFile(name, -1, false); 241 if (std::error_code EC = BufferOrErr.getError()) { 242 errMsg = EC.message(); 243 sys::fs::remove(NativeObjectPath); 244 return nullptr; 245 } 246 NativeObjectFile = BufferOrErr.get().release(); 247 248 // remove temp files 249 sys::fs::remove(NativeObjectPath); 250 251 // return buffer, unless error 252 if (!NativeObjectFile) 253 return nullptr; 254 *length = NativeObjectFile->getBufferSize(); 255 return NativeObjectFile->getBufferStart(); 256 } 257 258 bool LTOCodeGenerator::determineTarget(std::string &errMsg) { 259 if (TargetMach) 260 return true; 261 262 std::string TripleStr = IRLinker.getModule()->getTargetTriple(); 263 if (TripleStr.empty()) 264 TripleStr = sys::getDefaultTargetTriple(); 265 llvm::Triple Triple(TripleStr); 266 267 // create target machine from info for merged modules 268 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg); 269 if (!march) 270 return false; 271 272 // The relocation model is actually a static member of TargetMachine and 273 // needs to be set before the TargetMachine is instantiated. 274 Reloc::Model RelocModel = Reloc::Default; 275 switch (CodeModel) { 276 case LTO_CODEGEN_PIC_MODEL_STATIC: 277 RelocModel = Reloc::Static; 278 break; 279 case LTO_CODEGEN_PIC_MODEL_DYNAMIC: 280 RelocModel = Reloc::PIC_; 281 break; 282 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC: 283 RelocModel = Reloc::DynamicNoPIC; 284 break; 285 case LTO_CODEGEN_PIC_MODEL_DEFAULT: 286 // RelocModel is already the default, so leave it that way. 287 break; 288 } 289 290 // Construct LTOModule, hand over ownership of module and target. Use MAttr as 291 // the default set of features. 292 SubtargetFeatures Features(MAttr); 293 Features.getDefaultSubtargetFeatures(Triple); 294 std::string FeatureStr = Features.getString(); 295 // Set a default CPU for Darwin triples. 296 if (MCpu.empty() && Triple.isOSDarwin()) { 297 if (Triple.getArch() == llvm::Triple::x86_64) 298 MCpu = "core2"; 299 else if (Triple.getArch() == llvm::Triple::x86) 300 MCpu = "yonah"; 301 else if (Triple.getArch() == llvm::Triple::arm64 || 302 Triple.getArch() == llvm::Triple::aarch64) 303 MCpu = "cyclone"; 304 } 305 306 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options, 307 RelocModel, CodeModel::Default, 308 CodeGenOpt::Aggressive); 309 return true; 310 } 311 312 void LTOCodeGenerator:: 313 applyRestriction(GlobalValue &GV, 314 const ArrayRef<StringRef> &Libcalls, 315 std::vector<const char*> &MustPreserveList, 316 SmallPtrSet<GlobalValue*, 8> &AsmUsed, 317 Mangler &Mangler) { 318 // There are no restrictions to apply to declarations. 319 if (GV.isDeclaration()) 320 return; 321 322 // There is nothing more restrictive than private linkage. 323 if (GV.hasPrivateLinkage()) 324 return; 325 326 SmallString<64> Buffer; 327 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler); 328 329 if (MustPreserveSymbols.count(Buffer)) 330 MustPreserveList.push_back(GV.getName().data()); 331 if (AsmUndefinedRefs.count(Buffer)) 332 AsmUsed.insert(&GV); 333 334 // Conservatively append user-supplied runtime library functions to 335 // llvm.compiler.used. These could be internalized and deleted by 336 // optimizations like -globalopt, causing problems when later optimizations 337 // add new library calls (e.g., llvm.memset => memset and printf => puts). 338 // Leave it to the linker to remove any dead code (e.g. with -dead_strip). 339 if (isa<Function>(GV) && 340 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName())) 341 AsmUsed.insert(&GV); 342 } 343 344 static void findUsedValues(GlobalVariable *LLVMUsed, 345 SmallPtrSet<GlobalValue*, 8> &UsedValues) { 346 if (!LLVMUsed) return; 347 348 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); 349 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) 350 if (GlobalValue *GV = 351 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) 352 UsedValues.insert(GV); 353 } 354 355 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls, 356 const TargetLibraryInfo& TLI, 357 const TargetLowering *Lowering) 358 { 359 // TargetLibraryInfo has info on C runtime library calls on the current 360 // target. 361 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs); 362 I != E; ++I) { 363 LibFunc::Func F = static_cast<LibFunc::Func>(I); 364 if (TLI.has(F)) 365 Libcalls.push_back(TLI.getName(F)); 366 } 367 368 // TargetLowering has info on library calls that CodeGen expects to be 369 // available, both from the C runtime and compiler-rt. 370 if (Lowering) 371 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL); 372 I != E; ++I) 373 if (const char *Name 374 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I))) 375 Libcalls.push_back(Name); 376 377 array_pod_sort(Libcalls.begin(), Libcalls.end()); 378 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()), 379 Libcalls.end()); 380 } 381 382 void LTOCodeGenerator::applyScopeRestrictions() { 383 if (ScopeRestrictionsDone) 384 return; 385 Module *mergedModule = IRLinker.getModule(); 386 387 // Start off with a verification pass. 388 PassManager passes; 389 passes.add(createVerifierPass()); 390 passes.add(createDebugInfoVerifierPass()); 391 392 // mark which symbols can not be internalized 393 Mangler Mangler(TargetMach->getDataLayout()); 394 std::vector<const char*> MustPreserveList; 395 SmallPtrSet<GlobalValue*, 8> AsmUsed; 396 std::vector<StringRef> Libcalls; 397 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple())); 398 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering()); 399 400 for (Module::iterator f = mergedModule->begin(), 401 e = mergedModule->end(); f != e; ++f) 402 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler); 403 for (Module::global_iterator v = mergedModule->global_begin(), 404 e = mergedModule->global_end(); v != e; ++v) 405 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler); 406 for (Module::alias_iterator a = mergedModule->alias_begin(), 407 e = mergedModule->alias_end(); a != e; ++a) 408 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler); 409 410 GlobalVariable *LLVMCompilerUsed = 411 mergedModule->getGlobalVariable("llvm.compiler.used"); 412 findUsedValues(LLVMCompilerUsed, AsmUsed); 413 if (LLVMCompilerUsed) 414 LLVMCompilerUsed->eraseFromParent(); 415 416 if (!AsmUsed.empty()) { 417 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context); 418 std::vector<Constant*> asmUsed2; 419 for (auto *GV : AsmUsed) { 420 Constant *c = ConstantExpr::getBitCast(GV, i8PTy); 421 asmUsed2.push_back(c); 422 } 423 424 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size()); 425 LLVMCompilerUsed = 426 new llvm::GlobalVariable(*mergedModule, ATy, false, 427 llvm::GlobalValue::AppendingLinkage, 428 llvm::ConstantArray::get(ATy, asmUsed2), 429 "llvm.compiler.used"); 430 431 LLVMCompilerUsed->setSection("llvm.metadata"); 432 } 433 434 passes.add(createInternalizePass(MustPreserveList)); 435 436 // apply scope restrictions 437 passes.run(*mergedModule); 438 439 ScopeRestrictionsDone = true; 440 } 441 442 /// Optimize merged modules using various IPO passes 443 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out, 444 bool DisableOpt, 445 bool DisableInline, 446 bool DisableGVNLoadPRE, 447 std::string &errMsg) { 448 if (!this->determineTarget(errMsg)) 449 return false; 450 451 Module *mergedModule = IRLinker.getModule(); 452 453 // Mark which symbols can not be internalized 454 this->applyScopeRestrictions(); 455 456 // Instantiate the pass manager to organize the passes. 457 PassManager passes; 458 459 // Start off with a verification pass. 460 passes.add(createVerifierPass()); 461 passes.add(createDebugInfoVerifierPass()); 462 463 // Add an appropriate DataLayout instance for this module... 464 mergedModule->setDataLayout(TargetMach->getDataLayout()); 465 passes.add(new DataLayoutPass(mergedModule)); 466 467 // Add appropriate TargetLibraryInfo for this module. 468 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple()))); 469 470 TargetMach->addAnalysisPasses(passes); 471 472 // Enabling internalize here would use its AllButMain variant. It 473 // keeps only main if it exists and does nothing for libraries. Instead 474 // we create the pass ourselves with the symbol list provided by the linker. 475 if (!DisableOpt) 476 PassManagerBuilder().populateLTOPassManager(passes, 477 /*Internalize=*/false, 478 !DisableInline, 479 DisableGVNLoadPRE); 480 481 // Make sure everything is still good. 482 passes.add(createVerifierPass()); 483 passes.add(createDebugInfoVerifierPass()); 484 485 PassManager codeGenPasses; 486 487 codeGenPasses.add(new DataLayoutPass(mergedModule)); 488 489 formatted_raw_ostream Out(out); 490 491 // If the bitcode files contain ARC code and were compiled with optimization, 492 // the ObjCARCContractPass must be run, so do it unconditionally here. 493 codeGenPasses.add(createObjCARCContractPass()); 494 495 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out, 496 TargetMachine::CGFT_ObjectFile)) { 497 errMsg = "target file type not supported"; 498 return false; 499 } 500 501 // Run our queue of passes all at once now, efficiently. 502 passes.run(*mergedModule); 503 504 // Run the code generator, and write assembly file 505 codeGenPasses.run(*mergedModule); 506 507 return true; 508 } 509 510 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging 511 /// LTO problems. 512 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) { 513 for (std::pair<StringRef, StringRef> o = getToken(options); 514 !o.first.empty(); o = getToken(o.second)) { 515 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add 516 // that. 517 if (CodegenOptions.empty()) 518 CodegenOptions.push_back(strdup("libLLVMLTO")); 519 CodegenOptions.push_back(strdup(o.first.str().c_str())); 520 } 521 } 522 523 void LTOCodeGenerator::parseCodeGenDebugOptions() { 524 // if options were requested, set them 525 if (!CodegenOptions.empty()) 526 cl::ParseCommandLineOptions(CodegenOptions.size(), 527 const_cast<char **>(&CodegenOptions[0])); 528 } 529 530 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI, 531 void *Context) { 532 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI); 533 } 534 535 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) { 536 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity. 537 lto_codegen_diagnostic_severity_t Severity; 538 switch (DI.getSeverity()) { 539 case DS_Error: 540 Severity = LTO_DS_ERROR; 541 break; 542 case DS_Warning: 543 Severity = LTO_DS_WARNING; 544 break; 545 case DS_Remark: 546 Severity = LTO_DS_REMARK; 547 break; 548 case DS_Note: 549 Severity = LTO_DS_NOTE; 550 break; 551 } 552 // Create the string that will be reported to the external diagnostic handler. 553 std::string MsgStorage; 554 raw_string_ostream Stream(MsgStorage); 555 DiagnosticPrinterRawOStream DP(Stream); 556 DI.print(DP); 557 Stream.flush(); 558 559 // If this method has been called it means someone has set up an external 560 // diagnostic handler. Assert on that. 561 assert(DiagHandler && "Invalid diagnostic handler"); 562 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext); 563 } 564 565 void 566 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler, 567 void *Ctxt) { 568 this->DiagHandler = DiagHandler; 569 this->DiagContext = Ctxt; 570 if (!DiagHandler) 571 return Context.setDiagnosticHandler(nullptr, nullptr); 572 // Register the LTOCodeGenerator stub in the LLVMContext to forward the 573 // diagnostic to the external DiagHandler. 574 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this); 575 } 576