OSDN Git Service

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