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