]> git.lizzy.rs Git - rust.git/blob - src/rustllvm/PassWrapper.cpp
Auto merge of #67878 - Others:opt-3, r=Mark-Simulacrum
[rust.git] / src / rustllvm / PassWrapper.cpp
1 #include <stdio.h>
2
3 #include <vector>
4 #include <set>
5
6 #include "rustllvm.h"
7
8 #include "llvm/Analysis/TargetLibraryInfo.h"
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/CodeGen/TargetSubtargetInfo.h"
11 #include "llvm/InitializePasses.h"
12 #include "llvm/IR/AutoUpgrade.h"
13 #include "llvm/IR/AssemblyAnnotationWriter.h"
14 #include "llvm/IR/IntrinsicInst.h"
15 #include "llvm/Support/CBindingWrapping.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Host.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
20 #include "llvm/Transforms/IPO/AlwaysInliner.h"
21 #include "llvm/Transforms/IPO/FunctionImport.h"
22 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm-c/Transforms/PassManagerBuilder.h"
25
26 #include "llvm/Transforms/Instrumentation.h"
27 #if LLVM_VERSION_GE(9, 0)
28 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
29 #endif
30 #if LLVM_VERSION_GE(8, 0)
31 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
32 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
33 #endif
34
35 using namespace llvm;
36 using namespace llvm::legacy;
37
38 typedef struct LLVMOpaquePass *LLVMPassRef;
39 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
40
41 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
42 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
43 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
44                                    LLVMPassManagerBuilderRef)
45
46 extern "C" void LLVMInitializePasses() {
47   PassRegistry &Registry = *PassRegistry::getPassRegistry();
48   initializeCore(Registry);
49   initializeCodeGen(Registry);
50   initializeScalarOpts(Registry);
51   initializeVectorization(Registry);
52   initializeIPO(Registry);
53   initializeAnalysis(Registry);
54   initializeTransformUtils(Registry);
55   initializeInstCombine(Registry);
56   initializeInstrumentation(Registry);
57   initializeTarget(Registry);
58 }
59
60 enum class LLVMRustPassKind {
61   Other,
62   Function,
63   Module,
64 };
65
66 static LLVMRustPassKind toRust(PassKind Kind) {
67   switch (Kind) {
68   case PT_Function:
69     return LLVMRustPassKind::Function;
70   case PT_Module:
71     return LLVMRustPassKind::Module;
72   default:
73     return LLVMRustPassKind::Other;
74   }
75 }
76
77 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
78   StringRef SR(PassName);
79   PassRegistry *PR = PassRegistry::getPassRegistry();
80
81   const PassInfo *PI = PR->getPassInfo(SR);
82   if (PI) {
83     return wrap(PI->createPass());
84   }
85   return nullptr;
86 }
87
88 extern "C" LLVMPassRef LLVMRustCreateAddressSanitizerFunctionPass(bool Recover) {
89   const bool CompileKernel = false;
90   const bool UseAfterScope = true;
91
92   return wrap(createAddressSanitizerFunctionPass(CompileKernel, Recover, UseAfterScope));
93 }
94
95 extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) {
96   const bool CompileKernel = false;
97
98 #if LLVM_VERSION_GE(9, 0)
99   return wrap(createModuleAddressSanitizerLegacyPassPass(CompileKernel, Recover));
100 #else
101   return wrap(createAddressSanitizerModulePass(CompileKernel, Recover));
102 #endif
103 }
104
105 extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) {
106 #if LLVM_VERSION_GE(9, 0)
107   const bool CompileKernel = false;
108
109   return wrap(createMemorySanitizerLegacyPassPass(
110       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
111 #elif LLVM_VERSION_GE(8, 0)
112   return wrap(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover));
113 #else
114   return wrap(createMemorySanitizerPass(TrackOrigins, Recover));
115 #endif
116 }
117
118 extern "C" LLVMPassRef LLVMRustCreateThreadSanitizerPass() {
119 #if LLVM_VERSION_GE(8, 0)
120   return wrap(createThreadSanitizerLegacyPassPass());
121 #else
122   return wrap(createThreadSanitizerPass());
123 #endif
124 }
125
126 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
127   assert(RustPass);
128   Pass *Pass = unwrap(RustPass);
129   return toRust(Pass->getPassKind());
130 }
131
132 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
133   assert(RustPass);
134   Pass *Pass = unwrap(RustPass);
135   PassManagerBase *PMB = unwrap(PMR);
136   PMB->add(Pass);
137 }
138
139 extern "C"
140 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
141   LLVMPassManagerBuilderRef PMBR,
142   LLVMPassManagerRef PMR
143 ) {
144   unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
145 }
146
147 extern "C"
148 void LLVMRustAddLastExtensionPasses(
149     LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
150   auto AddExtensionPasses = [Passes, NumPasses](
151       const PassManagerBuilder &Builder, PassManagerBase &PM) {
152     for (size_t I = 0; I < NumPasses; I++) {
153       PM.add(unwrap(Passes[I]));
154     }
155   };
156   // Add the passes to both of the pre-finalization extension points,
157   // so they are run for optimized and non-optimized builds.
158   unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
159                              AddExtensionPasses);
160   unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
161                              AddExtensionPasses);
162 }
163
164 #ifdef LLVM_COMPONENT_X86
165 #define SUBTARGET_X86 SUBTARGET(X86)
166 #else
167 #define SUBTARGET_X86
168 #endif
169
170 #ifdef LLVM_COMPONENT_ARM
171 #define SUBTARGET_ARM SUBTARGET(ARM)
172 #else
173 #define SUBTARGET_ARM
174 #endif
175
176 #ifdef LLVM_COMPONENT_AARCH64
177 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
178 #else
179 #define SUBTARGET_AARCH64
180 #endif
181
182 #ifdef LLVM_COMPONENT_MIPS
183 #define SUBTARGET_MIPS SUBTARGET(Mips)
184 #else
185 #define SUBTARGET_MIPS
186 #endif
187
188 #ifdef LLVM_COMPONENT_POWERPC
189 #define SUBTARGET_PPC SUBTARGET(PPC)
190 #else
191 #define SUBTARGET_PPC
192 #endif
193
194 #ifdef LLVM_COMPONENT_SYSTEMZ
195 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
196 #else
197 #define SUBTARGET_SYSTEMZ
198 #endif
199
200 #ifdef LLVM_COMPONENT_MSP430
201 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
202 #else
203 #define SUBTARGET_MSP430
204 #endif
205
206 #ifdef LLVM_COMPONENT_RISCV
207 #define SUBTARGET_RISCV SUBTARGET(RISCV)
208 #else
209 #define SUBTARGET_RISCV
210 #endif
211
212 #ifdef LLVM_COMPONENT_SPARC
213 #define SUBTARGET_SPARC SUBTARGET(Sparc)
214 #else
215 #define SUBTARGET_SPARC
216 #endif
217
218 #ifdef LLVM_COMPONENT_HEXAGON
219 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
220 #else
221 #define SUBTARGET_HEXAGON
222 #endif
223
224 #define GEN_SUBTARGETS                                                         \
225   SUBTARGET_X86                                                                \
226   SUBTARGET_ARM                                                                \
227   SUBTARGET_AARCH64                                                            \
228   SUBTARGET_MIPS                                                               \
229   SUBTARGET_PPC                                                                \
230   SUBTARGET_SYSTEMZ                                                            \
231   SUBTARGET_MSP430                                                             \
232   SUBTARGET_SPARC                                                              \
233   SUBTARGET_HEXAGON                                                            \
234   SUBTARGET_RISCV                                                              \
235
236 #define SUBTARGET(x)                                                           \
237   namespace llvm {                                                             \
238   extern const SubtargetFeatureKV x##FeatureKV[];                              \
239   extern const SubtargetFeatureKV x##SubTypeKV[];                              \
240   }
241
242 GEN_SUBTARGETS
243 #undef SUBTARGET
244
245 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
246                                    const char *Feature) {
247   TargetMachine *Target = unwrap(TM);
248   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
249   return MCInfo->checkFeatures(std::string("+") + Feature);
250 }
251
252 enum class LLVMRustCodeModel {
253   Other,
254   Small,
255   Kernel,
256   Medium,
257   Large,
258   None,
259 };
260
261 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
262   switch (Model) {
263   case LLVMRustCodeModel::Small:
264     return CodeModel::Small;
265   case LLVMRustCodeModel::Kernel:
266     return CodeModel::Kernel;
267   case LLVMRustCodeModel::Medium:
268     return CodeModel::Medium;
269   case LLVMRustCodeModel::Large:
270     return CodeModel::Large;
271   default:
272     report_fatal_error("Bad CodeModel.");
273   }
274 }
275
276 enum class LLVMRustCodeGenOptLevel {
277   Other,
278   None,
279   Less,
280   Default,
281   Aggressive,
282 };
283
284 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
285   switch (Level) {
286   case LLVMRustCodeGenOptLevel::None:
287     return CodeGenOpt::None;
288   case LLVMRustCodeGenOptLevel::Less:
289     return CodeGenOpt::Less;
290   case LLVMRustCodeGenOptLevel::Default:
291     return CodeGenOpt::Default;
292   case LLVMRustCodeGenOptLevel::Aggressive:
293     return CodeGenOpt::Aggressive;
294   default:
295     report_fatal_error("Bad CodeGenOptLevel.");
296   }
297 }
298
299 enum class LLVMRustRelocMode {
300   Default,
301   Static,
302   PIC,
303   DynamicNoPic,
304   ROPI,
305   RWPI,
306   ROPIRWPI,
307 };
308
309 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
310   switch (RustReloc) {
311   case LLVMRustRelocMode::Default:
312     return None;
313   case LLVMRustRelocMode::Static:
314     return Reloc::Static;
315   case LLVMRustRelocMode::PIC:
316     return Reloc::PIC_;
317   case LLVMRustRelocMode::DynamicNoPic:
318     return Reloc::DynamicNoPIC;
319   case LLVMRustRelocMode::ROPI:
320     return Reloc::ROPI;
321   case LLVMRustRelocMode::RWPI:
322     return Reloc::RWPI;
323   case LLVMRustRelocMode::ROPIRWPI:
324     return Reloc::ROPI_RWPI;
325   }
326   report_fatal_error("Bad RelocModel.");
327 }
328
329 #ifdef LLVM_RUSTLLVM
330 /// getLongestEntryLength - Return the length of the longest entry in the table.
331 template<typename KV>
332 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
333   size_t MaxLen = 0;
334   for (auto &I : Table)
335     MaxLen = std::max(MaxLen, std::strlen(I.Key));
336   return MaxLen;
337 }
338
339 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
340   const TargetMachine *Target = unwrap(TM);
341   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
342   const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
343   const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
344   const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
345   unsigned MaxCPULen = getLongestEntryLength(CPUTable);
346
347   printf("Available CPUs for this target:\n");
348   if (HostArch == TargetArch) {
349     const StringRef HostCPU = sys::getHostCPUName();
350     printf("    %-*s - Select the CPU of the current host (currently %.*s).\n",
351       MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
352   }
353   for (auto &CPU : CPUTable)
354     printf("    %-*s\n", MaxCPULen, CPU.Key);
355   printf("\n");
356 }
357
358 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
359   const TargetMachine *Target = unwrap(TM);
360   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
361   const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
362   unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
363
364   printf("Available features for this target:\n");
365   for (auto &Feature : FeatTable)
366     printf("    %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
367   printf("\n");
368
369   printf("Use +feature to enable a feature, or -feature to disable it.\n"
370          "For example, rustc -C -target-cpu=mycpu -C "
371          "target-feature=+feature1,-feature2\n\n");
372 }
373
374 #else
375
376 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
377   printf("Target CPU help is not supported by this LLVM version.\n\n");
378 }
379
380 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
381   printf("Target features help is not supported by this LLVM version.\n\n");
382 }
383 #endif
384
385 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
386   StringRef Name = sys::getHostCPUName();
387   *len = Name.size();
388   return Name.data();
389 }
390
391 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
392     const char *TripleStr, const char *CPU, const char *Feature,
393     const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
394     LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
395     bool PositionIndependentExecutable, bool FunctionSections,
396     bool DataSections,
397     bool TrapUnreachable,
398     bool Singlethread,
399     bool AsmComments,
400     bool EmitStackSizeSection,
401     bool RelaxELFRelocations) {
402
403   auto OptLevel = fromRust(RustOptLevel);
404   auto RM = fromRust(RustReloc);
405
406   std::string Error;
407   Triple Trip(Triple::normalize(TripleStr));
408   const llvm::Target *TheTarget =
409       TargetRegistry::lookupTarget(Trip.getTriple(), Error);
410   if (TheTarget == nullptr) {
411     LLVMRustSetLastError(Error.c_str());
412     return nullptr;
413   }
414
415   TargetOptions Options;
416
417   Options.FloatABIType = FloatABI::Default;
418   if (UseSoftFloat) {
419     Options.FloatABIType = FloatABI::Soft;
420   }
421   Options.DataSections = DataSections;
422   Options.FunctionSections = FunctionSections;
423   Options.MCOptions.AsmVerbose = AsmComments;
424   Options.MCOptions.PreserveAsmComments = AsmComments;
425   Options.MCOptions.ABIName = ABIStr;
426   Options.RelaxELFRelocations = RelaxELFRelocations;
427
428   if (TrapUnreachable) {
429     // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
430     // This limits the extent of possible undefined behavior in some cases, as
431     // it prevents control flow from "falling through" into whatever code
432     // happens to be laid out next in memory.
433     Options.TrapUnreachable = true;
434   }
435
436   if (Singlethread) {
437     Options.ThreadModel = ThreadModel::Single;
438   }
439
440   Options.EmitStackSizeSection = EmitStackSizeSection;
441
442   Optional<CodeModel::Model> CM;
443   if (RustCM != LLVMRustCodeModel::None)
444     CM = fromRust(RustCM);
445   TargetMachine *TM = TheTarget->createTargetMachine(
446       Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
447   return wrap(TM);
448 }
449
450 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
451   delete unwrap(TM);
452 }
453
454 extern "C" void LLVMRustConfigurePassManagerBuilder(
455     LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
456     bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
457     const char* PGOGenPath, const char* PGOUsePath) {
458   unwrap(PMBR)->MergeFunctions = MergeFunctions;
459   unwrap(PMBR)->SLPVectorize = SLPVectorize;
460   unwrap(PMBR)->OptLevel = fromRust(OptLevel);
461   unwrap(PMBR)->LoopVectorize = LoopVectorize;
462   unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
463
464   if (PGOGenPath) {
465     assert(!PGOUsePath);
466     unwrap(PMBR)->EnablePGOInstrGen = true;
467     unwrap(PMBR)->PGOInstrGen = PGOGenPath;
468   }
469   if (PGOUsePath) {
470     assert(!PGOGenPath);
471     unwrap(PMBR)->PGOInstrUse = PGOUsePath;
472   }
473 }
474
475 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
476 // field of a PassManagerBuilder, we expose our own method of doing so.
477 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
478                                               LLVMModuleRef M,
479                                               bool DisableSimplifyLibCalls) {
480   Triple TargetTriple(unwrap(M)->getTargetTriple());
481   TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
482   if (DisableSimplifyLibCalls)
483     TLI->disableAllFunctions();
484   unwrap(PMBR)->LibraryInfo = TLI;
485 }
486
487 // Unfortunately, the LLVM C API doesn't provide a way to create the
488 // TargetLibraryInfo pass, so we use this method to do so.
489 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
490                                        bool DisableSimplifyLibCalls) {
491   Triple TargetTriple(unwrap(M)->getTargetTriple());
492   TargetLibraryInfoImpl TLII(TargetTriple);
493   if (DisableSimplifyLibCalls)
494     TLII.disableAllFunctions();
495   unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
496 }
497
498 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
499 // all the functions in a module, so we do that manually here. You'll find
500 // similar code in clang's BackendUtil.cpp file.
501 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
502                                                LLVMModuleRef M) {
503   llvm::legacy::FunctionPassManager *P =
504       unwrap<llvm::legacy::FunctionPassManager>(PMR);
505   P->doInitialization();
506
507   // Upgrade all calls to old intrinsics first.
508   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
509     UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
510
511   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
512        ++I)
513     if (!I->isDeclaration())
514       P->run(*I);
515
516   P->doFinalization();
517 }
518
519 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
520   // Initializing the command-line options more than once is not allowed. So,
521   // check if they've already been initialized.  (This could happen if we're
522   // being called from rustpkg, for example). If the arguments change, then
523   // that's just kinda unfortunate.
524   static bool Initialized = false;
525   if (Initialized)
526     return;
527   Initialized = true;
528   cl::ParseCommandLineOptions(Argc, Argv);
529 }
530
531 enum class LLVMRustFileType {
532   Other,
533   AssemblyFile,
534   ObjectFile,
535 };
536
537 #if LLVM_VERSION_GE(10, 0)
538 static CodeGenFileType fromRust(LLVMRustFileType Type) {
539   switch (Type) {
540   case LLVMRustFileType::AssemblyFile:
541     return CGFT_AssemblyFile;
542   case LLVMRustFileType::ObjectFile:
543     return CGFT_ObjectFile;
544   default:
545     report_fatal_error("Bad FileType.");
546   }
547 }
548 #else
549 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
550   switch (Type) {
551   case LLVMRustFileType::AssemblyFile:
552     return TargetMachine::CGFT_AssemblyFile;
553   case LLVMRustFileType::ObjectFile:
554     return TargetMachine::CGFT_ObjectFile;
555   default:
556     report_fatal_error("Bad FileType.");
557   }
558 }
559 #endif
560
561 extern "C" LLVMRustResult
562 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
563                         LLVMModuleRef M, const char *Path,
564                         LLVMRustFileType RustFileType) {
565   llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
566   auto FileType = fromRust(RustFileType);
567
568   std::string ErrorInfo;
569   std::error_code EC;
570   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
571   if (EC)
572     ErrorInfo = EC.message();
573   if (ErrorInfo != "") {
574     LLVMRustSetLastError(ErrorInfo.c_str());
575     return LLVMRustResult::Failure;
576   }
577
578   buffer_ostream BOS(OS);
579   unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
580   PM->run(*unwrap(M));
581
582   // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
583   // stream (OS), so the only real safe place to delete this is here? Don't we
584   // wish this was written in Rust?
585   LLVMDisposePassManager(PMR);
586   return LLVMRustResult::Success;
587 }
588
589
590 // Callback to demangle function name
591 // Parameters:
592 // * name to be demangled
593 // * name len
594 // * output buffer
595 // * output buffer len
596 // Returns len of demangled string, or 0 if demangle failed.
597 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
598
599
600 namespace {
601
602 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
603   DemangleFn Demangle;
604   std::vector<char> Buf;
605
606 public:
607   RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
608
609   // Return empty string if demangle failed
610   // or if name does not need to be demangled
611   StringRef CallDemangle(StringRef name) {
612     if (!Demangle) {
613       return StringRef();
614     }
615
616     if (Buf.size() < name.size() * 2) {
617       // Semangled name usually shorter than mangled,
618       // but allocate twice as much memory just in case
619       Buf.resize(name.size() * 2);
620     }
621
622     auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
623     if (!R) {
624       // Demangle failed.
625       return StringRef();
626     }
627
628     auto Demangled = StringRef(Buf.data(), R);
629     if (Demangled == name) {
630       // Do not print anything if demangled name is equal to mangled.
631       return StringRef();
632     }
633
634     return Demangled;
635   }
636
637   void emitFunctionAnnot(const Function *F,
638                          formatted_raw_ostream &OS) override {
639     StringRef Demangled = CallDemangle(F->getName());
640     if (Demangled.empty()) {
641         return;
642     }
643
644     OS << "; " << Demangled << "\n";
645   }
646
647   void emitInstructionAnnot(const Instruction *I,
648                             formatted_raw_ostream &OS) override {
649     const char *Name;
650     const Value *Value;
651     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
652       Name = "call";
653       Value = CI->getCalledValue();
654     } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
655       Name = "invoke";
656       Value = II->getCalledValue();
657     } else {
658       // Could demangle more operations, e. g.
659       // `store %place, @function`.
660       return;
661     }
662
663     if (!Value->hasName()) {
664       return;
665     }
666
667     StringRef Demangled = CallDemangle(Value->getName());
668     if (Demangled.empty()) {
669       return;
670     }
671
672     OS << "; " << Name << " " << Demangled << "\n";
673   }
674 };
675
676 } // namespace
677
678 extern "C" LLVMRustResult
679 LLVMRustPrintModule(LLVMModuleRef M, const char *Path, DemangleFn Demangle) {
680   std::string ErrorInfo;
681   std::error_code EC;
682   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
683   if (EC)
684     ErrorInfo = EC.message();
685   if (ErrorInfo != "") {
686     LLVMRustSetLastError(ErrorInfo.c_str());
687     return LLVMRustResult::Failure;
688   }
689
690   RustAssemblyAnnotationWriter AAW(Demangle);
691   formatted_raw_ostream FOS(OS);
692   unwrap(M)->print(FOS, &AAW);
693
694   return LLVMRustResult::Success;
695 }
696
697 extern "C" void LLVMRustPrintPasses() {
698   LLVMInitializePasses();
699   struct MyListener : PassRegistrationListener {
700     void passEnumerate(const PassInfo *Info) {
701       StringRef PassArg = Info->getPassArgument();
702       StringRef PassName = Info->getPassName();
703       if (!PassArg.empty()) {
704         // These unsigned->signed casts could theoretically overflow, but
705         // realistically never will (and even if, the result is implementation
706         // defined rather plain UB).
707         printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
708                (int)PassName.size(), PassName.data());
709       }
710     }
711   } Listener;
712
713   PassRegistry *PR = PassRegistry::getPassRegistry();
714   PR->enumerateWith(&Listener);
715 }
716
717 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
718                                             bool AddLifetimes) {
719   unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
720 }
721
722 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
723                                            size_t Len) {
724   llvm::legacy::PassManager passes;
725
726   auto PreserveFunctions = [=](const GlobalValue &GV) {
727     for (size_t I = 0; I < Len; I++) {
728       if (GV.getName() == Symbols[I]) {
729         return true;
730       }
731     }
732     return false;
733   };
734
735   passes.add(llvm::createInternalizePass(PreserveFunctions));
736
737   passes.run(*unwrap(M));
738 }
739
740 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
741   for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
742        ++GV) {
743     GV->setDoesNotThrow();
744     Function *F = dyn_cast<Function>(GV);
745     if (F == nullptr)
746       continue;
747
748     for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
749       for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
750         if (isa<InvokeInst>(I)) {
751           InvokeInst *CI = cast<InvokeInst>(I);
752           CI->setDoesNotThrow();
753         }
754       }
755     }
756   }
757 }
758
759 extern "C" void
760 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
761                                        LLVMTargetMachineRef TMR) {
762   TargetMachine *Target = unwrap(TMR);
763   unwrap(Module)->setDataLayout(Target->createDataLayout());
764 }
765
766 extern "C" void LLVMRustSetModulePICLevel(LLVMModuleRef M) {
767   unwrap(M)->setPICLevel(PICLevel::Level::BigPIC);
768 }
769
770 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
771   unwrap(M)->setPIELevel(PIELevel::Level::Large);
772 }
773
774 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
775 // right now. This ThinLTO support is only enabled on "recent ish" versions of
776 // LLVM, and otherwise it's just blanket rejected from other compilers.
777 //
778 // Most of this implementation is straight copied from LLVM. At the time of
779 // this writing it wasn't *quite* suitable to reuse more code from upstream
780 // for our purposes, but we should strive to upstream this support once it's
781 // ready to go! I figure we may want a bit of testing locally first before
782 // sending this upstream to LLVM. I hear though they're quite eager to receive
783 // feedback like this!
784 //
785 // If you're reading this code and wondering "what in the world" or you're
786 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
787 // then fear not! (ok maybe fear a little). All code here is mostly based
788 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
789 //
790 // You'll find that the general layout here roughly corresponds to the `run`
791 // method in that file as well as `ProcessThinLTOModule`. Functions are
792 // specifically commented below as well, but if you're updating this code
793 // or otherwise trying to understand it, the LLVM source will be useful in
794 // interpreting the mysteries within.
795 //
796 // Otherwise I'll apologize in advance, it probably requires a relatively
797 // significant investment on your part to "truly understand" what's going on
798 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
799 // and various online resources about ThinLTO to make heads or tails of all
800 // this.
801
802 // This is a shared data structure which *must* be threadsafe to share
803 // read-only amongst threads. This also corresponds basically to the arguments
804 // of the `ProcessThinLTOModule` function in the LLVM source.
805 struct LLVMRustThinLTOData {
806   // The combined index that is the global analysis over all modules we're
807   // performing ThinLTO for. This is mostly managed by LLVM.
808   ModuleSummaryIndex Index;
809
810   // All modules we may look at, stored as in-memory serialized versions. This
811   // is later used when inlining to ensure we can extract any module to inline
812   // from.
813   StringMap<MemoryBufferRef> ModuleMap;
814
815   // A set that we manage of everything we *don't* want internalized. Note that
816   // this includes all transitive references right now as well, but it may not
817   // always!
818   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
819
820   // Not 100% sure what these are, but they impact what's internalized and
821   // what's inlined across modules, I believe.
822   StringMap<FunctionImporter::ImportMapTy> ImportLists;
823   StringMap<FunctionImporter::ExportSetTy> ExportLists;
824   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
825
826   LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
827 };
828
829 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
830 struct LLVMRustThinLTOModule {
831   const char *identifier;
832   const char *data;
833   size_t len;
834 };
835
836 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
837 // does.
838 static const GlobalValueSummary *
839 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
840   auto StrongDefForLinker = llvm::find_if(
841       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
842         auto Linkage = Summary->linkage();
843         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
844                !GlobalValue::isWeakForLinker(Linkage);
845       });
846   if (StrongDefForLinker != GVSummaryList.end())
847     return StrongDefForLinker->get();
848
849   auto FirstDefForLinker = llvm::find_if(
850       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
851         auto Linkage = Summary->linkage();
852         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
853       });
854   if (FirstDefForLinker == GVSummaryList.end())
855     return nullptr;
856   return FirstDefForLinker->get();
857 }
858
859 // The main entry point for creating the global ThinLTO analysis. The structure
860 // here is basically the same as before threads are spawned in the `run`
861 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
862 extern "C" LLVMRustThinLTOData*
863 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
864                           int num_modules,
865                           const char **preserved_symbols,
866                           int num_symbols) {
867 #if LLVM_VERSION_GE(10, 0)
868   auto Ret = std::make_unique<LLVMRustThinLTOData>();
869 #else
870   auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
871 #endif
872
873   // Load each module's summary and merge it into one combined index
874   for (int i = 0; i < num_modules; i++) {
875     auto module = &modules[i];
876     StringRef buffer(module->data, module->len);
877     MemoryBufferRef mem_buffer(buffer, module->identifier);
878
879     Ret->ModuleMap[module->identifier] = mem_buffer;
880
881     if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
882       LLVMRustSetLastError(toString(std::move(Err)).c_str());
883       return nullptr;
884     }
885   }
886
887   // Collect for each module the list of function it defines (GUID -> Summary)
888   Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
889
890   // Convert the preserved symbols set from string to GUID, this is then needed
891   // for internalization.
892   for (int i = 0; i < num_symbols; i++) {
893     auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
894     Ret->GUIDPreservedSymbols.insert(GUID);
895   }
896
897   // Collect the import/export lists for all modules from the call-graph in the
898   // combined index
899   //
900   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
901   auto deadIsPrevailing = [&](GlobalValue::GUID G) {
902     return PrevailingType::Unknown;
903   };
904 #if LLVM_VERSION_GE(8, 0)
905   // We don't have a complete picture in our use of ThinLTO, just our immediate
906   // crate, so we need `ImportEnabled = false` to limit internalization.
907   // Otherwise, we sometimes lose `static` values -- see #60184.
908   computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
909                                   deadIsPrevailing, /* ImportEnabled = */ false);
910 #else
911   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
912 #endif
913   ComputeCrossModuleImport(
914     Ret->Index,
915     Ret->ModuleToDefinedGVSummaries,
916     Ret->ImportLists,
917     Ret->ExportLists
918   );
919
920   // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
921   // impacts the caching.
922   //
923   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
924   // being lifted from `lib/LTO/LTO.cpp` as well
925   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
926   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
927   for (auto &I : Ret->Index) {
928     if (I.second.SummaryList.size() > 1)
929       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
930   }
931   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
932     const auto &Prevailing = PrevailingCopy.find(GUID);
933     if (Prevailing == PrevailingCopy.end())
934       return true;
935     return Prevailing->second == S;
936   };
937   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
938                               GlobalValue::GUID GUID,
939                               GlobalValue::LinkageTypes NewLinkage) {
940     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
941   };
942 #if LLVM_VERSION_GE(9, 0)
943   thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
944                                   Ret->GUIDPreservedSymbols);
945 #elif LLVM_VERSION_GE(8, 0)
946   thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
947 #else
948   thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
949 #endif
950
951   // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
952   // callback below. This callback below will dictate the linkage for all
953   // summaries in the index, and we basically just only want to ensure that dead
954   // symbols are internalized. Otherwise everything that's already external
955   // linkage will stay as external, and internal will stay as internal.
956   std::set<GlobalValue::GUID> ExportedGUIDs;
957   for (auto &List : Ret->Index) {
958     for (auto &GVS: List.second.SummaryList) {
959       if (GlobalValue::isLocalLinkage(GVS->linkage()))
960         continue;
961       auto GUID = GVS->getOriginalName();
962       if (GVS->flags().Live)
963         ExportedGUIDs.insert(GUID);
964     }
965   }
966 #if LLVM_VERSION_GE(10, 0)
967   auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
968     const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
969     return (ExportList != Ret->ExportLists.end() &&
970       ExportList->second.count(VI)) ||
971       ExportedGUIDs.count(VI.getGUID());
972   };
973   thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported, isPrevailing);
974 #else
975   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
976     const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
977     return (ExportList != Ret->ExportLists.end() &&
978       ExportList->second.count(GUID)) ||
979       ExportedGUIDs.count(GUID);
980   };
981   thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
982 #endif
983
984   return Ret.release();
985 }
986
987 extern "C" void
988 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
989   delete Data;
990 }
991
992 // Below are the various passes that happen *per module* when doing ThinLTO.
993 //
994 // In other words, these are the functions that are all run concurrently
995 // with one another, one per module. The passes here correspond to the analysis
996 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
997 // `ProcessThinLTOModule` function. Here they're split up into separate steps
998 // so rustc can save off the intermediate bytecode between each step.
999
1000 extern "C" bool
1001 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1002   Module &Mod = *unwrap(M);
1003   if (renameModuleForThinLTO(Mod, Data->Index)) {
1004     LLVMRustSetLastError("renameModuleForThinLTO failed");
1005     return false;
1006   }
1007   return true;
1008 }
1009
1010 extern "C" bool
1011 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1012   Module &Mod = *unwrap(M);
1013   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1014 #if LLVM_VERSION_GE(8, 0)
1015   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
1016 #else
1017   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1018 #endif
1019   return true;
1020 }
1021
1022 extern "C" bool
1023 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1024   Module &Mod = *unwrap(M);
1025   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1026   thinLTOInternalizeModule(Mod, DefinedGlobals);
1027   return true;
1028 }
1029
1030 extern "C" bool
1031 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1032   Module &Mod = *unwrap(M);
1033
1034   const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1035   auto Loader = [&](StringRef Identifier) {
1036     const auto &Memory = Data->ModuleMap.lookup(Identifier);
1037     auto &Context = Mod.getContext();
1038     auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1039
1040     if (!MOrErr)
1041       return MOrErr;
1042
1043     // The rest of this closure is a workaround for
1044     // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1045     // we accidentally import wasm custom sections into different modules,
1046     // duplicating them by in the final output artifact.
1047     //
1048     // The issue is worked around here by manually removing the
1049     // `wasm.custom_sections` named metadata node from any imported module. This
1050     // we know isn't used by any optimization pass so there's no need for it to
1051     // be imported.
1052     //
1053     // Note that the metadata is currently lazily loaded, so we materialize it
1054     // here before looking up if there's metadata inside. The `FunctionImporter`
1055     // will immediately materialize metadata anyway after an import, so this
1056     // shouldn't be a perf hit.
1057     if (Error Err = (*MOrErr)->materializeMetadata()) {
1058       Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1059       return Ret;
1060     }
1061
1062     auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1063     if (WasmCustomSections)
1064       WasmCustomSections->eraseFromParent();
1065
1066     return MOrErr;
1067   };
1068   FunctionImporter Importer(Data->Index, Loader);
1069   Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1070   if (!Result) {
1071     LLVMRustSetLastError(toString(Result.takeError()).c_str());
1072     return false;
1073   }
1074   return true;
1075 }
1076
1077 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1078                                                       const char*, // importing module name
1079                                                       const char*); // imported module name
1080
1081 // Calls `module_name_callback` for each module import done by ThinLTO.
1082 // The callback is provided with regular null-terminated C strings.
1083 extern "C" void
1084 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1085                                 LLVMRustModuleNameCallback module_name_callback,
1086                                 void* callback_payload) {
1087   for (const auto& importing_module : data->ImportLists) {
1088     const std::string importing_module_id = importing_module.getKey().str();
1089     const auto& imports = importing_module.getValue();
1090     for (const auto& imported_module : imports) {
1091       const std::string imported_module_id = imported_module.getKey().str();
1092       module_name_callback(callback_payload,
1093                            importing_module_id.c_str(),
1094                            imported_module_id.c_str());
1095     }
1096   }
1097 }
1098
1099 // This struct and various functions are sort of a hack right now, but the
1100 // problem is that we've got in-memory LLVM modules after we generate and
1101 // optimize all codegen-units for one compilation in rustc. To be compatible
1102 // with the LTO support above we need to serialize the modules plus their
1103 // ThinLTO summary into memory.
1104 //
1105 // This structure is basically an owned version of a serialize module, with
1106 // a ThinLTO summary attached.
1107 struct LLVMRustThinLTOBuffer {
1108   std::string data;
1109 };
1110
1111 extern "C" LLVMRustThinLTOBuffer*
1112 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1113 #if LLVM_VERSION_GE(10, 0)
1114   auto Ret = std::make_unique<LLVMRustThinLTOBuffer>();
1115 #else
1116   auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1117 #endif
1118   {
1119     raw_string_ostream OS(Ret->data);
1120     {
1121       legacy::PassManager PM;
1122       PM.add(createWriteThinLTOBitcodePass(OS));
1123       PM.run(*unwrap(M));
1124     }
1125   }
1126   return Ret.release();
1127 }
1128
1129 extern "C" void
1130 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1131   delete Buffer;
1132 }
1133
1134 extern "C" const void*
1135 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1136   return Buffer->data.data();
1137 }
1138
1139 extern "C" size_t
1140 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1141   return Buffer->data.length();
1142 }
1143
1144 // This is what we used to parse upstream bitcode for actual ThinLTO
1145 // processing.  We'll call this once per module optimized through ThinLTO, and
1146 // it'll be called concurrently on many threads.
1147 extern "C" LLVMModuleRef
1148 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1149                            const char *data,
1150                            size_t len,
1151                            const char *identifier) {
1152   StringRef Data(data, len);
1153   MemoryBufferRef Buffer(Data, identifier);
1154   unwrap(Context)->enableDebugTypeODRUniquing();
1155   Expected<std::unique_ptr<Module>> SrcOrError =
1156       parseBitcodeFile(Buffer, *unwrap(Context));
1157   if (!SrcOrError) {
1158     LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1159     return nullptr;
1160   }
1161   return wrap(std::move(*SrcOrError).release());
1162 }
1163
1164 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1165 // the comment in `back/lto.rs` for why this exists.
1166 extern "C" void
1167 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1168                                 DICompileUnit **A,
1169                                 DICompileUnit **B) {
1170   Module *M = unwrap(Mod);
1171   DICompileUnit **Cur = A;
1172   DICompileUnit **Next = B;
1173   for (DICompileUnit *CU : M->debug_compile_units()) {
1174     *Cur = CU;
1175     Cur = Next;
1176     Next = nullptr;
1177     if (Cur == nullptr)
1178       break;
1179   }
1180 }
1181
1182 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1183 // the comment in `back/lto.rs` for why this exists.
1184 extern "C" void
1185 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1186   Module *M = unwrap(Mod);
1187
1188   // If the original source module didn't have a `DICompileUnit` then try to
1189   // merge all the existing compile units. If there aren't actually any though
1190   // then there's not much for us to do so return.
1191   if (Unit == nullptr) {
1192     for (DICompileUnit *CU : M->debug_compile_units()) {
1193       Unit = CU;
1194       break;
1195     }
1196     if (Unit == nullptr)
1197       return;
1198   }
1199
1200   // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1201   // process it recursively. Note that we specifically iterate over instructions
1202   // to ensure we feed everything into it.
1203   DebugInfoFinder Finder;
1204   Finder.processModule(*M);
1205   for (Function &F : M->functions()) {
1206     for (auto &FI : F) {
1207       for (Instruction &BI : FI) {
1208         if (auto Loc = BI.getDebugLoc())
1209           Finder.processLocation(*M, Loc);
1210         if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1211           Finder.processValue(*M, DVI);
1212         if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1213           Finder.processDeclare(*M, DDI);
1214       }
1215     }
1216   }
1217
1218   // After we've found all our debuginfo, rewrite all subprograms to point to
1219   // the same `DICompileUnit`.
1220   for (auto &F : Finder.subprograms()) {
1221     F->replaceUnit(Unit);
1222   }
1223
1224   // Erase any other references to other `DICompileUnit` instances, the verifier
1225   // will later ensure that we don't actually have any other stale references to
1226   // worry about.
1227   auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1228   MD->clearOperands();
1229   MD->addOperand(Unit);
1230 }