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