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