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