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