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