]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/LTO/LTOCodeGenerator.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/legacy/LTOCodeGenerator.h"
16
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassTimingInfo.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LTO/LTO.h"
40 #include "llvm/LTO/legacy/LTOModule.h"
41 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
42 #include "llvm/Linker/Linker.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/ToolOutputFile.h"
54 #include "llvm/Support/YAMLTraits.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/Transforms/IPO.h"
58 #include "llvm/Transforms/IPO/Internalize.h"
59 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
60 #include "llvm/Transforms/ObjCARC.h"
61 #include "llvm/Transforms/Utils/ModuleUtils.h"
62 #include <system_error>
63 using namespace llvm;
64
65 const char* LTOCodeGenerator::getVersionString() {
66 #ifdef LLVM_VERSION_INFO
67   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 #else
69   return PACKAGE_NAME " version " PACKAGE_VERSION;
70 #endif
71 }
72
73 namespace llvm {
74 cl::opt<bool> LTODiscardValueNames(
75     "lto-discard-value-names",
76     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
77 #ifdef NDEBUG
78     cl::init(true),
79 #else
80     cl::init(false),
81 #endif
82     cl::Hidden);
83
84 cl::opt<std::string>
85     LTORemarksFilename("lto-pass-remarks-output",
86                        cl::desc("Output filename for pass remarks"),
87                        cl::value_desc("filename"));
88
89 cl::opt<bool> LTOPassRemarksWithHotness(
90     "lto-pass-remarks-with-hotness",
91     cl::desc("With PGO, include profile count in optimization remarks"),
92     cl::Hidden);
93 }
94
95 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
96     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
97       TheLinker(new Linker(*MergedModule)) {
98   Context.setDiscardValueNames(LTODiscardValueNames);
99   Context.enableDebugTypeODRUniquing();
100   initializeLTOPasses();
101 }
102
103 LTOCodeGenerator::~LTOCodeGenerator() {}
104
105 // Initialize LTO passes. Please keep this function in sync with
106 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
107 // passes are initialized.
108 void LTOCodeGenerator::initializeLTOPasses() {
109   PassRegistry &R = *PassRegistry::getPassRegistry();
110
111   initializeInternalizeLegacyPassPass(R);
112   initializeIPSCCPLegacyPassPass(R);
113   initializeGlobalOptLegacyPassPass(R);
114   initializeConstantMergeLegacyPassPass(R);
115   initializeDAHPass(R);
116   initializeInstructionCombiningPassPass(R);
117   initializeSimpleInlinerPass(R);
118   initializePruneEHPass(R);
119   initializeGlobalDCELegacyPassPass(R);
120   initializeArgPromotionPass(R);
121   initializeJumpThreadingPass(R);
122   initializeSROALegacyPassPass(R);
123   initializePostOrderFunctionAttrsLegacyPassPass(R);
124   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
125   initializeGlobalsAAWrapperPassPass(R);
126   initializeLegacyLICMPassPass(R);
127   initializeMergedLoadStoreMotionLegacyPassPass(R);
128   initializeGVNLegacyPassPass(R);
129   initializeMemCpyOptLegacyPassPass(R);
130   initializeDCELegacyPassPass(R);
131   initializeCFGSimplifyPassPass(R);
132 }
133
134 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
135   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
136   for (int i = 0, e = undefs.size(); i != e; ++i)
137     AsmUndefinedRefs[undefs[i]] = 1;
138 }
139
140 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
141   assert(&Mod->getModule().getContext() == &Context &&
142          "Expected module in same context");
143
144   bool ret = TheLinker->linkInModule(Mod->takeModule());
145   setAsmUndefinedRefs(Mod);
146
147   // We've just changed the input, so let's make sure we verify it.
148   HasVerifiedInput = false;
149
150   return !ret;
151 }
152
153 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
154   assert(&Mod->getModule().getContext() == &Context &&
155          "Expected module in same context");
156
157   AsmUndefinedRefs.clear();
158
159   MergedModule = Mod->takeModule();
160   TheLinker = make_unique<Linker>(*MergedModule);
161   setAsmUndefinedRefs(&*Mod);
162
163   // We've just changed the input, so let's make sure we verify it.
164   HasVerifiedInput = false;
165 }
166
167 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
168   this->Options = Options;
169 }
170
171 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
172   switch (Debug) {
173   case LTO_DEBUG_MODEL_NONE:
174     EmitDwarfDebugInfo = false;
175     return;
176
177   case LTO_DEBUG_MODEL_DWARF:
178     EmitDwarfDebugInfo = true;
179     return;
180   }
181   llvm_unreachable("Unknown debug format!");
182 }
183
184 void LTOCodeGenerator::setOptLevel(unsigned Level) {
185   OptLevel = Level;
186   switch (OptLevel) {
187   case 0:
188     CGOptLevel = CodeGenOpt::None;
189     return;
190   case 1:
191     CGOptLevel = CodeGenOpt::Less;
192     return;
193   case 2:
194     CGOptLevel = CodeGenOpt::Default;
195     return;
196   case 3:
197     CGOptLevel = CodeGenOpt::Aggressive;
198     return;
199   }
200   llvm_unreachable("Unknown optimization level!");
201 }
202
203 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
204   if (!determineTarget())
205     return false;
206
207   // We always run the verifier once on the merged module.
208   verifyMergedModuleOnce();
209
210   // mark which symbols can not be internalized
211   applyScopeRestrictions();
212
213   // create output file
214   std::error_code EC;
215   ToolOutputFile Out(Path, EC, sys::fs::F_None);
216   if (EC) {
217     std::string ErrMsg = "could not open bitcode file for writing: ";
218     ErrMsg += Path.str() + ": " + EC.message();
219     emitError(ErrMsg);
220     return false;
221   }
222
223   // write bitcode to it
224   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
225   Out.os().close();
226
227   if (Out.os().has_error()) {
228     std::string ErrMsg = "could not write bitcode file: ";
229     ErrMsg += Path.str() + ": " + Out.os().error().message();
230     emitError(ErrMsg);
231     Out.os().clear_error();
232     return false;
233   }
234
235   Out.keep();
236   return true;
237 }
238
239 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
240   // make unique temp output file to put generated code
241   SmallString<128> Filename;
242   int FD;
243
244   StringRef Extension
245       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
246
247   std::error_code EC =
248       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
249   if (EC) {
250     emitError(EC.message());
251     return false;
252   }
253
254   // generate object file
255   ToolOutputFile objFile(Filename, FD);
256
257   bool genResult = compileOptimized(&objFile.os());
258   objFile.os().close();
259   if (objFile.os().has_error()) {
260     emitError((Twine("could not write object file: ") + Filename + ": " +
261                objFile.os().error().message())
262                   .str());
263     objFile.os().clear_error();
264     sys::fs::remove(Twine(Filename));
265     return false;
266   }
267
268   objFile.keep();
269   if (!genResult) {
270     sys::fs::remove(Twine(Filename));
271     return false;
272   }
273
274   NativeObjectPath = Filename.c_str();
275   *Name = NativeObjectPath.c_str();
276   return true;
277 }
278
279 std::unique_ptr<MemoryBuffer>
280 LTOCodeGenerator::compileOptimized() {
281   const char *name;
282   if (!compileOptimizedToFile(&name))
283     return nullptr;
284
285   // read .o file into memory buffer
286   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
287       MemoryBuffer::getFile(name, -1, false);
288   if (std::error_code EC = BufferOrErr.getError()) {
289     emitError(EC.message());
290     sys::fs::remove(NativeObjectPath);
291     return nullptr;
292   }
293
294   // remove temp files
295   sys::fs::remove(NativeObjectPath);
296
297   return std::move(*BufferOrErr);
298 }
299
300 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
301                                        bool DisableInline,
302                                        bool DisableGVNLoadPRE,
303                                        bool DisableVectorization) {
304   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
305                 DisableVectorization))
306     return false;
307
308   return compileOptimizedToFile(Name);
309 }
310
311 std::unique_ptr<MemoryBuffer>
312 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
313                           bool DisableGVNLoadPRE, bool DisableVectorization) {
314   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
315                 DisableVectorization))
316     return nullptr;
317
318   return compileOptimized();
319 }
320
321 bool LTOCodeGenerator::determineTarget() {
322   if (TargetMach)
323     return true;
324
325   TripleStr = MergedModule->getTargetTriple();
326   if (TripleStr.empty()) {
327     TripleStr = sys::getDefaultTargetTriple();
328     MergedModule->setTargetTriple(TripleStr);
329   }
330   llvm::Triple Triple(TripleStr);
331
332   // create target machine from info for merged modules
333   std::string ErrMsg;
334   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
335   if (!MArch) {
336     emitError(ErrMsg);
337     return false;
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   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 = createTargetMachine();
356   return true;
357 }
358
359 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
360   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
361       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
362 }
363
364 // If a linkonce global is present in the MustPreserveSymbols, we need to make
365 // sure we honor this. To force the compiler to not drop it, we add it to the
366 // "llvm.compiler.used" global.
367 void LTOCodeGenerator::preserveDiscardableGVs(
368     Module &TheModule,
369     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
370   std::vector<GlobalValue *> Used;
371   auto mayPreserveGlobal = [&](GlobalValue &GV) {
372     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
373         !mustPreserveGV(GV))
374       return;
375     if (GV.hasAvailableExternallyLinkage())
376       return emitWarning(
377           (Twine("Linker asked to preserve available_externally global: '") +
378            GV.getName() + "'").str());
379     if (GV.hasInternalLinkage())
380       return emitWarning((Twine("Linker asked to preserve internal global: '") +
381                    GV.getName() + "'").str());
382     Used.push_back(&GV);
383   };
384   for (auto &GV : TheModule)
385     mayPreserveGlobal(GV);
386   for (auto &GV : TheModule.globals())
387     mayPreserveGlobal(GV);
388   for (auto &GV : TheModule.aliases())
389     mayPreserveGlobal(GV);
390
391   if (Used.empty())
392     return;
393
394   appendToCompilerUsed(TheModule, Used);
395 }
396
397 void LTOCodeGenerator::applyScopeRestrictions() {
398   if (ScopeRestrictionsDone)
399     return;
400
401   // Declare a callback for the internalize pass that will ask for every
402   // candidate GlobalValue if it can be internalized or not.
403   Mangler Mang;
404   SmallString<64> MangledName;
405   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
406     // Unnamed globals can't be mangled, but they can't be preserved either.
407     if (!GV.hasName())
408       return false;
409
410     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
411     // with the linker supplied name, which on Darwin includes a leading
412     // underscore.
413     MangledName.clear();
414     MangledName.reserve(GV.getName().size() + 1);
415     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
416     return MustPreserveSymbols.count(MangledName);
417   };
418
419   // Preserve linkonce value on linker request
420   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
421
422   if (!ShouldInternalize)
423     return;
424
425   if (ShouldRestoreGlobalsLinkage) {
426     // Record the linkage type of non-local symbols so they can be restored
427     // prior
428     // to module splitting.
429     auto RecordLinkage = [&](const GlobalValue &GV) {
430       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
431           GV.hasName())
432         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
433     };
434     for (auto &GV : *MergedModule)
435       RecordLinkage(GV);
436     for (auto &GV : MergedModule->globals())
437       RecordLinkage(GV);
438     for (auto &GV : MergedModule->aliases())
439       RecordLinkage(GV);
440   }
441
442   // Update the llvm.compiler_used globals to force preserving libcalls and
443   // symbols referenced from asm
444   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
445
446   internalizeModule(*MergedModule, mustPreserveGV);
447
448   ScopeRestrictionsDone = true;
449 }
450
451 /// Restore original linkage for symbols that may have been internalized
452 void LTOCodeGenerator::restoreLinkageForExternals() {
453   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
454     return;
455
456   assert(ScopeRestrictionsDone &&
457          "Cannot externalize without internalization!");
458
459   if (ExternalSymbols.empty())
460     return;
461
462   auto externalize = [this](GlobalValue &GV) {
463     if (!GV.hasLocalLinkage() || !GV.hasName())
464       return;
465
466     auto I = ExternalSymbols.find(GV.getName());
467     if (I == ExternalSymbols.end())
468       return;
469
470     GV.setLinkage(I->second);
471   };
472
473   llvm::for_each(MergedModule->functions(), externalize);
474   llvm::for_each(MergedModule->globals(), externalize);
475   llvm::for_each(MergedModule->aliases(), externalize);
476 }
477
478 void LTOCodeGenerator::verifyMergedModuleOnce() {
479   // Only run on the first call.
480   if (HasVerifiedInput)
481     return;
482   HasVerifiedInput = true;
483
484   bool BrokenDebugInfo = false;
485   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
486     report_fatal_error("Broken module found, compilation aborted!");
487   if (BrokenDebugInfo) {
488     emitWarning("Invalid debug info found, debug info will be stripped");
489     StripDebugInfo(*MergedModule);
490   }
491 }
492
493 void LTOCodeGenerator::finishOptimizationRemarks() {
494   if (DiagnosticOutputFile) {
495     DiagnosticOutputFile->keep();
496     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
497     DiagnosticOutputFile->os().flush();
498   }
499 }
500
501 /// Optimize merged modules using various IPO passes
502 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
503                                 bool DisableGVNLoadPRE,
504                                 bool DisableVectorization) {
505   if (!this->determineTarget())
506     return false;
507
508   auto DiagFileOrErr = lto::setupOptimizationRemarks(
509       Context, LTORemarksFilename, LTOPassRemarksWithHotness);
510   if (!DiagFileOrErr) {
511     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
512     report_fatal_error("Can't get an output file for the remarks");
513   }
514   DiagnosticOutputFile = std::move(*DiagFileOrErr);
515
516   // We always run the verifier once on the merged module, the `DisableVerify`
517   // parameter only applies to subsequent verify.
518   verifyMergedModuleOnce();
519
520   // Mark which symbols can not be internalized
521   this->applyScopeRestrictions();
522
523   // Instantiate the pass manager to organize the passes.
524   legacy::PassManager passes;
525
526   // Add an appropriate DataLayout instance for this module...
527   MergedModule->setDataLayout(TargetMach->createDataLayout());
528
529   passes.add(
530       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
531
532   Triple TargetTriple(TargetMach->getTargetTriple());
533   PassManagerBuilder PMB;
534   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
535   PMB.LoopVectorize = !DisableVectorization;
536   PMB.SLPVectorize = !DisableVectorization;
537   if (!DisableInline)
538     PMB.Inliner = createFunctionInliningPass();
539   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
540   if (Freestanding)
541     PMB.LibraryInfo->disableAllFunctions();
542   PMB.OptLevel = OptLevel;
543   PMB.VerifyInput = !DisableVerify;
544   PMB.VerifyOutput = !DisableVerify;
545
546   PMB.populateLTOPassManager(passes);
547
548   // Run our queue of passes all at once now, efficiently.
549   passes.run(*MergedModule);
550
551   return true;
552 }
553
554 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
555   if (!this->determineTarget())
556     return false;
557
558   // We always run the verifier once on the merged module.  If it has already
559   // been called in optimize(), this call will return early.
560   verifyMergedModuleOnce();
561
562   legacy::PassManager preCodeGenPasses;
563
564   // If the bitcode files contain ARC code and were compiled with optimization,
565   // the ObjCARCContractPass must be run, so do it unconditionally here.
566   preCodeGenPasses.add(createObjCARCContractPass());
567   preCodeGenPasses.run(*MergedModule);
568
569   // Re-externalize globals that may have been internalized to increase scope
570   // for splitting
571   restoreLinkageForExternals();
572
573   // Do code generation. We need to preserve the module in case the client calls
574   // writeMergedModules() after compilation, but we only need to allow this at
575   // parallelism level 1. This is achieved by having splitCodeGen return the
576   // original module at parallelism level 1 which we then assign back to
577   // MergedModule.
578   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
579                               [&]() { return createTargetMachine(); }, FileType,
580                               ShouldRestoreGlobalsLinkage);
581
582   // If statistics were requested, print them out after codegen.
583   if (llvm::AreStatisticsEnabled())
584     llvm::PrintStatistics();
585   reportAndResetTimings();
586
587   finishOptimizationRemarks();
588
589   return true;
590 }
591
592 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
593 /// LTO problems.
594 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
595   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
596        o = getToken(o.second))
597     CodegenOptions.push_back(o.first);
598 }
599
600 void LTOCodeGenerator::parseCodeGenDebugOptions() {
601   // if options were requested, set them
602   if (!CodegenOptions.empty()) {
603     // ParseCommandLineOptions() expects argv[0] to be program name.
604     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
605     for (std::string &Arg : CodegenOptions)
606       CodegenArgv.push_back(Arg.c_str());
607     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
608   }
609 }
610
611
612 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
613   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
614   lto_codegen_diagnostic_severity_t Severity;
615   switch (DI.getSeverity()) {
616   case DS_Error:
617     Severity = LTO_DS_ERROR;
618     break;
619   case DS_Warning:
620     Severity = LTO_DS_WARNING;
621     break;
622   case DS_Remark:
623     Severity = LTO_DS_REMARK;
624     break;
625   case DS_Note:
626     Severity = LTO_DS_NOTE;
627     break;
628   }
629   // Create the string that will be reported to the external diagnostic handler.
630   std::string MsgStorage;
631   raw_string_ostream Stream(MsgStorage);
632   DiagnosticPrinterRawOStream DP(Stream);
633   DI.print(DP);
634   Stream.flush();
635
636   // If this method has been called it means someone has set up an external
637   // diagnostic handler. Assert on that.
638   assert(DiagHandler && "Invalid diagnostic handler");
639   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
640 }
641
642 namespace {
643 struct LTODiagnosticHandler : public DiagnosticHandler {
644   LTOCodeGenerator *CodeGenerator;
645   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
646       : CodeGenerator(CodeGenPtr) {}
647   bool handleDiagnostics(const DiagnosticInfo &DI) override {
648     CodeGenerator->DiagnosticHandler(DI);
649     return true;
650   }
651 };
652 }
653
654 void
655 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
656                                        void *Ctxt) {
657   this->DiagHandler = DiagHandler;
658   this->DiagContext = Ctxt;
659   if (!DiagHandler)
660     return Context.setDiagnosticHandler(nullptr);
661   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
662   // diagnostic to the external DiagHandler.
663   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
664                                true);
665 }
666
667 namespace {
668 class LTODiagnosticInfo : public DiagnosticInfo {
669   const Twine &Msg;
670 public:
671   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
672       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
673   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
674 };
675 }
676
677 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
678   if (DiagHandler)
679     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
680   else
681     Context.diagnose(LTODiagnosticInfo(ErrMsg));
682 }
683
684 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
685   if (DiagHandler)
686     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
687   else
688     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
689 }