xref: /freebsd/contrib/llvm-project/llvm/lib/IR/DebugInfo.cpp (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the helper classes used to build and interpret debug
10 // information in LLVM IR form.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm-c/DebugInfo.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/Support/Casting.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <optional>
40 #include <utility>
41 
42 using namespace llvm;
43 using namespace llvm::at;
44 using namespace llvm::dwarf;
45 
46 /// Finds all intrinsics declaring local variables as living in the memory that
47 /// 'V' points to. This may include a mix of dbg.declare and
48 /// dbg.addr intrinsics.
49 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
50   // This function is hot. Check whether the value has any metadata to avoid a
51   // DenseMap lookup.
52   if (!V->isUsedByMetadata())
53     return {};
54   auto *L = LocalAsMetadata::getIfExists(V);
55   if (!L)
56     return {};
57   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
58   if (!MDV)
59     return {};
60 
61   TinyPtrVector<DbgVariableIntrinsic *> Declares;
62   for (User *U : MDV->users()) {
63     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
64       if (DII->isAddressOfVariable())
65         Declares.push_back(DII);
66   }
67 
68   return Declares;
69 }
70 
71 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
72   TinyPtrVector<DbgDeclareInst *> DDIs;
73   for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
74     if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
75       DDIs.push_back(DDI);
76   return DDIs;
77 }
78 
79 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
80   // This function is hot. Check whether the value has any metadata to avoid a
81   // DenseMap lookup.
82   if (!V->isUsedByMetadata())
83     return;
84   // TODO: If this value appears multiple times in a DIArgList, we should still
85   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
86   // This behaviour can be removed when we can automatically remove duplicates.
87   SmallPtrSet<DbgValueInst *, 4> EncounteredDbgValues;
88   if (auto *L = LocalAsMetadata::getIfExists(V)) {
89     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
90       for (User *U : MDV->users())
91         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
92           DbgValues.push_back(DVI);
93     }
94     for (Metadata *AL : L->getAllArgListUsers()) {
95       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
96         for (User *U : MDV->users())
97           if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
98             if (EncounteredDbgValues.insert(DVI).second)
99               DbgValues.push_back(DVI);
100       }
101     }
102   }
103 }
104 
105 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
106                         Value *V) {
107   // This function is hot. Check whether the value has any metadata to avoid a
108   // DenseMap lookup.
109   if (!V->isUsedByMetadata())
110     return;
111   // TODO: If this value appears multiple times in a DIArgList, we should still
112   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
113   // This behaviour can be removed when we can automatically remove duplicates.
114   SmallPtrSet<DbgVariableIntrinsic *, 4> EncounteredDbgValues;
115   if (auto *L = LocalAsMetadata::getIfExists(V)) {
116     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
117       for (User *U : MDV->users())
118         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
119           DbgUsers.push_back(DII);
120     }
121     for (Metadata *AL : L->getAllArgListUsers()) {
122       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
123         for (User *U : MDV->users())
124           if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
125             if (EncounteredDbgValues.insert(DII).second)
126               DbgUsers.push_back(DII);
127       }
128     }
129   }
130 }
131 
132 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
133   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
134     return LocalScope->getSubprogram();
135   return nullptr;
136 }
137 
138 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
139   // Original dbg.declare must have a location.
140   const DebugLoc &DeclareLoc = DII->getDebugLoc();
141   MDNode *Scope = DeclareLoc.getScope();
142   DILocation *InlinedAt = DeclareLoc.getInlinedAt();
143   // Because no machine insts can come from debug intrinsics, only the scope
144   // and inlinedAt is significant. Zero line numbers are used in case this
145   // DebugLoc leaks into any adjacent instructions. Produce an unknown location
146   // with the correct scope / inlinedAt fields.
147   return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
148 }
149 
150 //===----------------------------------------------------------------------===//
151 // DebugInfoFinder implementations.
152 //===----------------------------------------------------------------------===//
153 
154 void DebugInfoFinder::reset() {
155   CUs.clear();
156   SPs.clear();
157   GVs.clear();
158   TYs.clear();
159   Scopes.clear();
160   NodesSeen.clear();
161 }
162 
163 void DebugInfoFinder::processModule(const Module &M) {
164   for (auto *CU : M.debug_compile_units())
165     processCompileUnit(CU);
166   for (auto &F : M.functions()) {
167     if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
168       processSubprogram(SP);
169     // There could be subprograms from inlined functions referenced from
170     // instructions only. Walk the function to find them.
171     for (const BasicBlock &BB : F)
172       for (const Instruction &I : BB)
173         processInstruction(M, I);
174   }
175 }
176 
177 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
178   if (!addCompileUnit(CU))
179     return;
180   for (auto *DIG : CU->getGlobalVariables()) {
181     if (!addGlobalVariable(DIG))
182       continue;
183     auto *GV = DIG->getVariable();
184     processScope(GV->getScope());
185     processType(GV->getType());
186   }
187   for (auto *ET : CU->getEnumTypes())
188     processType(ET);
189   for (auto *RT : CU->getRetainedTypes())
190     if (auto *T = dyn_cast<DIType>(RT))
191       processType(T);
192     else
193       processSubprogram(cast<DISubprogram>(RT));
194   for (auto *Import : CU->getImportedEntities()) {
195     auto *Entity = Import->getEntity();
196     if (auto *T = dyn_cast<DIType>(Entity))
197       processType(T);
198     else if (auto *SP = dyn_cast<DISubprogram>(Entity))
199       processSubprogram(SP);
200     else if (auto *NS = dyn_cast<DINamespace>(Entity))
201       processScope(NS->getScope());
202     else if (auto *M = dyn_cast<DIModule>(Entity))
203       processScope(M->getScope());
204   }
205 }
206 
207 void DebugInfoFinder::processInstruction(const Module &M,
208                                          const Instruction &I) {
209   if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
210     processVariable(M, *DVI);
211 
212   if (auto DbgLoc = I.getDebugLoc())
213     processLocation(M, DbgLoc.get());
214 }
215 
216 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
217   if (!Loc)
218     return;
219   processScope(Loc->getScope());
220   processLocation(M, Loc->getInlinedAt());
221 }
222 
223 void DebugInfoFinder::processType(DIType *DT) {
224   if (!addType(DT))
225     return;
226   processScope(DT->getScope());
227   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
228     for (DIType *Ref : ST->getTypeArray())
229       processType(Ref);
230     return;
231   }
232   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
233     processType(DCT->getBaseType());
234     for (Metadata *D : DCT->getElements()) {
235       if (auto *T = dyn_cast<DIType>(D))
236         processType(T);
237       else if (auto *SP = dyn_cast<DISubprogram>(D))
238         processSubprogram(SP);
239     }
240     return;
241   }
242   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
243     processType(DDT->getBaseType());
244   }
245 }
246 
247 void DebugInfoFinder::processScope(DIScope *Scope) {
248   if (!Scope)
249     return;
250   if (auto *Ty = dyn_cast<DIType>(Scope)) {
251     processType(Ty);
252     return;
253   }
254   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
255     addCompileUnit(CU);
256     return;
257   }
258   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
259     processSubprogram(SP);
260     return;
261   }
262   if (!addScope(Scope))
263     return;
264   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
265     processScope(LB->getScope());
266   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
267     processScope(NS->getScope());
268   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
269     processScope(M->getScope());
270   }
271 }
272 
273 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
274   if (!addSubprogram(SP))
275     return;
276   processScope(SP->getScope());
277   // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
278   // ValueMap containing identity mappings for all of the DICompileUnit's, not
279   // just DISubprogram's, referenced from anywhere within the Function being
280   // cloned prior to calling MapMetadata / RemapInstruction to avoid their
281   // duplication later as DICompileUnit's are also directly referenced by
282   // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
283   // Also, DICompileUnit's may reference DISubprogram's too and therefore need
284   // to be at least looked through.
285   processCompileUnit(SP->getUnit());
286   processType(SP->getType());
287   for (auto *Element : SP->getTemplateParams()) {
288     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
289       processType(TType->getType());
290     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
291       processType(TVal->getType());
292     }
293   }
294 }
295 
296 void DebugInfoFinder::processVariable(const Module &M,
297                                       const DbgVariableIntrinsic &DVI) {
298   auto *N = dyn_cast<MDNode>(DVI.getVariable());
299   if (!N)
300     return;
301 
302   auto *DV = dyn_cast<DILocalVariable>(N);
303   if (!DV)
304     return;
305 
306   if (!NodesSeen.insert(DV).second)
307     return;
308   processScope(DV->getScope());
309   processType(DV->getType());
310 }
311 
312 bool DebugInfoFinder::addType(DIType *DT) {
313   if (!DT)
314     return false;
315 
316   if (!NodesSeen.insert(DT).second)
317     return false;
318 
319   TYs.push_back(const_cast<DIType *>(DT));
320   return true;
321 }
322 
323 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
324   if (!CU)
325     return false;
326   if (!NodesSeen.insert(CU).second)
327     return false;
328 
329   CUs.push_back(CU);
330   return true;
331 }
332 
333 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
334   if (!NodesSeen.insert(DIG).second)
335     return false;
336 
337   GVs.push_back(DIG);
338   return true;
339 }
340 
341 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
342   if (!SP)
343     return false;
344 
345   if (!NodesSeen.insert(SP).second)
346     return false;
347 
348   SPs.push_back(SP);
349   return true;
350 }
351 
352 bool DebugInfoFinder::addScope(DIScope *Scope) {
353   if (!Scope)
354     return false;
355   // FIXME: Ocaml binding generates a scope with no content, we treat it
356   // as null for now.
357   if (Scope->getNumOperands() == 0)
358     return false;
359   if (!NodesSeen.insert(Scope).second)
360     return false;
361   Scopes.push_back(Scope);
362   return true;
363 }
364 
365 static MDNode *updateLoopMetadataDebugLocationsImpl(
366     MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
367   assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
368          "Loop ID needs at least one operand");
369   assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
370          "Loop ID should refer to itself");
371 
372   // Save space for the self-referential LoopID.
373   SmallVector<Metadata *, 4> MDs = {nullptr};
374 
375   for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
376     Metadata *MD = OrigLoopID->getOperand(i);
377     if (!MD)
378       MDs.push_back(nullptr);
379     else if (Metadata *NewMD = Updater(MD))
380       MDs.push_back(NewMD);
381   }
382 
383   MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
384   // Insert the self-referential LoopID.
385   NewLoopID->replaceOperandWith(0, NewLoopID);
386   return NewLoopID;
387 }
388 
389 void llvm::updateLoopMetadataDebugLocations(
390     Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
391   MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
392   if (!OrigLoopID)
393     return;
394   MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
395   I.setMetadata(LLVMContext::MD_loop, NewLoopID);
396 }
397 
398 /// Return true if a node is a DILocation or if a DILocation is
399 /// indirectly referenced by one of the node's children.
400 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
401                                   SmallPtrSetImpl<Metadata *> &Reachable,
402                                   Metadata *MD) {
403   MDNode *N = dyn_cast_or_null<MDNode>(MD);
404   if (!N)
405     return false;
406   if (isa<DILocation>(N) || Reachable.count(N))
407     return true;
408   if (!Visited.insert(N).second)
409     return false;
410   for (auto &OpIt : N->operands()) {
411     Metadata *Op = OpIt.get();
412     if (isDILocationReachable(Visited, Reachable, Op)) {
413       Reachable.insert(N);
414       return true;
415     }
416   }
417   return false;
418 }
419 
420 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
421   assert(!N->operands().empty() && "Missing self reference?");
422   SmallPtrSet<Metadata *, 8> Visited, DILocationReachable;
423   // If we already visited N, there is nothing to do.
424   if (!Visited.insert(N).second)
425     return N;
426 
427   // If there is no debug location, we do not have to rewrite this
428   // MDNode. This loop also initializes DILocationReachable, later
429   // needed by updateLoopMetadataDebugLocationsImpl; the use of
430   // count_if avoids an early exit.
431   if (!std::count_if(N->op_begin() + 1, N->op_end(),
432                      [&Visited, &DILocationReachable](const MDOperand &Op) {
433                        return isDILocationReachable(
434                                   Visited, DILocationReachable, Op.get());
435                      }))
436     return N;
437 
438   // If there is only the debug location without any actual loop metadata, we
439   // can remove the metadata.
440   if (llvm::all_of(llvm::drop_begin(N->operands()),
441                    [&Visited, &DILocationReachable](const MDOperand &Op) {
442                      return isDILocationReachable(Visited, DILocationReachable,
443                                                   Op.get());
444                    }))
445     return nullptr;
446 
447   return updateLoopMetadataDebugLocationsImpl(
448       N, [&DILocationReachable](Metadata *MD) -> Metadata * {
449         if (isa<DILocation>(MD) || DILocationReachable.count(MD))
450           return nullptr;
451         return MD;
452       });
453 }
454 
455 bool llvm::stripDebugInfo(Function &F) {
456   bool Changed = false;
457   if (F.hasMetadata(LLVMContext::MD_dbg)) {
458     Changed = true;
459     F.setSubprogram(nullptr);
460   }
461 
462   DenseMap<MDNode *, MDNode *> LoopIDsMap;
463   for (BasicBlock &BB : F) {
464     for (Instruction &I : llvm::make_early_inc_range(BB)) {
465       if (isa<DbgInfoIntrinsic>(&I)) {
466         I.eraseFromParent();
467         Changed = true;
468         continue;
469       }
470       if (I.getDebugLoc()) {
471         Changed = true;
472         I.setDebugLoc(DebugLoc());
473       }
474       if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
475         auto *NewLoopID = LoopIDsMap.lookup(LoopID);
476         if (!NewLoopID)
477           NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
478         if (NewLoopID != LoopID)
479           I.setMetadata(LLVMContext::MD_loop, NewLoopID);
480       }
481       // Strip other attachments that are or use debug info.
482       if (I.hasMetadataOtherThanDebugLoc()) {
483         // Heapallocsites point into the DIType system.
484         I.setMetadata("heapallocsite", nullptr);
485         // DIAssignID are debug info metadata primitives.
486         I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
487       }
488     }
489   }
490   return Changed;
491 }
492 
493 bool llvm::StripDebugInfo(Module &M) {
494   bool Changed = false;
495 
496   for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
497     // We're stripping debug info, and without them, coverage information
498     // doesn't quite make sense.
499     if (NMD.getName().startswith("llvm.dbg.") ||
500         NMD.getName() == "llvm.gcov") {
501       NMD.eraseFromParent();
502       Changed = true;
503     }
504   }
505 
506   for (Function &F : M)
507     Changed |= stripDebugInfo(F);
508 
509   for (auto &GV : M.globals()) {
510     Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
511   }
512 
513   if (GVMaterializer *Materializer = M.getMaterializer())
514     Materializer->setStripDebugInfo();
515 
516   return Changed;
517 }
518 
519 namespace {
520 
521 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
522 class DebugTypeInfoRemoval {
523   DenseMap<Metadata *, Metadata *> Replacements;
524 
525 public:
526   /// The (void)() type.
527   MDNode *EmptySubroutineType;
528 
529 private:
530   /// Remember what linkage name we originally had before stripping. If we end
531   /// up making two subprograms identical who originally had different linkage
532   /// names, then we need to make one of them distinct, to avoid them getting
533   /// uniqued. Maps the new node to the old linkage name.
534   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
535 
536   // TODO: Remember the distinct subprogram we created for a given linkage name,
537   // so that we can continue to unique whenever possible. Map <newly created
538   // node, old linkage name> to the first (possibly distinct) mdsubprogram
539   // created for that combination. This is not strictly needed for correctness,
540   // but can cut down on the number of MDNodes and let us diff cleanly with the
541   // output of -gline-tables-only.
542 
543 public:
544   DebugTypeInfoRemoval(LLVMContext &C)
545       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
546                                                   MDNode::get(C, {}))) {}
547 
548   Metadata *map(Metadata *M) {
549     if (!M)
550       return nullptr;
551     auto Replacement = Replacements.find(M);
552     if (Replacement != Replacements.end())
553       return Replacement->second;
554 
555     return M;
556   }
557   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
558 
559   /// Recursively remap N and all its referenced children. Does a DF post-order
560   /// traversal, so as to remap bottoms up.
561   void traverseAndRemap(MDNode *N) { traverse(N); }
562 
563 private:
564   // Create a new DISubprogram, to replace the one given.
565   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
566     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
567     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
568     DISubprogram *Declaration = nullptr;
569     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
570     DIType *ContainingType =
571         cast_or_null<DIType>(map(MDS->getContainingType()));
572     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
573     auto Variables = nullptr;
574     auto TemplateParams = nullptr;
575 
576     // Make a distinct DISubprogram, for situations that warrent it.
577     auto distinctMDSubprogram = [&]() {
578       return DISubprogram::getDistinct(
579           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
580           FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
581           ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
582           MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
583           Variables);
584     };
585 
586     if (MDS->isDistinct())
587       return distinctMDSubprogram();
588 
589     auto *NewMDS = DISubprogram::get(
590         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
591         FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
592         MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
593         MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
594 
595     StringRef OldLinkageName = MDS->getLinkageName();
596 
597     // See if we need to make a distinct one.
598     auto OrigLinkage = NewToLinkageName.find(NewMDS);
599     if (OrigLinkage != NewToLinkageName.end()) {
600       if (OrigLinkage->second == OldLinkageName)
601         // We're good.
602         return NewMDS;
603 
604       // Otherwise, need to make a distinct one.
605       // TODO: Query the map to see if we already have one.
606       return distinctMDSubprogram();
607     }
608 
609     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
610     return NewMDS;
611   }
612 
613   /// Create a new compile unit, to replace the one given
614   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
615     // Drop skeleton CUs.
616     if (CU->getDWOId())
617       return nullptr;
618 
619     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
620     MDTuple *EnumTypes = nullptr;
621     MDTuple *RetainedTypes = nullptr;
622     MDTuple *GlobalVariables = nullptr;
623     MDTuple *ImportedEntities = nullptr;
624     return DICompileUnit::getDistinct(
625         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
626         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
627         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
628         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
629         CU->getDWOId(), CU->getSplitDebugInlining(),
630         CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
631         CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
632   }
633 
634   DILocation *getReplacementMDLocation(DILocation *MLD) {
635     auto *Scope = map(MLD->getScope());
636     auto *InlinedAt = map(MLD->getInlinedAt());
637     if (MLD->isDistinct())
638       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
639                                      MLD->getColumn(), Scope, InlinedAt);
640     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
641                            Scope, InlinedAt);
642   }
643 
644   /// Create a new generic MDNode, to replace the one given
645   MDNode *getReplacementMDNode(MDNode *N) {
646     SmallVector<Metadata *, 8> Ops;
647     Ops.reserve(N->getNumOperands());
648     for (auto &I : N->operands())
649       if (I)
650         Ops.push_back(map(I));
651     auto *Ret = MDNode::get(N->getContext(), Ops);
652     return Ret;
653   }
654 
655   /// Attempt to re-map N to a newly created node.
656   void remap(MDNode *N) {
657     if (Replacements.count(N))
658       return;
659 
660     auto doRemap = [&](MDNode *N) -> MDNode * {
661       if (!N)
662         return nullptr;
663       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
664         remap(MDSub->getUnit());
665         return getReplacementSubprogram(MDSub);
666       }
667       if (isa<DISubroutineType>(N))
668         return EmptySubroutineType;
669       if (auto *CU = dyn_cast<DICompileUnit>(N))
670         return getReplacementCU(CU);
671       if (isa<DIFile>(N))
672         return N;
673       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
674         // Remap to our referenced scope (recursively).
675         return mapNode(MDLB->getScope());
676       if (auto *MLD = dyn_cast<DILocation>(N))
677         return getReplacementMDLocation(MLD);
678 
679       // Otherwise, if we see these, just drop them now. Not strictly necessary,
680       // but this speeds things up a little.
681       if (isa<DINode>(N))
682         return nullptr;
683 
684       return getReplacementMDNode(N);
685     };
686     Replacements[N] = doRemap(N);
687   }
688 
689   /// Do the remapping traversal.
690   void traverse(MDNode *);
691 };
692 
693 } // end anonymous namespace
694 
695 void DebugTypeInfoRemoval::traverse(MDNode *N) {
696   if (!N || Replacements.count(N))
697     return;
698 
699   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
700   // parts of the graph.
701   auto prune = [](MDNode *Parent, MDNode *Child) {
702     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
703       return Child == MDS->getRetainedNodes().get();
704     return false;
705   };
706 
707   SmallVector<MDNode *, 16> ToVisit;
708   DenseSet<MDNode *> Opened;
709 
710   // Visit each node starting at N in post order, and map them.
711   ToVisit.push_back(N);
712   while (!ToVisit.empty()) {
713     auto *N = ToVisit.back();
714     if (!Opened.insert(N).second) {
715       // Close it.
716       remap(N);
717       ToVisit.pop_back();
718       continue;
719     }
720     for (auto &I : N->operands())
721       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
722         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
723             !isa<DICompileUnit>(MDN))
724           ToVisit.push_back(MDN);
725   }
726 }
727 
728 bool llvm::stripNonLineTableDebugInfo(Module &M) {
729   bool Changed = false;
730 
731   // First off, delete the debug intrinsics.
732   auto RemoveUses = [&](StringRef Name) {
733     if (auto *DbgVal = M.getFunction(Name)) {
734       while (!DbgVal->use_empty())
735         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
736       DbgVal->eraseFromParent();
737       Changed = true;
738     }
739   };
740   RemoveUses("llvm.dbg.addr");
741   RemoveUses("llvm.dbg.declare");
742   RemoveUses("llvm.dbg.label");
743   RemoveUses("llvm.dbg.value");
744 
745   // Delete non-CU debug info named metadata nodes.
746   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
747        NMI != NME;) {
748     NamedMDNode *NMD = &*NMI;
749     ++NMI;
750     // Specifically keep dbg.cu around.
751     if (NMD->getName() == "llvm.dbg.cu")
752       continue;
753   }
754 
755   // Drop all dbg attachments from global variables.
756   for (auto &GV : M.globals())
757     GV.eraseMetadata(LLVMContext::MD_dbg);
758 
759   DebugTypeInfoRemoval Mapper(M.getContext());
760   auto remap = [&](MDNode *Node) -> MDNode * {
761     if (!Node)
762       return nullptr;
763     Mapper.traverseAndRemap(Node);
764     auto *NewNode = Mapper.mapNode(Node);
765     Changed |= Node != NewNode;
766     Node = NewNode;
767     return NewNode;
768   };
769 
770   // Rewrite the DebugLocs to be equivalent to what
771   // -gline-tables-only would have created.
772   for (auto &F : M) {
773     if (auto *SP = F.getSubprogram()) {
774       Mapper.traverseAndRemap(SP);
775       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
776       Changed |= SP != NewSP;
777       F.setSubprogram(NewSP);
778     }
779     for (auto &BB : F) {
780       for (auto &I : BB) {
781         auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
782           auto *Scope = DL.getScope();
783           MDNode *InlinedAt = DL.getInlinedAt();
784           Scope = remap(Scope);
785           InlinedAt = remap(InlinedAt);
786           return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
787                                  Scope, InlinedAt);
788         };
789 
790         if (I.getDebugLoc() != DebugLoc())
791           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
792 
793         // Remap DILocations in llvm.loop attachments.
794         updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
795           if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
796             return remapDebugLoc(Loc).get();
797           return MD;
798         });
799 
800         // Strip heapallocsite attachments, they point into the DIType system.
801         if (I.hasMetadataOtherThanDebugLoc())
802           I.setMetadata("heapallocsite", nullptr);
803       }
804     }
805   }
806 
807   // Create a new llvm.dbg.cu, which is equivalent to the one
808   // -gline-tables-only would have created.
809   for (auto &NMD : M.getNamedMDList()) {
810     SmallVector<MDNode *, 8> Ops;
811     for (MDNode *Op : NMD.operands())
812       Ops.push_back(remap(Op));
813 
814     if (!Changed)
815       continue;
816 
817     NMD.clearOperands();
818     for (auto *Op : Ops)
819       if (Op)
820         NMD.addOperand(Op);
821   }
822   return Changed;
823 }
824 
825 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
826   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
827           M.getModuleFlag("Debug Info Version")))
828     return Val->getZExtValue();
829   return 0;
830 }
831 
832 void Instruction::applyMergedLocation(const DILocation *LocA,
833                                       const DILocation *LocB) {
834   setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
835 }
836 
837 void Instruction::mergeDIAssignID(
838     ArrayRef<const Instruction *> SourceInstructions) {
839   // Replace all uses (and attachments) of all the DIAssignIDs
840   // on SourceInstructions with a single merged value.
841   assert(getFunction() && "Uninserted instruction merged");
842   // Collect up the DIAssignID tags.
843   SmallVector<DIAssignID *, 4> IDs;
844   for (const Instruction *I : SourceInstructions) {
845     if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
846       IDs.push_back(cast<DIAssignID>(MD));
847     assert(getFunction() == I->getFunction() &&
848            "Merging with instruction from another function not allowed");
849   }
850 
851   // Add this instruction's DIAssignID too, if it has one.
852   if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
853     IDs.push_back(cast<DIAssignID>(MD));
854 
855   if (IDs.empty())
856     return; // No DIAssignID tags to process.
857 
858   DIAssignID *MergeID = IDs[0];
859   for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
860     if (*It != MergeID)
861       at::RAUW(*It, MergeID);
862   }
863   setMetadata(LLVMContext::MD_DIAssignID, MergeID);
864 }
865 
866 void Instruction::updateLocationAfterHoist() { dropLocation(); }
867 
868 void Instruction::dropLocation() {
869   const DebugLoc &DL = getDebugLoc();
870   if (!DL)
871     return;
872 
873   // If this isn't a call, drop the location to allow a location from a
874   // preceding instruction to propagate.
875   bool MayLowerToCall = false;
876   if (isa<CallBase>(this)) {
877     auto *II = dyn_cast<IntrinsicInst>(this);
878     MayLowerToCall =
879         !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
880   }
881 
882   if (!MayLowerToCall) {
883     setDebugLoc(DebugLoc());
884     return;
885   }
886 
887   // Set a line 0 location for calls to preserve scope information in case
888   // inlining occurs.
889   DISubprogram *SP = getFunction()->getSubprogram();
890   if (SP)
891     // If a function scope is available, set it on the line 0 location. When
892     // hoisting a call to a predecessor block, using the function scope avoids
893     // making it look like the callee was reached earlier than it should be.
894     setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
895   else
896     // The parent function has no scope. Go ahead and drop the location. If
897     // the parent function is inlined, and the callee has a subprogram, the
898     // inliner will attach a location to the call.
899     //
900     // One alternative is to set a line 0 location with the existing scope and
901     // inlinedAt info. The location might be sensitive to when inlining occurs.
902     setDebugLoc(DebugLoc());
903 }
904 
905 //===----------------------------------------------------------------------===//
906 // LLVM C API implementations.
907 //===----------------------------------------------------------------------===//
908 
909 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
910   switch (lang) {
911 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR)                 \
912   case LLVMDWARFSourceLanguage##NAME:                                          \
913     return ID;
914 #include "llvm/BinaryFormat/Dwarf.def"
915 #undef HANDLE_DW_LANG
916   }
917   llvm_unreachable("Unhandled Tag");
918 }
919 
920 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
921   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
922 }
923 
924 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
925   return static_cast<DINode::DIFlags>(Flags);
926 }
927 
928 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
929   return static_cast<LLVMDIFlags>(Flags);
930 }
931 
932 static DISubprogram::DISPFlags
933 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
934   return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
935 }
936 
937 unsigned LLVMDebugMetadataVersion() {
938   return DEBUG_METADATA_VERSION;
939 }
940 
941 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
942   return wrap(new DIBuilder(*unwrap(M), false));
943 }
944 
945 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
946   return wrap(new DIBuilder(*unwrap(M)));
947 }
948 
949 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
950   return getDebugMetadataVersionFromModule(*unwrap(M));
951 }
952 
953 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
954   return StripDebugInfo(*unwrap(M));
955 }
956 
957 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
958   delete unwrap(Builder);
959 }
960 
961 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
962   unwrap(Builder)->finalize();
963 }
964 
965 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
966                                      LLVMMetadataRef subprogram) {
967   unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
968 }
969 
970 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
971     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
972     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
973     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
974     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
975     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
976     LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
977     const char *SDK, size_t SDKLen) {
978   auto File = unwrapDI<DIFile>(FileRef);
979 
980   return wrap(unwrap(Builder)->createCompileUnit(
981       map_from_llvmDWARFsourcelanguage(Lang), File,
982       StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
983       RuntimeVer, StringRef(SplitName, SplitNameLen),
984       static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
985       SplitDebugInlining, DebugInfoForProfiling,
986       DICompileUnit::DebugNameTableKind::Default, false,
987       StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
988 }
989 
990 LLVMMetadataRef
991 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
992                         size_t FilenameLen, const char *Directory,
993                         size_t DirectoryLen) {
994   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
995                                           StringRef(Directory, DirectoryLen)));
996 }
997 
998 LLVMMetadataRef
999 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
1000                           const char *Name, size_t NameLen,
1001                           const char *ConfigMacros, size_t ConfigMacrosLen,
1002                           const char *IncludePath, size_t IncludePathLen,
1003                           const char *APINotesFile, size_t APINotesFileLen) {
1004   return wrap(unwrap(Builder)->createModule(
1005       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
1006       StringRef(ConfigMacros, ConfigMacrosLen),
1007       StringRef(IncludePath, IncludePathLen),
1008       StringRef(APINotesFile, APINotesFileLen)));
1009 }
1010 
1011 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
1012                                              LLVMMetadataRef ParentScope,
1013                                              const char *Name, size_t NameLen,
1014                                              LLVMBool ExportSymbols) {
1015   return wrap(unwrap(Builder)->createNameSpace(
1016       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
1017 }
1018 
1019 LLVMMetadataRef LLVMDIBuilderCreateFunction(
1020     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1021     size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
1022     LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1023     LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
1024     unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
1025   return wrap(unwrap(Builder)->createFunction(
1026       unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
1027       unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
1028       map_from_llvmDIFlags(Flags),
1029       pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
1030       nullptr, nullptr));
1031 }
1032 
1033 
1034 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
1035     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1036     LLVMMetadataRef File, unsigned Line, unsigned Col) {
1037   return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
1038                                                   unwrapDI<DIFile>(File),
1039                                                   Line, Col));
1040 }
1041 
1042 LLVMMetadataRef
1043 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
1044                                     LLVMMetadataRef Scope,
1045                                     LLVMMetadataRef File,
1046                                     unsigned Discriminator) {
1047   return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
1048                                                       unwrapDI<DIFile>(File),
1049                                                       Discriminator));
1050 }
1051 
1052 LLVMMetadataRef
1053 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
1054                                                LLVMMetadataRef Scope,
1055                                                LLVMMetadataRef NS,
1056                                                LLVMMetadataRef File,
1057                                                unsigned Line) {
1058   return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1059                                                     unwrapDI<DINamespace>(NS),
1060                                                     unwrapDI<DIFile>(File),
1061                                                     Line));
1062 }
1063 
1064 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1065     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1066     LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1067     LLVMMetadataRef *Elements, unsigned NumElements) {
1068   auto Elts =
1069       (NumElements > 0)
1070           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1071           : nullptr;
1072   return wrap(unwrap(Builder)->createImportedModule(
1073       unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1074       unwrapDI<DIFile>(File), Line, Elts));
1075 }
1076 
1077 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1078     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1079     LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1080     unsigned NumElements) {
1081   auto Elts =
1082       (NumElements > 0)
1083           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1084           : nullptr;
1085   return wrap(unwrap(Builder)->createImportedModule(
1086       unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1087       Line, Elts));
1088 }
1089 
1090 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1091     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1092     LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1093     LLVMMetadataRef *Elements, unsigned NumElements) {
1094   auto Elts =
1095       (NumElements > 0)
1096           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1097           : nullptr;
1098   return wrap(unwrap(Builder)->createImportedDeclaration(
1099       unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1100       Line, {Name, NameLen}, Elts));
1101 }
1102 
1103 LLVMMetadataRef
1104 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1105                                  unsigned Column, LLVMMetadataRef Scope,
1106                                  LLVMMetadataRef InlinedAt) {
1107   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1108                               unwrap(InlinedAt)));
1109 }
1110 
1111 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1112   return unwrapDI<DILocation>(Location)->getLine();
1113 }
1114 
1115 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1116   return unwrapDI<DILocation>(Location)->getColumn();
1117 }
1118 
1119 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1120   return wrap(unwrapDI<DILocation>(Location)->getScope());
1121 }
1122 
1123 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1124   return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1125 }
1126 
1127 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1128   return wrap(unwrapDI<DIScope>(Scope)->getFile());
1129 }
1130 
1131 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1132   auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1133   *Len = Dir.size();
1134   return Dir.data();
1135 }
1136 
1137 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1138   auto Name = unwrapDI<DIFile>(File)->getFilename();
1139   *Len = Name.size();
1140   return Name.data();
1141 }
1142 
1143 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1144   if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1145     *Len = Src->size();
1146     return Src->data();
1147   }
1148   *Len = 0;
1149   return "";
1150 }
1151 
1152 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1153                                          LLVMMetadataRef ParentMacroFile,
1154                                          unsigned Line,
1155                                          LLVMDWARFMacinfoRecordType RecordType,
1156                                          const char *Name, size_t NameLen,
1157                                          const char *Value, size_t ValueLen) {
1158   return wrap(
1159       unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1160                                    static_cast<MacinfoRecordType>(RecordType),
1161                                    {Name, NameLen}, {Value, ValueLen}));
1162 }
1163 
1164 LLVMMetadataRef
1165 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1166                                  LLVMMetadataRef ParentMacroFile, unsigned Line,
1167                                  LLVMMetadataRef File) {
1168   return wrap(unwrap(Builder)->createTempMacroFile(
1169       unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1170 }
1171 
1172 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1173                                               const char *Name, size_t NameLen,
1174                                               int64_t Value,
1175                                               LLVMBool IsUnsigned) {
1176   return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1177                                                 IsUnsigned != 0));
1178 }
1179 
1180 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1181   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1182   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1183   uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1184   unsigned NumElements, LLVMMetadataRef ClassTy) {
1185 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1186                                                NumElements});
1187 return wrap(unwrap(Builder)->createEnumerationType(
1188     unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1189     LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1190 }
1191 
1192 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1193   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1194   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1195   uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1196   LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1197   const char *UniqueId, size_t UniqueIdLen) {
1198   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1199                                                  NumElements});
1200   return wrap(unwrap(Builder)->createUnionType(
1201      unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1202      LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1203      Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1204 }
1205 
1206 
1207 LLVMMetadataRef
1208 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1209                              uint32_t AlignInBits, LLVMMetadataRef Ty,
1210                              LLVMMetadataRef *Subscripts,
1211                              unsigned NumSubscripts) {
1212   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1213                                                  NumSubscripts});
1214   return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1215                                                unwrapDI<DIType>(Ty), Subs));
1216 }
1217 
1218 LLVMMetadataRef
1219 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1220                               uint32_t AlignInBits, LLVMMetadataRef Ty,
1221                               LLVMMetadataRef *Subscripts,
1222                               unsigned NumSubscripts) {
1223   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1224                                                  NumSubscripts});
1225   return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1226                                                 unwrapDI<DIType>(Ty), Subs));
1227 }
1228 
1229 LLVMMetadataRef
1230 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1231                              size_t NameLen, uint64_t SizeInBits,
1232                              LLVMDWARFTypeEncoding Encoding,
1233                              LLVMDIFlags Flags) {
1234   return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1235                                                SizeInBits, Encoding,
1236                                                map_from_llvmDIFlags(Flags)));
1237 }
1238 
1239 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1240     LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1241     uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1242     const char *Name, size_t NameLen) {
1243   return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1244                                          SizeInBits, AlignInBits,
1245                                          AddressSpace, {Name, NameLen}));
1246 }
1247 
1248 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1249     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1250     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1251     uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1252     LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1253     unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1254     const char *UniqueId, size_t UniqueIdLen) {
1255   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1256                                                  NumElements});
1257   return wrap(unwrap(Builder)->createStructType(
1258       unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1259       LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1260       unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1261       unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1262 }
1263 
1264 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1265     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1266     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1267     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1268     LLVMMetadataRef Ty) {
1269   return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1270       {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1271       OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1272 }
1273 
1274 LLVMMetadataRef
1275 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1276                                    size_t NameLen) {
1277   return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1278 }
1279 
1280 LLVMMetadataRef
1281 LLVMDIBuilderCreateStaticMemberType(
1282     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1283     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1284     LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1285     uint32_t AlignInBits) {
1286   return wrap(unwrap(Builder)->createStaticMemberType(
1287                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1288                   unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
1289                   map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
1290                   AlignInBits));
1291 }
1292 
1293 LLVMMetadataRef
1294 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1295                             const char *Name, size_t NameLen,
1296                             LLVMMetadataRef File, unsigned LineNo,
1297                             uint64_t SizeInBits, uint32_t AlignInBits,
1298                             uint64_t OffsetInBits, LLVMDIFlags Flags,
1299                             LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1300   return wrap(unwrap(Builder)->createObjCIVar(
1301                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1302                   SizeInBits, AlignInBits, OffsetInBits,
1303                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1304                   unwrapDI<MDNode>(PropertyNode)));
1305 }
1306 
1307 LLVMMetadataRef
1308 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1309                                 const char *Name, size_t NameLen,
1310                                 LLVMMetadataRef File, unsigned LineNo,
1311                                 const char *GetterName, size_t GetterNameLen,
1312                                 const char *SetterName, size_t SetterNameLen,
1313                                 unsigned PropertyAttributes,
1314                                 LLVMMetadataRef Ty) {
1315   return wrap(unwrap(Builder)->createObjCProperty(
1316                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1317                   {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1318                   PropertyAttributes, unwrapDI<DIType>(Ty)));
1319 }
1320 
1321 LLVMMetadataRef
1322 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1323                                      LLVMMetadataRef Type) {
1324   return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1325 }
1326 
1327 LLVMMetadataRef
1328 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1329                            const char *Name, size_t NameLen,
1330                            LLVMMetadataRef File, unsigned LineNo,
1331                            LLVMMetadataRef Scope, uint32_t AlignInBits) {
1332   return wrap(unwrap(Builder)->createTypedef(
1333       unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1334       unwrapDI<DIScope>(Scope), AlignInBits));
1335 }
1336 
1337 LLVMMetadataRef
1338 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1339                                LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1340                                uint64_t BaseOffset, uint32_t VBPtrOffset,
1341                                LLVMDIFlags Flags) {
1342   return wrap(unwrap(Builder)->createInheritance(
1343                   unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1344                   BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1345 }
1346 
1347 LLVMMetadataRef
1348 LLVMDIBuilderCreateForwardDecl(
1349     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1350     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1351     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1352     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1353   return wrap(unwrap(Builder)->createForwardDecl(
1354                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1355                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1356                   AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1357 }
1358 
1359 LLVMMetadataRef
1360 LLVMDIBuilderCreateReplaceableCompositeType(
1361     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1362     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1363     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1364     LLVMDIFlags Flags, const char *UniqueIdentifier,
1365     size_t UniqueIdentifierLen) {
1366   return wrap(unwrap(Builder)->createReplaceableCompositeType(
1367                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1368                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1369                   AlignInBits, map_from_llvmDIFlags(Flags),
1370                   {UniqueIdentifier, UniqueIdentifierLen}));
1371 }
1372 
1373 LLVMMetadataRef
1374 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1375                                  LLVMMetadataRef Type) {
1376   return wrap(unwrap(Builder)->createQualifiedType(Tag,
1377                                                    unwrapDI<DIType>(Type)));
1378 }
1379 
1380 LLVMMetadataRef
1381 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1382                                  LLVMMetadataRef Type) {
1383   return wrap(unwrap(Builder)->createReferenceType(Tag,
1384                                                    unwrapDI<DIType>(Type)));
1385 }
1386 
1387 LLVMMetadataRef
1388 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1389   return wrap(unwrap(Builder)->createNullPtrType());
1390 }
1391 
1392 LLVMMetadataRef
1393 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1394                                      LLVMMetadataRef PointeeType,
1395                                      LLVMMetadataRef ClassType,
1396                                      uint64_t SizeInBits,
1397                                      uint32_t AlignInBits,
1398                                      LLVMDIFlags Flags) {
1399   return wrap(unwrap(Builder)->createMemberPointerType(
1400                   unwrapDI<DIType>(PointeeType),
1401                   unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1402                   map_from_llvmDIFlags(Flags)));
1403 }
1404 
1405 LLVMMetadataRef
1406 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1407                                       LLVMMetadataRef Scope,
1408                                       const char *Name, size_t NameLen,
1409                                       LLVMMetadataRef File, unsigned LineNumber,
1410                                       uint64_t SizeInBits,
1411                                       uint64_t OffsetInBits,
1412                                       uint64_t StorageOffsetInBits,
1413                                       LLVMDIFlags Flags, LLVMMetadataRef Type) {
1414   return wrap(unwrap(Builder)->createBitFieldMemberType(
1415                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1416                   unwrapDI<DIFile>(File), LineNumber,
1417                   SizeInBits, OffsetInBits, StorageOffsetInBits,
1418                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1419 }
1420 
1421 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1422     LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1423     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1424     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1425     LLVMMetadataRef DerivedFrom,
1426     LLVMMetadataRef *Elements, unsigned NumElements,
1427     LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1428     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1429   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1430                                                  NumElements});
1431   return wrap(unwrap(Builder)->createClassType(
1432                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1433                   unwrapDI<DIFile>(File), LineNumber,
1434                   SizeInBits, AlignInBits, OffsetInBits,
1435                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
1436                   Elts, unwrapDI<DIType>(VTableHolder),
1437                   unwrapDI<MDNode>(TemplateParamsNode),
1438                   {UniqueIdentifier, UniqueIdentifierLen}));
1439 }
1440 
1441 LLVMMetadataRef
1442 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1443                                   LLVMMetadataRef Type) {
1444   return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1445 }
1446 
1447 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1448   StringRef Str = unwrap<DIType>(DType)->getName();
1449   *Length = Str.size();
1450   return Str.data();
1451 }
1452 
1453 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1454   return unwrapDI<DIType>(DType)->getSizeInBits();
1455 }
1456 
1457 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1458   return unwrapDI<DIType>(DType)->getOffsetInBits();
1459 }
1460 
1461 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1462   return unwrapDI<DIType>(DType)->getAlignInBits();
1463 }
1464 
1465 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1466   return unwrapDI<DIType>(DType)->getLine();
1467 }
1468 
1469 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1470   return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1471 }
1472 
1473 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1474                                                   LLVMMetadataRef *Types,
1475                                                   size_t Length) {
1476   return wrap(
1477       unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1478 }
1479 
1480 LLVMMetadataRef
1481 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1482                                   LLVMMetadataRef File,
1483                                   LLVMMetadataRef *ParameterTypes,
1484                                   unsigned NumParameterTypes,
1485                                   LLVMDIFlags Flags) {
1486   auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1487                                                      NumParameterTypes});
1488   return wrap(unwrap(Builder)->createSubroutineType(
1489     Elts, map_from_llvmDIFlags(Flags)));
1490 }
1491 
1492 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1493                                               uint64_t *Addr, size_t Length) {
1494   return wrap(
1495       unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
1496 }
1497 
1498 LLVMMetadataRef
1499 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1500                                            uint64_t Value) {
1501   return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1502 }
1503 
1504 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1505     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1506     size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1507     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1508     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1509   return wrap(unwrap(Builder)->createGlobalVariableExpression(
1510       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1511       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1512       true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1513       nullptr, AlignInBits));
1514 }
1515 
1516 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1517   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1518 }
1519 
1520 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1521     LLVMMetadataRef GVE) {
1522   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1523 }
1524 
1525 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1526   return wrap(unwrapDI<DIVariable>(Var)->getFile());
1527 }
1528 
1529 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1530   return wrap(unwrapDI<DIVariable>(Var)->getScope());
1531 }
1532 
1533 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1534   return unwrapDI<DIVariable>(Var)->getLine();
1535 }
1536 
1537 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1538                                     size_t Count) {
1539   return wrap(
1540       MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1541 }
1542 
1543 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1544   MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1545 }
1546 
1547 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1548                                     LLVMMetadataRef Replacement) {
1549   auto *Node = unwrapDI<MDNode>(TargetMetadata);
1550   Node->replaceAllUsesWith(unwrap(Replacement));
1551   MDNode::deleteTemporary(Node);
1552 }
1553 
1554 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1555     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1556     size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1557     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1558     LLVMMetadataRef Decl, uint32_t AlignInBits) {
1559   return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1560       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1561       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1562       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1563 }
1564 
1565 LLVMValueRef
1566 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1567                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1568                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
1569   return wrap(unwrap(Builder)->insertDeclare(
1570                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1571                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1572                   unwrap<Instruction>(Instr)));
1573 }
1574 
1575 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1576     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1577     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1578   return wrap(unwrap(Builder)->insertDeclare(
1579                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1580                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1581                   unwrap(Block)));
1582 }
1583 
1584 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1585                                                LLVMValueRef Val,
1586                                                LLVMMetadataRef VarInfo,
1587                                                LLVMMetadataRef Expr,
1588                                                LLVMMetadataRef DebugLoc,
1589                                                LLVMValueRef Instr) {
1590   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1591                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1592                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1593                   unwrap<Instruction>(Instr)));
1594 }
1595 
1596 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1597                                               LLVMValueRef Val,
1598                                               LLVMMetadataRef VarInfo,
1599                                               LLVMMetadataRef Expr,
1600                                               LLVMMetadataRef DebugLoc,
1601                                               LLVMBasicBlockRef Block) {
1602   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1603                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1604                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1605                   unwrap(Block)));
1606 }
1607 
1608 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1609     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1610     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1611     LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1612   return wrap(unwrap(Builder)->createAutoVariable(
1613                   unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1614                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1615                   map_from_llvmDIFlags(Flags), AlignInBits));
1616 }
1617 
1618 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1619     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1620     size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1621     LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1622   return wrap(unwrap(Builder)->createParameterVariable(
1623                   unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1624                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1625                   map_from_llvmDIFlags(Flags)));
1626 }
1627 
1628 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1629                                                  int64_t Lo, int64_t Count) {
1630   return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1631 }
1632 
1633 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1634                                               LLVMMetadataRef *Data,
1635                                               size_t Length) {
1636   Metadata **DataValue = unwrap(Data);
1637   return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1638 }
1639 
1640 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1641   return wrap(unwrap<Function>(Func)->getSubprogram());
1642 }
1643 
1644 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1645   unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1646 }
1647 
1648 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1649   return unwrapDI<DISubprogram>(Subprogram)->getLine();
1650 }
1651 
1652 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1653   return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1654 }
1655 
1656 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1657   if (Loc)
1658     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1659   else
1660     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1661 }
1662 
1663 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1664   switch(unwrap(Metadata)->getMetadataID()) {
1665 #define HANDLE_METADATA_LEAF(CLASS) \
1666   case Metadata::CLASS##Kind: \
1667     return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1668 #include "llvm/IR/Metadata.def"
1669   default:
1670     return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1671   }
1672 }
1673 
1674 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
1675   assert(ID && "Expected non-null ID");
1676   LLVMContext &Ctx = ID->getContext();
1677   auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
1678 
1679   auto MapIt = Map.find(ID);
1680   if (MapIt == Map.end())
1681     return make_range(nullptr, nullptr);
1682 
1683   return make_range(MapIt->second.begin(), MapIt->second.end());
1684 }
1685 
1686 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
1687   assert(ID && "Expected non-null ID");
1688   LLVMContext &Ctx = ID->getContext();
1689 
1690   auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
1691 
1692   // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
1693   // one of those already exists first.
1694   if (!IDAsValue)
1695     return make_range(Value::user_iterator(), Value::user_iterator());
1696 
1697   return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
1698 }
1699 
1700 void at::deleteAssignmentMarkers(const Instruction *Inst) {
1701   auto Range = getAssignmentMarkers(Inst);
1702   if (Range.empty())
1703     return;
1704   SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
1705   for (auto *DAI : ToDelete)
1706     DAI->eraseFromParent();
1707 }
1708 
1709 void at::RAUW(DIAssignID *Old, DIAssignID *New) {
1710   // Replace MetadataAsValue uses.
1711   if (auto *OldIDAsValue =
1712           MetadataAsValue::getIfExists(Old->getContext(), Old)) {
1713     auto *NewIDAsValue = MetadataAsValue::get(Old->getContext(), New);
1714     OldIDAsValue->replaceAllUsesWith(NewIDAsValue);
1715   }
1716 
1717   // Replace attachments.
1718   AssignmentInstRange InstRange = getAssignmentInsts(Old);
1719   // Use intermediate storage for the instruction ptrs because the
1720   // getAssignmentInsts range iterators will be invalidated by adding and
1721   // removing DIAssignID attachments.
1722   SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
1723   for (auto *I : InstVec)
1724     I->setMetadata(LLVMContext::MD_DIAssignID, New);
1725 }
1726 
1727 void at::deleteAll(Function *F) {
1728   SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
1729   for (BasicBlock &BB : *F) {
1730     for (Instruction &I : BB) {
1731       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
1732         ToDelete.push_back(DAI);
1733       else
1734         I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
1735     }
1736   }
1737   for (auto *DAI : ToDelete)
1738     DAI->eraseFromParent();
1739 }
1740 
1741 /// Collect constant properies (base, size, offset) of \p StoreDest.
1742 /// Return std::nullopt if any properties are not constants.
1743 static std::optional<AssignmentInfo>
1744 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
1745                       uint64_t SizeInBits) {
1746   APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
1747   const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
1748       DL, GEPOffset, /*AllowNonInbounds*/ true);
1749   uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
1750   // Check for overflow.
1751   if (OffsetInBytes == UINT64_MAX)
1752     return std::nullopt;
1753   if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
1754     return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
1755   return std::nullopt;
1756 }
1757 
1758 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1759                                                     const MemIntrinsic *I) {
1760   const Value *StoreDest = I->getRawDest();
1761   // Assume 8 bit bytes.
1762   auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
1763   if (!ConstLengthInBytes)
1764     // We can't use a non-const size, bail.
1765     return std::nullopt;
1766   uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
1767   return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
1768 }
1769 
1770 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1771                                                     const StoreInst *SI) {
1772   const Value *StoreDest = SI->getPointerOperand();
1773   uint64_t SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
1774   return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
1775 }
1776 
1777 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1778                                                     const AllocaInst *AI) {
1779   uint64_t SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
1780   return getAssignmentInfoImpl(DL, AI, SizeInBits);
1781 }
1782 
1783 static CallInst *emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
1784                                Instruction &StoreLikeInst,
1785                                const VarRecord &VarRec, DIBuilder &DIB) {
1786   auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
1787   assert(ID && "Store instruction must have DIAssignID metadata");
1788   (void)ID;
1789 
1790   DIExpression *Expr =
1791       DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
1792   if (!Info.StoreToWholeAlloca) {
1793     auto R = DIExpression::createFragmentExpression(Expr, Info.OffsetInBits,
1794                                                     Info.SizeInBits);
1795     assert(R.has_value() && "failed to create fragment expression");
1796     Expr = *R;
1797   }
1798   DIExpression *AddrExpr =
1799       DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
1800   return DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
1801                              AddrExpr, VarRec.DL);
1802 }
1803 
1804 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
1805 #define DEBUG_TYPE "assignment-tracking"
1806 
1807 void at::trackAssignments(Function::iterator Start, Function::iterator End,
1808                           const StorageToVarsMap &Vars, const DataLayout &DL,
1809                           bool DebugPrints) {
1810   // Early-exit if there are no interesting variables.
1811   if (Vars.empty())
1812     return;
1813 
1814   auto &Ctx = Start->getContext();
1815   auto &Module = *Start->getModule();
1816 
1817   // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
1818   auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
1819   DIBuilder DIB(Module, /*AllowUnresolved*/ false);
1820 
1821   // Scan the instructions looking for stores to local variables' storage.
1822   LLVM_DEBUG(errs() << "# Scanning instructions\n");
1823   for (auto BBI = Start; BBI != End; ++BBI) {
1824     for (Instruction &I : *BBI) {
1825 
1826       std::optional<AssignmentInfo> Info;
1827       Value *ValueComponent = nullptr;
1828       Value *DestComponent = nullptr;
1829       if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1830         // We want to track the variable's stack home from its alloca's
1831         // position onwards so we treat it as an assignment (where the stored
1832         // value is Undef).
1833         Info = getAssignmentInfo(DL, AI);
1834         ValueComponent = Undef;
1835         DestComponent = AI;
1836       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1837         Info = getAssignmentInfo(DL, SI);
1838         ValueComponent = SI->getValueOperand();
1839         DestComponent = SI->getPointerOperand();
1840       } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
1841         Info = getAssignmentInfo(DL, MI);
1842         // May not be able to represent this value easily.
1843         ValueComponent = Undef;
1844         DestComponent = MI->getOperand(0);
1845       } else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
1846         Info = getAssignmentInfo(DL, MI);
1847         // If we're zero-initing we can state the assigned value is zero,
1848         // otherwise use undef.
1849         auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
1850         if (ConstValue && ConstValue->isZero())
1851           ValueComponent = ConstValue;
1852         else
1853           ValueComponent = Undef;
1854         DestComponent = MI->getOperand(0);
1855       } else {
1856         // Not a store-like instruction.
1857         continue;
1858       }
1859 
1860       assert(ValueComponent && DestComponent);
1861       LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
1862 
1863       // Check if getAssignmentInfo failed to understand this store.
1864       if (!Info.has_value()) {
1865         LLVM_DEBUG(
1866             errs()
1867             << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
1868         continue;
1869       }
1870       LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
1871 
1872       //  Check if the store destination is a local variable with debug info.
1873       auto LocalIt = Vars.find(Info->Base);
1874       if (LocalIt == Vars.end()) {
1875         LLVM_DEBUG(
1876             errs()
1877             << " | SKIP: Base address not associated with local variable\n");
1878         continue;
1879       }
1880 
1881       DIAssignID *ID =
1882           cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
1883       if (!ID) {
1884         ID = DIAssignID::getDistinct(Ctx);
1885         I.setMetadata(LLVMContext::MD_DIAssignID, ID);
1886       }
1887 
1888       for (const VarRecord &R : LocalIt->second) {
1889         auto *Assign =
1890             emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
1891         (void)Assign;
1892         LLVM_DEBUG(errs() << " > INSERT: " << *Assign << "\n");
1893       }
1894     }
1895   }
1896 }
1897 
1898 void AssignmentTrackingPass::runOnFunction(Function &F) {
1899   // Collect a map of {backing storage : dbg.declares} (currently "backing
1900   // storage" is limited to Allocas). We'll use this to find dbg.declares to
1901   // delete after running `trackAssignments`.
1902   DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
1903   // Create another similar map of {storage : variables} that we'll pass to
1904   // trackAssignments.
1905   StorageToVarsMap Vars;
1906   for (auto &BB : F) {
1907     for (auto &I : BB) {
1908       DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I);
1909       if (!DDI)
1910         continue;
1911       // FIXME: trackAssignments doesn't let you specify any modifiers to the
1912       // variable (e.g. fragment) or location (e.g. offset), so we have to
1913       // leave dbg.declares with non-empty expressions in place.
1914       if (DDI->getExpression()->getNumElements() != 0)
1915         continue;
1916       if (AllocaInst *Alloca =
1917               dyn_cast<AllocaInst>(DDI->getAddress()->stripPointerCasts())) {
1918         DbgDeclares[Alloca].insert(DDI);
1919         Vars[Alloca].insert(VarRecord(DDI));
1920       }
1921     }
1922   }
1923 
1924   auto DL = std::make_unique<DataLayout>(F.getParent());
1925   // FIXME: Locals can be backed by caller allocas (sret, byval).
1926   // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
1927   // doesn't "understand" dbg.declares). However, this doesn't appear to break
1928   // any rules given this description of dbg.declare from
1929   // llvm/docs/SourceLevelDebugging.rst:
1930   //
1931   //   It is not control-dependent, meaning that if a call to llvm.dbg.declare
1932   //   exists and has a valid location argument, that address is considered to
1933   //   be the true home of the variable across its entire lifetime.
1934   trackAssignments(F.begin(), F.end(), Vars, *DL);
1935 
1936   // Delete dbg.declares for variables now tracked with assignment tracking.
1937   for (auto &P : DbgDeclares) {
1938     const AllocaInst *Alloca = P.first;
1939     auto Markers = at::getAssignmentMarkers(Alloca);
1940     (void)Markers;
1941     for (DbgDeclareInst *DDI : P.second) {
1942       // Assert that the alloca that DDI uses is now linked to a dbg.assign
1943       // describing the same variable (i.e. check that this dbg.declare
1944       // has been replaced by a dbg.assign).
1945       assert(llvm::any_of(Markers, [DDI](DbgAssignIntrinsic *DAI) {
1946         return DebugVariable(DAI) == DebugVariable(DDI);
1947       }));
1948       // Delete DDI because the variable location is now tracked using
1949       // assignment tracking.
1950       DDI->eraseFromParent();
1951     }
1952   }
1953 }
1954 
1955 static const char *AssignmentTrackingModuleFlag =
1956     "debug-info-assignment-tracking";
1957 
1958 static void setAssignmentTrackingModuleFlag(Module &M) {
1959   M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
1960                   ConstantAsMetadata::get(
1961                       ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
1962 }
1963 
1964 static bool getAssignmentTrackingModuleFlag(const Module &M) {
1965   Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
1966   return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
1967 }
1968 
1969 bool llvm::isAssignmentTrackingEnabled(const Module &M) {
1970   return getAssignmentTrackingModuleFlag(M);
1971 }
1972 
1973 PreservedAnalyses AssignmentTrackingPass::run(Function &F,
1974                                               FunctionAnalysisManager &AM) {
1975   runOnFunction(F);
1976 
1977   // Record that this module uses assignment tracking. It doesn't matter that
1978   // some functons in the module may not use it - the debug info in those
1979   // functions will still be handled properly.
1980   setAssignmentTrackingModuleFlag(*F.getParent());
1981 
1982   // Q: Can we return a less conservative set than just CFGAnalyses? Can we
1983   // return PreservedAnalyses::all()?
1984   PreservedAnalyses PA;
1985   PA.preserveSet<CFGAnalyses>();
1986   return PA;
1987 }
1988 
1989 PreservedAnalyses AssignmentTrackingPass::run(Module &M,
1990                                               ModuleAnalysisManager &AM) {
1991   for (auto &F : M)
1992     runOnFunction(F);
1993 
1994   // Record that this module uses assignment tracking.
1995   setAssignmentTrackingModuleFlag(M);
1996 
1997   // Q: Can we return a less conservative set than just CFGAnalyses? Can we
1998   // return PreservedAnalyses::all()?
1999   PreservedAnalyses PA;
2000   PA.preserveSet<CFGAnalyses>();
2001   return PA;
2002 }
2003 
2004 #undef DEBUG_TYPE
2005