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