xref: /freebsd/contrib/llvm-project/llvm/lib/IR/DebugInfo.cpp (revision d56accc7c3dcc897489b6a07834763a03b9f3d68)
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 "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GVMaterializer.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Support/Casting.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <utility>
38 
39 using namespace llvm;
40 using namespace llvm::dwarf;
41 
42 /// Finds all intrinsics declaring local variables as living in the memory that
43 /// 'V' points to. This may include a mix of dbg.declare and
44 /// dbg.addr intrinsics.
45 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
46   // This function is hot. Check whether the value has any metadata to avoid a
47   // DenseMap lookup.
48   if (!V->isUsedByMetadata())
49     return {};
50   auto *L = LocalAsMetadata::getIfExists(V);
51   if (!L)
52     return {};
53   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
54   if (!MDV)
55     return {};
56 
57   TinyPtrVector<DbgVariableIntrinsic *> Declares;
58   for (User *U : MDV->users()) {
59     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
60       if (DII->isAddressOfVariable())
61         Declares.push_back(DII);
62   }
63 
64   return Declares;
65 }
66 
67 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
68   TinyPtrVector<DbgDeclareInst *> DDIs;
69   for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
70     if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
71       DDIs.push_back(DDI);
72   return DDIs;
73 }
74 
75 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
76   // This function is hot. Check whether the value has any metadata to avoid a
77   // DenseMap lookup.
78   if (!V->isUsedByMetadata())
79     return;
80   // TODO: If this value appears multiple times in a DIArgList, we should still
81   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
82   // This behaviour can be removed when we can automatically remove duplicates.
83   SmallPtrSet<DbgValueInst *, 4> EncounteredDbgValues;
84   if (auto *L = LocalAsMetadata::getIfExists(V)) {
85     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
86       for (User *U : MDV->users())
87         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
88           DbgValues.push_back(DVI);
89     }
90     for (Metadata *AL : L->getAllArgListUsers()) {
91       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
92         for (User *U : MDV->users())
93           if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
94             if (EncounteredDbgValues.insert(DVI).second)
95               DbgValues.push_back(DVI);
96       }
97     }
98   }
99 }
100 
101 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
102                         Value *V) {
103   // This function is hot. Check whether the value has any metadata to avoid a
104   // DenseMap lookup.
105   if (!V->isUsedByMetadata())
106     return;
107   // TODO: If this value appears multiple times in a DIArgList, we should still
108   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
109   // This behaviour can be removed when we can automatically remove duplicates.
110   SmallPtrSet<DbgVariableIntrinsic *, 4> EncounteredDbgValues;
111   if (auto *L = LocalAsMetadata::getIfExists(V)) {
112     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
113       for (User *U : MDV->users())
114         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
115           DbgUsers.push_back(DII);
116     }
117     for (Metadata *AL : L->getAllArgListUsers()) {
118       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
119         for (User *U : MDV->users())
120           if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
121             if (EncounteredDbgValues.insert(DII).second)
122               DbgUsers.push_back(DII);
123       }
124     }
125   }
126 }
127 
128 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
129   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
130     return LocalScope->getSubprogram();
131   return nullptr;
132 }
133 
134 //===----------------------------------------------------------------------===//
135 // DebugInfoFinder implementations.
136 //===----------------------------------------------------------------------===//
137 
138 void DebugInfoFinder::reset() {
139   CUs.clear();
140   SPs.clear();
141   GVs.clear();
142   TYs.clear();
143   Scopes.clear();
144   NodesSeen.clear();
145 }
146 
147 void DebugInfoFinder::processModule(const Module &M) {
148   for (auto *CU : M.debug_compile_units())
149     processCompileUnit(CU);
150   for (auto &F : M.functions()) {
151     if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
152       processSubprogram(SP);
153     // There could be subprograms from inlined functions referenced from
154     // instructions only. Walk the function to find them.
155     for (const BasicBlock &BB : F)
156       for (const Instruction &I : BB)
157         processInstruction(M, I);
158   }
159 }
160 
161 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
162   if (!addCompileUnit(CU))
163     return;
164   for (auto DIG : CU->getGlobalVariables()) {
165     if (!addGlobalVariable(DIG))
166       continue;
167     auto *GV = DIG->getVariable();
168     processScope(GV->getScope());
169     processType(GV->getType());
170   }
171   for (auto *ET : CU->getEnumTypes())
172     processType(ET);
173   for (auto *RT : CU->getRetainedTypes())
174     if (auto *T = dyn_cast<DIType>(RT))
175       processType(T);
176     else
177       processSubprogram(cast<DISubprogram>(RT));
178   for (auto *Import : CU->getImportedEntities()) {
179     auto *Entity = Import->getEntity();
180     if (auto *T = dyn_cast<DIType>(Entity))
181       processType(T);
182     else if (auto *SP = dyn_cast<DISubprogram>(Entity))
183       processSubprogram(SP);
184     else if (auto *NS = dyn_cast<DINamespace>(Entity))
185       processScope(NS->getScope());
186     else if (auto *M = dyn_cast<DIModule>(Entity))
187       processScope(M->getScope());
188   }
189 }
190 
191 void DebugInfoFinder::processInstruction(const Module &M,
192                                          const Instruction &I) {
193   if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
194     processVariable(M, *DVI);
195 
196   if (auto DbgLoc = I.getDebugLoc())
197     processLocation(M, DbgLoc.get());
198 }
199 
200 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
201   if (!Loc)
202     return;
203   processScope(Loc->getScope());
204   processLocation(M, Loc->getInlinedAt());
205 }
206 
207 void DebugInfoFinder::processType(DIType *DT) {
208   if (!addType(DT))
209     return;
210   processScope(DT->getScope());
211   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
212     for (DIType *Ref : ST->getTypeArray())
213       processType(Ref);
214     return;
215   }
216   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
217     processType(DCT->getBaseType());
218     for (Metadata *D : DCT->getElements()) {
219       if (auto *T = dyn_cast<DIType>(D))
220         processType(T);
221       else if (auto *SP = dyn_cast<DISubprogram>(D))
222         processSubprogram(SP);
223     }
224     return;
225   }
226   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
227     processType(DDT->getBaseType());
228   }
229 }
230 
231 void DebugInfoFinder::processScope(DIScope *Scope) {
232   if (!Scope)
233     return;
234   if (auto *Ty = dyn_cast<DIType>(Scope)) {
235     processType(Ty);
236     return;
237   }
238   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
239     addCompileUnit(CU);
240     return;
241   }
242   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
243     processSubprogram(SP);
244     return;
245   }
246   if (!addScope(Scope))
247     return;
248   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
249     processScope(LB->getScope());
250   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
251     processScope(NS->getScope());
252   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
253     processScope(M->getScope());
254   }
255 }
256 
257 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
258   if (!addSubprogram(SP))
259     return;
260   processScope(SP->getScope());
261   // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
262   // ValueMap containing identity mappings for all of the DICompileUnit's, not
263   // just DISubprogram's, referenced from anywhere within the Function being
264   // cloned prior to calling MapMetadata / RemapInstruction to avoid their
265   // duplication later as DICompileUnit's are also directly referenced by
266   // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
267   // Also, DICompileUnit's may reference DISubprogram's too and therefore need
268   // to be at least looked through.
269   processCompileUnit(SP->getUnit());
270   processType(SP->getType());
271   for (auto *Element : SP->getTemplateParams()) {
272     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
273       processType(TType->getType());
274     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
275       processType(TVal->getType());
276     }
277   }
278 }
279 
280 void DebugInfoFinder::processVariable(const Module &M,
281                                       const DbgVariableIntrinsic &DVI) {
282   auto *N = dyn_cast<MDNode>(DVI.getVariable());
283   if (!N)
284     return;
285 
286   auto *DV = dyn_cast<DILocalVariable>(N);
287   if (!DV)
288     return;
289 
290   if (!NodesSeen.insert(DV).second)
291     return;
292   processScope(DV->getScope());
293   processType(DV->getType());
294 }
295 
296 bool DebugInfoFinder::addType(DIType *DT) {
297   if (!DT)
298     return false;
299 
300   if (!NodesSeen.insert(DT).second)
301     return false;
302 
303   TYs.push_back(const_cast<DIType *>(DT));
304   return true;
305 }
306 
307 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
308   if (!CU)
309     return false;
310   if (!NodesSeen.insert(CU).second)
311     return false;
312 
313   CUs.push_back(CU);
314   return true;
315 }
316 
317 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
318   if (!NodesSeen.insert(DIG).second)
319     return false;
320 
321   GVs.push_back(DIG);
322   return true;
323 }
324 
325 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
326   if (!SP)
327     return false;
328 
329   if (!NodesSeen.insert(SP).second)
330     return false;
331 
332   SPs.push_back(SP);
333   return true;
334 }
335 
336 bool DebugInfoFinder::addScope(DIScope *Scope) {
337   if (!Scope)
338     return false;
339   // FIXME: Ocaml binding generates a scope with no content, we treat it
340   // as null for now.
341   if (Scope->getNumOperands() == 0)
342     return false;
343   if (!NodesSeen.insert(Scope).second)
344     return false;
345   Scopes.push_back(Scope);
346   return true;
347 }
348 
349 static MDNode *updateLoopMetadataDebugLocationsImpl(
350     MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
351   assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
352          "Loop ID needs at least one operand");
353   assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
354          "Loop ID should refer to itself");
355 
356   // Save space for the self-referential LoopID.
357   SmallVector<Metadata *, 4> MDs = {nullptr};
358 
359   for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
360     Metadata *MD = OrigLoopID->getOperand(i);
361     if (!MD)
362       MDs.push_back(nullptr);
363     else if (Metadata *NewMD = Updater(MD))
364       MDs.push_back(NewMD);
365   }
366 
367   MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
368   // Insert the self-referential LoopID.
369   NewLoopID->replaceOperandWith(0, NewLoopID);
370   return NewLoopID;
371 }
372 
373 void llvm::updateLoopMetadataDebugLocations(
374     Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
375   MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
376   if (!OrigLoopID)
377     return;
378   MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
379   I.setMetadata(LLVMContext::MD_loop, NewLoopID);
380 }
381 
382 /// Return true if a node is a DILocation or if a DILocation is
383 /// indirectly referenced by one of the node's children.
384 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
385                                   SmallPtrSetImpl<Metadata *> &Reachable,
386                                   Metadata *MD) {
387   MDNode *N = dyn_cast_or_null<MDNode>(MD);
388   if (!N)
389     return false;
390   if (isa<DILocation>(N) || Reachable.count(N))
391     return true;
392   if (!Visited.insert(N).second)
393     return false;
394   for (auto &OpIt : N->operands()) {
395     Metadata *Op = OpIt.get();
396     if (isDILocationReachable(Visited, Reachable, Op)) {
397       Reachable.insert(N);
398       return true;
399     }
400   }
401   return false;
402 }
403 
404 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
405   assert(!N->operands().empty() && "Missing self reference?");
406   SmallPtrSet<Metadata *, 8> Visited, DILocationReachable;
407   // If we already visited N, there is nothing to do.
408   if (!Visited.insert(N).second)
409     return N;
410 
411   // If there is no debug location, we do not have to rewrite this
412   // MDNode. This loop also initializes DILocationReachable, later
413   // needed by updateLoopMetadataDebugLocationsImpl; the use of
414   // count_if avoids an early exit.
415   if (!std::count_if(N->op_begin() + 1, N->op_end(),
416                      [&Visited, &DILocationReachable](const MDOperand &Op) {
417                        return isDILocationReachable(
418                                   Visited, DILocationReachable, Op.get());
419                      }))
420     return N;
421 
422   // If there is only the debug location without any actual loop metadata, we
423   // can remove the metadata.
424   if (std::all_of(
425           N->op_begin() + 1, N->op_end(),
426           [&Visited, &DILocationReachable](const MDOperand &Op) {
427             return isDILocationReachable(Visited, DILocationReachable,
428                                          Op.get());
429           }))
430     return nullptr;
431 
432   return updateLoopMetadataDebugLocationsImpl(
433       N, [&DILocationReachable](Metadata *MD) -> Metadata * {
434         if (isa<DILocation>(MD) || DILocationReachable.count(MD))
435           return nullptr;
436         return MD;
437       });
438 }
439 
440 bool llvm::stripDebugInfo(Function &F) {
441   bool Changed = false;
442   if (F.hasMetadata(LLVMContext::MD_dbg)) {
443     Changed = true;
444     F.setSubprogram(nullptr);
445   }
446 
447   DenseMap<MDNode *, MDNode *> LoopIDsMap;
448   for (BasicBlock &BB : F) {
449     for (Instruction &I : llvm::make_early_inc_range(BB)) {
450       if (isa<DbgInfoIntrinsic>(&I)) {
451         I.eraseFromParent();
452         Changed = true;
453         continue;
454       }
455       if (I.getDebugLoc()) {
456         Changed = true;
457         I.setDebugLoc(DebugLoc());
458       }
459       if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
460         auto *NewLoopID = LoopIDsMap.lookup(LoopID);
461         if (!NewLoopID)
462           NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
463         if (NewLoopID != LoopID)
464           I.setMetadata(LLVMContext::MD_loop, NewLoopID);
465       }
466       // Strip heapallocsite attachments, they point into the DIType system.
467       if (I.hasMetadataOtherThanDebugLoc())
468         I.setMetadata("heapallocsite", nullptr);
469     }
470   }
471   return Changed;
472 }
473 
474 bool llvm::StripDebugInfo(Module &M) {
475   bool Changed = false;
476 
477   for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
478     // We're stripping debug info, and without them, coverage information
479     // doesn't quite make sense.
480     if (NMD.getName().startswith("llvm.dbg.") ||
481         NMD.getName() == "llvm.gcov") {
482       NMD.eraseFromParent();
483       Changed = true;
484     }
485   }
486 
487   for (Function &F : M)
488     Changed |= stripDebugInfo(F);
489 
490   for (auto &GV : M.globals()) {
491     Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
492   }
493 
494   if (GVMaterializer *Materializer = M.getMaterializer())
495     Materializer->setStripDebugInfo();
496 
497   return Changed;
498 }
499 
500 namespace {
501 
502 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
503 class DebugTypeInfoRemoval {
504   DenseMap<Metadata *, Metadata *> Replacements;
505 
506 public:
507   /// The (void)() type.
508   MDNode *EmptySubroutineType;
509 
510 private:
511   /// Remember what linkage name we originally had before stripping. If we end
512   /// up making two subprograms identical who originally had different linkage
513   /// names, then we need to make one of them distinct, to avoid them getting
514   /// uniqued. Maps the new node to the old linkage name.
515   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
516 
517   // TODO: Remember the distinct subprogram we created for a given linkage name,
518   // so that we can continue to unique whenever possible. Map <newly created
519   // node, old linkage name> to the first (possibly distinct) mdsubprogram
520   // created for that combination. This is not strictly needed for correctness,
521   // but can cut down on the number of MDNodes and let us diff cleanly with the
522   // output of -gline-tables-only.
523 
524 public:
525   DebugTypeInfoRemoval(LLVMContext &C)
526       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
527                                                   MDNode::get(C, {}))) {}
528 
529   Metadata *map(Metadata *M) {
530     if (!M)
531       return nullptr;
532     auto Replacement = Replacements.find(M);
533     if (Replacement != Replacements.end())
534       return Replacement->second;
535 
536     return M;
537   }
538   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
539 
540   /// Recursively remap N and all its referenced children. Does a DF post-order
541   /// traversal, so as to remap bottoms up.
542   void traverseAndRemap(MDNode *N) { traverse(N); }
543 
544 private:
545   // Create a new DISubprogram, to replace the one given.
546   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
547     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
548     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
549     DISubprogram *Declaration = nullptr;
550     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
551     DIType *ContainingType =
552         cast_or_null<DIType>(map(MDS->getContainingType()));
553     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
554     auto Variables = nullptr;
555     auto TemplateParams = nullptr;
556 
557     // Make a distinct DISubprogram, for situations that warrent it.
558     auto distinctMDSubprogram = [&]() {
559       return DISubprogram::getDistinct(
560           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
561           FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
562           ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
563           MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
564           Variables);
565     };
566 
567     if (MDS->isDistinct())
568       return distinctMDSubprogram();
569 
570     auto *NewMDS = DISubprogram::get(
571         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
572         FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
573         MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
574         MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
575 
576     StringRef OldLinkageName = MDS->getLinkageName();
577 
578     // See if we need to make a distinct one.
579     auto OrigLinkage = NewToLinkageName.find(NewMDS);
580     if (OrigLinkage != NewToLinkageName.end()) {
581       if (OrigLinkage->second == OldLinkageName)
582         // We're good.
583         return NewMDS;
584 
585       // Otherwise, need to make a distinct one.
586       // TODO: Query the map to see if we already have one.
587       return distinctMDSubprogram();
588     }
589 
590     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
591     return NewMDS;
592   }
593 
594   /// Create a new compile unit, to replace the one given
595   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
596     // Drop skeleton CUs.
597     if (CU->getDWOId())
598       return nullptr;
599 
600     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
601     MDTuple *EnumTypes = nullptr;
602     MDTuple *RetainedTypes = nullptr;
603     MDTuple *GlobalVariables = nullptr;
604     MDTuple *ImportedEntities = nullptr;
605     return DICompileUnit::getDistinct(
606         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
607         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
608         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
609         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
610         CU->getDWOId(), CU->getSplitDebugInlining(),
611         CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
612         CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
613   }
614 
615   DILocation *getReplacementMDLocation(DILocation *MLD) {
616     auto *Scope = map(MLD->getScope());
617     auto *InlinedAt = map(MLD->getInlinedAt());
618     if (MLD->isDistinct())
619       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
620                                      MLD->getColumn(), Scope, InlinedAt);
621     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
622                            Scope, InlinedAt);
623   }
624 
625   /// Create a new generic MDNode, to replace the one given
626   MDNode *getReplacementMDNode(MDNode *N) {
627     SmallVector<Metadata *, 8> Ops;
628     Ops.reserve(N->getNumOperands());
629     for (auto &I : N->operands())
630       if (I)
631         Ops.push_back(map(I));
632     auto *Ret = MDNode::get(N->getContext(), Ops);
633     return Ret;
634   }
635 
636   /// Attempt to re-map N to a newly created node.
637   void remap(MDNode *N) {
638     if (Replacements.count(N))
639       return;
640 
641     auto doRemap = [&](MDNode *N) -> MDNode * {
642       if (!N)
643         return nullptr;
644       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
645         remap(MDSub->getUnit());
646         return getReplacementSubprogram(MDSub);
647       }
648       if (isa<DISubroutineType>(N))
649         return EmptySubroutineType;
650       if (auto *CU = dyn_cast<DICompileUnit>(N))
651         return getReplacementCU(CU);
652       if (isa<DIFile>(N))
653         return N;
654       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
655         // Remap to our referenced scope (recursively).
656         return mapNode(MDLB->getScope());
657       if (auto *MLD = dyn_cast<DILocation>(N))
658         return getReplacementMDLocation(MLD);
659 
660       // Otherwise, if we see these, just drop them now. Not strictly necessary,
661       // but this speeds things up a little.
662       if (isa<DINode>(N))
663         return nullptr;
664 
665       return getReplacementMDNode(N);
666     };
667     Replacements[N] = doRemap(N);
668   }
669 
670   /// Do the remapping traversal.
671   void traverse(MDNode *);
672 };
673 
674 } // end anonymous namespace
675 
676 void DebugTypeInfoRemoval::traverse(MDNode *N) {
677   if (!N || Replacements.count(N))
678     return;
679 
680   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
681   // parts of the graph.
682   auto prune = [](MDNode *Parent, MDNode *Child) {
683     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
684       return Child == MDS->getRetainedNodes().get();
685     return false;
686   };
687 
688   SmallVector<MDNode *, 16> ToVisit;
689   DenseSet<MDNode *> Opened;
690 
691   // Visit each node starting at N in post order, and map them.
692   ToVisit.push_back(N);
693   while (!ToVisit.empty()) {
694     auto *N = ToVisit.back();
695     if (!Opened.insert(N).second) {
696       // Close it.
697       remap(N);
698       ToVisit.pop_back();
699       continue;
700     }
701     for (auto &I : N->operands())
702       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
703         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
704             !isa<DICompileUnit>(MDN))
705           ToVisit.push_back(MDN);
706   }
707 }
708 
709 bool llvm::stripNonLineTableDebugInfo(Module &M) {
710   bool Changed = false;
711 
712   // First off, delete the debug intrinsics.
713   auto RemoveUses = [&](StringRef Name) {
714     if (auto *DbgVal = M.getFunction(Name)) {
715       while (!DbgVal->use_empty())
716         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
717       DbgVal->eraseFromParent();
718       Changed = true;
719     }
720   };
721   RemoveUses("llvm.dbg.addr");
722   RemoveUses("llvm.dbg.declare");
723   RemoveUses("llvm.dbg.label");
724   RemoveUses("llvm.dbg.value");
725 
726   // Delete non-CU debug info named metadata nodes.
727   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
728        NMI != NME;) {
729     NamedMDNode *NMD = &*NMI;
730     ++NMI;
731     // Specifically keep dbg.cu around.
732     if (NMD->getName() == "llvm.dbg.cu")
733       continue;
734   }
735 
736   // Drop all dbg attachments from global variables.
737   for (auto &GV : M.globals())
738     GV.eraseMetadata(LLVMContext::MD_dbg);
739 
740   DebugTypeInfoRemoval Mapper(M.getContext());
741   auto remap = [&](MDNode *Node) -> MDNode * {
742     if (!Node)
743       return nullptr;
744     Mapper.traverseAndRemap(Node);
745     auto *NewNode = Mapper.mapNode(Node);
746     Changed |= Node != NewNode;
747     Node = NewNode;
748     return NewNode;
749   };
750 
751   // Rewrite the DebugLocs to be equivalent to what
752   // -gline-tables-only would have created.
753   for (auto &F : M) {
754     if (auto *SP = F.getSubprogram()) {
755       Mapper.traverseAndRemap(SP);
756       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
757       Changed |= SP != NewSP;
758       F.setSubprogram(NewSP);
759     }
760     for (auto &BB : F) {
761       for (auto &I : BB) {
762         auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
763           auto *Scope = DL.getScope();
764           MDNode *InlinedAt = DL.getInlinedAt();
765           Scope = remap(Scope);
766           InlinedAt = remap(InlinedAt);
767           return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
768                                  Scope, InlinedAt);
769         };
770 
771         if (I.getDebugLoc() != DebugLoc())
772           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
773 
774         // Remap DILocations in llvm.loop attachments.
775         updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
776           if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
777             return remapDebugLoc(Loc).get();
778           return MD;
779         });
780 
781         // Strip heapallocsite attachments, they point into the DIType system.
782         if (I.hasMetadataOtherThanDebugLoc())
783           I.setMetadata("heapallocsite", nullptr);
784       }
785     }
786   }
787 
788   // Create a new llvm.dbg.cu, which is equivalent to the one
789   // -gline-tables-only would have created.
790   for (auto &NMD : M.getNamedMDList()) {
791     SmallVector<MDNode *, 8> Ops;
792     for (MDNode *Op : NMD.operands())
793       Ops.push_back(remap(Op));
794 
795     if (!Changed)
796       continue;
797 
798     NMD.clearOperands();
799     for (auto *Op : Ops)
800       if (Op)
801         NMD.addOperand(Op);
802   }
803   return Changed;
804 }
805 
806 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
807   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
808           M.getModuleFlag("Debug Info Version")))
809     return Val->getZExtValue();
810   return 0;
811 }
812 
813 void Instruction::applyMergedLocation(const DILocation *LocA,
814                                       const DILocation *LocB) {
815   setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
816 }
817 
818 void Instruction::updateLocationAfterHoist() { dropLocation(); }
819 
820 void Instruction::dropLocation() {
821   const DebugLoc &DL = getDebugLoc();
822   if (!DL)
823     return;
824 
825   // If this isn't a call, drop the location to allow a location from a
826   // preceding instruction to propagate.
827   if (!isa<CallBase>(this)) {
828     setDebugLoc(DebugLoc());
829     return;
830   }
831 
832   // Set a line 0 location for calls to preserve scope information in case
833   // inlining occurs.
834   DISubprogram *SP = getFunction()->getSubprogram();
835   if (SP)
836     // If a function scope is available, set it on the line 0 location. When
837     // hoisting a call to a predecessor block, using the function scope avoids
838     // making it look like the callee was reached earlier than it should be.
839     setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
840   else
841     // The parent function has no scope. Go ahead and drop the location. If
842     // the parent function is inlined, and the callee has a subprogram, the
843     // inliner will attach a location to the call.
844     //
845     // One alternative is to set a line 0 location with the existing scope and
846     // inlinedAt info. The location might be sensitive to when inlining occurs.
847     setDebugLoc(DebugLoc());
848 }
849 
850 //===----------------------------------------------------------------------===//
851 // LLVM C API implementations.
852 //===----------------------------------------------------------------------===//
853 
854 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
855   switch (lang) {
856 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR)                 \
857   case LLVMDWARFSourceLanguage##NAME:                                          \
858     return ID;
859 #include "llvm/BinaryFormat/Dwarf.def"
860 #undef HANDLE_DW_LANG
861   }
862   llvm_unreachable("Unhandled Tag");
863 }
864 
865 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
866   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
867 }
868 
869 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
870   return static_cast<DINode::DIFlags>(Flags);
871 }
872 
873 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
874   return static_cast<LLVMDIFlags>(Flags);
875 }
876 
877 static DISubprogram::DISPFlags
878 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
879   return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
880 }
881 
882 unsigned LLVMDebugMetadataVersion() {
883   return DEBUG_METADATA_VERSION;
884 }
885 
886 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
887   return wrap(new DIBuilder(*unwrap(M), false));
888 }
889 
890 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
891   return wrap(new DIBuilder(*unwrap(M)));
892 }
893 
894 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
895   return getDebugMetadataVersionFromModule(*unwrap(M));
896 }
897 
898 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
899   return StripDebugInfo(*unwrap(M));
900 }
901 
902 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
903   delete unwrap(Builder);
904 }
905 
906 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
907   unwrap(Builder)->finalize();
908 }
909 
910 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
911                                      LLVMMetadataRef subprogram) {
912   unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
913 }
914 
915 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
916     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
917     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
918     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
919     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
920     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
921     LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
922     const char *SDK, size_t SDKLen) {
923   auto File = unwrapDI<DIFile>(FileRef);
924 
925   return wrap(unwrap(Builder)->createCompileUnit(
926       map_from_llvmDWARFsourcelanguage(Lang), File,
927       StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
928       RuntimeVer, StringRef(SplitName, SplitNameLen),
929       static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
930       SplitDebugInlining, DebugInfoForProfiling,
931       DICompileUnit::DebugNameTableKind::Default, false,
932       StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
933 }
934 
935 LLVMMetadataRef
936 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
937                         size_t FilenameLen, const char *Directory,
938                         size_t DirectoryLen) {
939   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
940                                           StringRef(Directory, DirectoryLen)));
941 }
942 
943 LLVMMetadataRef
944 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
945                           const char *Name, size_t NameLen,
946                           const char *ConfigMacros, size_t ConfigMacrosLen,
947                           const char *IncludePath, size_t IncludePathLen,
948                           const char *APINotesFile, size_t APINotesFileLen) {
949   return wrap(unwrap(Builder)->createModule(
950       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
951       StringRef(ConfigMacros, ConfigMacrosLen),
952       StringRef(IncludePath, IncludePathLen),
953       StringRef(APINotesFile, APINotesFileLen)));
954 }
955 
956 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
957                                              LLVMMetadataRef ParentScope,
958                                              const char *Name, size_t NameLen,
959                                              LLVMBool ExportSymbols) {
960   return wrap(unwrap(Builder)->createNameSpace(
961       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
962 }
963 
964 LLVMMetadataRef LLVMDIBuilderCreateFunction(
965     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
966     size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
967     LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
968     LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
969     unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
970   return wrap(unwrap(Builder)->createFunction(
971       unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
972       unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
973       map_from_llvmDIFlags(Flags),
974       pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
975       nullptr, nullptr));
976 }
977 
978 
979 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
980     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
981     LLVMMetadataRef File, unsigned Line, unsigned Col) {
982   return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
983                                                   unwrapDI<DIFile>(File),
984                                                   Line, Col));
985 }
986 
987 LLVMMetadataRef
988 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
989                                     LLVMMetadataRef Scope,
990                                     LLVMMetadataRef File,
991                                     unsigned Discriminator) {
992   return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
993                                                       unwrapDI<DIFile>(File),
994                                                       Discriminator));
995 }
996 
997 LLVMMetadataRef
998 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
999                                                LLVMMetadataRef Scope,
1000                                                LLVMMetadataRef NS,
1001                                                LLVMMetadataRef File,
1002                                                unsigned Line) {
1003   return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1004                                                     unwrapDI<DINamespace>(NS),
1005                                                     unwrapDI<DIFile>(File),
1006                                                     Line));
1007 }
1008 
1009 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1010     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1011     LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1012     LLVMMetadataRef *Elements, unsigned NumElements) {
1013   auto Elts =
1014       (NumElements > 0)
1015           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1016           : nullptr;
1017   return wrap(unwrap(Builder)->createImportedModule(
1018       unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1019       unwrapDI<DIFile>(File), Line, Elts));
1020 }
1021 
1022 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1023     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1024     LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1025     unsigned NumElements) {
1026   auto Elts =
1027       (NumElements > 0)
1028           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1029           : nullptr;
1030   return wrap(unwrap(Builder)->createImportedModule(
1031       unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1032       Line, Elts));
1033 }
1034 
1035 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1036     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1037     LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1038     LLVMMetadataRef *Elements, unsigned NumElements) {
1039   auto Elts =
1040       (NumElements > 0)
1041           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1042           : nullptr;
1043   return wrap(unwrap(Builder)->createImportedDeclaration(
1044       unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1045       Line, {Name, NameLen}, Elts));
1046 }
1047 
1048 LLVMMetadataRef
1049 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1050                                  unsigned Column, LLVMMetadataRef Scope,
1051                                  LLVMMetadataRef InlinedAt) {
1052   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1053                               unwrap(InlinedAt)));
1054 }
1055 
1056 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1057   return unwrapDI<DILocation>(Location)->getLine();
1058 }
1059 
1060 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1061   return unwrapDI<DILocation>(Location)->getColumn();
1062 }
1063 
1064 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1065   return wrap(unwrapDI<DILocation>(Location)->getScope());
1066 }
1067 
1068 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1069   return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1070 }
1071 
1072 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1073   return wrap(unwrapDI<DIScope>(Scope)->getFile());
1074 }
1075 
1076 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1077   auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1078   *Len = Dir.size();
1079   return Dir.data();
1080 }
1081 
1082 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1083   auto Name = unwrapDI<DIFile>(File)->getFilename();
1084   *Len = Name.size();
1085   return Name.data();
1086 }
1087 
1088 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1089   if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1090     *Len = Src->size();
1091     return Src->data();
1092   }
1093   *Len = 0;
1094   return "";
1095 }
1096 
1097 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1098                                          LLVMMetadataRef ParentMacroFile,
1099                                          unsigned Line,
1100                                          LLVMDWARFMacinfoRecordType RecordType,
1101                                          const char *Name, size_t NameLen,
1102                                          const char *Value, size_t ValueLen) {
1103   return wrap(
1104       unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1105                                    static_cast<MacinfoRecordType>(RecordType),
1106                                    {Name, NameLen}, {Value, ValueLen}));
1107 }
1108 
1109 LLVMMetadataRef
1110 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1111                                  LLVMMetadataRef ParentMacroFile, unsigned Line,
1112                                  LLVMMetadataRef File) {
1113   return wrap(unwrap(Builder)->createTempMacroFile(
1114       unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1115 }
1116 
1117 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1118                                               const char *Name, size_t NameLen,
1119                                               int64_t Value,
1120                                               LLVMBool IsUnsigned) {
1121   return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1122                                                 IsUnsigned != 0));
1123 }
1124 
1125 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1126   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1127   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1128   uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1129   unsigned NumElements, LLVMMetadataRef ClassTy) {
1130 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1131                                                NumElements});
1132 return wrap(unwrap(Builder)->createEnumerationType(
1133     unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1134     LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1135 }
1136 
1137 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1138   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1139   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1140   uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1141   LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1142   const char *UniqueId, size_t UniqueIdLen) {
1143   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1144                                                  NumElements});
1145   return wrap(unwrap(Builder)->createUnionType(
1146      unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1147      LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1148      Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1149 }
1150 
1151 
1152 LLVMMetadataRef
1153 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1154                              uint32_t AlignInBits, LLVMMetadataRef Ty,
1155                              LLVMMetadataRef *Subscripts,
1156                              unsigned NumSubscripts) {
1157   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1158                                                  NumSubscripts});
1159   return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1160                                                unwrapDI<DIType>(Ty), Subs));
1161 }
1162 
1163 LLVMMetadataRef
1164 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1165                               uint32_t AlignInBits, LLVMMetadataRef Ty,
1166                               LLVMMetadataRef *Subscripts,
1167                               unsigned NumSubscripts) {
1168   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1169                                                  NumSubscripts});
1170   return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1171                                                 unwrapDI<DIType>(Ty), Subs));
1172 }
1173 
1174 LLVMMetadataRef
1175 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1176                              size_t NameLen, uint64_t SizeInBits,
1177                              LLVMDWARFTypeEncoding Encoding,
1178                              LLVMDIFlags Flags) {
1179   return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1180                                                SizeInBits, Encoding,
1181                                                map_from_llvmDIFlags(Flags)));
1182 }
1183 
1184 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1185     LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1186     uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1187     const char *Name, size_t NameLen) {
1188   return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1189                                          SizeInBits, AlignInBits,
1190                                          AddressSpace, {Name, NameLen}));
1191 }
1192 
1193 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1194     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1195     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1196     uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1197     LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1198     unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1199     const char *UniqueId, size_t UniqueIdLen) {
1200   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1201                                                  NumElements});
1202   return wrap(unwrap(Builder)->createStructType(
1203       unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1204       LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1205       unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1206       unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1207 }
1208 
1209 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1210     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1211     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1212     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1213     LLVMMetadataRef Ty) {
1214   return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1215       {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1216       OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1217 }
1218 
1219 LLVMMetadataRef
1220 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1221                                    size_t NameLen) {
1222   return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1223 }
1224 
1225 LLVMMetadataRef
1226 LLVMDIBuilderCreateStaticMemberType(
1227     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1228     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1229     LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1230     uint32_t AlignInBits) {
1231   return wrap(unwrap(Builder)->createStaticMemberType(
1232                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1233                   unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
1234                   map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
1235                   AlignInBits));
1236 }
1237 
1238 LLVMMetadataRef
1239 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1240                             const char *Name, size_t NameLen,
1241                             LLVMMetadataRef File, unsigned LineNo,
1242                             uint64_t SizeInBits, uint32_t AlignInBits,
1243                             uint64_t OffsetInBits, LLVMDIFlags Flags,
1244                             LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1245   return wrap(unwrap(Builder)->createObjCIVar(
1246                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1247                   SizeInBits, AlignInBits, OffsetInBits,
1248                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1249                   unwrapDI<MDNode>(PropertyNode)));
1250 }
1251 
1252 LLVMMetadataRef
1253 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1254                                 const char *Name, size_t NameLen,
1255                                 LLVMMetadataRef File, unsigned LineNo,
1256                                 const char *GetterName, size_t GetterNameLen,
1257                                 const char *SetterName, size_t SetterNameLen,
1258                                 unsigned PropertyAttributes,
1259                                 LLVMMetadataRef Ty) {
1260   return wrap(unwrap(Builder)->createObjCProperty(
1261                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1262                   {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1263                   PropertyAttributes, unwrapDI<DIType>(Ty)));
1264 }
1265 
1266 LLVMMetadataRef
1267 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1268                                      LLVMMetadataRef Type) {
1269   return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1270 }
1271 
1272 LLVMMetadataRef
1273 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1274                            const char *Name, size_t NameLen,
1275                            LLVMMetadataRef File, unsigned LineNo,
1276                            LLVMMetadataRef Scope, uint32_t AlignInBits) {
1277   return wrap(unwrap(Builder)->createTypedef(
1278       unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1279       unwrapDI<DIScope>(Scope), AlignInBits));
1280 }
1281 
1282 LLVMMetadataRef
1283 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1284                                LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1285                                uint64_t BaseOffset, uint32_t VBPtrOffset,
1286                                LLVMDIFlags Flags) {
1287   return wrap(unwrap(Builder)->createInheritance(
1288                   unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1289                   BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1290 }
1291 
1292 LLVMMetadataRef
1293 LLVMDIBuilderCreateForwardDecl(
1294     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1295     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1296     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1297     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1298   return wrap(unwrap(Builder)->createForwardDecl(
1299                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1300                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1301                   AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1302 }
1303 
1304 LLVMMetadataRef
1305 LLVMDIBuilderCreateReplaceableCompositeType(
1306     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1307     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1308     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1309     LLVMDIFlags Flags, const char *UniqueIdentifier,
1310     size_t UniqueIdentifierLen) {
1311   return wrap(unwrap(Builder)->createReplaceableCompositeType(
1312                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1313                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1314                   AlignInBits, map_from_llvmDIFlags(Flags),
1315                   {UniqueIdentifier, UniqueIdentifierLen}));
1316 }
1317 
1318 LLVMMetadataRef
1319 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1320                                  LLVMMetadataRef Type) {
1321   return wrap(unwrap(Builder)->createQualifiedType(Tag,
1322                                                    unwrapDI<DIType>(Type)));
1323 }
1324 
1325 LLVMMetadataRef
1326 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1327                                  LLVMMetadataRef Type) {
1328   return wrap(unwrap(Builder)->createReferenceType(Tag,
1329                                                    unwrapDI<DIType>(Type)));
1330 }
1331 
1332 LLVMMetadataRef
1333 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1334   return wrap(unwrap(Builder)->createNullPtrType());
1335 }
1336 
1337 LLVMMetadataRef
1338 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1339                                      LLVMMetadataRef PointeeType,
1340                                      LLVMMetadataRef ClassType,
1341                                      uint64_t SizeInBits,
1342                                      uint32_t AlignInBits,
1343                                      LLVMDIFlags Flags) {
1344   return wrap(unwrap(Builder)->createMemberPointerType(
1345                   unwrapDI<DIType>(PointeeType),
1346                   unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1347                   map_from_llvmDIFlags(Flags)));
1348 }
1349 
1350 LLVMMetadataRef
1351 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1352                                       LLVMMetadataRef Scope,
1353                                       const char *Name, size_t NameLen,
1354                                       LLVMMetadataRef File, unsigned LineNumber,
1355                                       uint64_t SizeInBits,
1356                                       uint64_t OffsetInBits,
1357                                       uint64_t StorageOffsetInBits,
1358                                       LLVMDIFlags Flags, LLVMMetadataRef Type) {
1359   return wrap(unwrap(Builder)->createBitFieldMemberType(
1360                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1361                   unwrapDI<DIFile>(File), LineNumber,
1362                   SizeInBits, OffsetInBits, StorageOffsetInBits,
1363                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1364 }
1365 
1366 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1367     LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1368     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1369     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1370     LLVMMetadataRef DerivedFrom,
1371     LLVMMetadataRef *Elements, unsigned NumElements,
1372     LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1373     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1374   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1375                                                  NumElements});
1376   return wrap(unwrap(Builder)->createClassType(
1377                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1378                   unwrapDI<DIFile>(File), LineNumber,
1379                   SizeInBits, AlignInBits, OffsetInBits,
1380                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
1381                   Elts, unwrapDI<DIType>(VTableHolder),
1382                   unwrapDI<MDNode>(TemplateParamsNode),
1383                   {UniqueIdentifier, UniqueIdentifierLen}));
1384 }
1385 
1386 LLVMMetadataRef
1387 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1388                                   LLVMMetadataRef Type) {
1389   return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1390 }
1391 
1392 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1393   StringRef Str = unwrap<DIType>(DType)->getName();
1394   *Length = Str.size();
1395   return Str.data();
1396 }
1397 
1398 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1399   return unwrapDI<DIType>(DType)->getSizeInBits();
1400 }
1401 
1402 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1403   return unwrapDI<DIType>(DType)->getOffsetInBits();
1404 }
1405 
1406 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1407   return unwrapDI<DIType>(DType)->getAlignInBits();
1408 }
1409 
1410 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1411   return unwrapDI<DIType>(DType)->getLine();
1412 }
1413 
1414 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1415   return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1416 }
1417 
1418 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1419                                                   LLVMMetadataRef *Types,
1420                                                   size_t Length) {
1421   return wrap(
1422       unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1423 }
1424 
1425 LLVMMetadataRef
1426 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1427                                   LLVMMetadataRef File,
1428                                   LLVMMetadataRef *ParameterTypes,
1429                                   unsigned NumParameterTypes,
1430                                   LLVMDIFlags Flags) {
1431   auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1432                                                      NumParameterTypes});
1433   return wrap(unwrap(Builder)->createSubroutineType(
1434     Elts, map_from_llvmDIFlags(Flags)));
1435 }
1436 
1437 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1438                                               uint64_t *Addr, size_t Length) {
1439   return wrap(
1440       unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
1441 }
1442 
1443 LLVMMetadataRef
1444 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1445                                            uint64_t Value) {
1446   return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1447 }
1448 
1449 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1450     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1451     size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1452     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1453     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1454   return wrap(unwrap(Builder)->createGlobalVariableExpression(
1455       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1456       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1457       true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1458       nullptr, AlignInBits));
1459 }
1460 
1461 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1462   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1463 }
1464 
1465 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1466     LLVMMetadataRef GVE) {
1467   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1468 }
1469 
1470 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1471   return wrap(unwrapDI<DIVariable>(Var)->getFile());
1472 }
1473 
1474 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1475   return wrap(unwrapDI<DIVariable>(Var)->getScope());
1476 }
1477 
1478 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1479   return unwrapDI<DIVariable>(Var)->getLine();
1480 }
1481 
1482 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1483                                     size_t Count) {
1484   return wrap(
1485       MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1486 }
1487 
1488 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1489   MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1490 }
1491 
1492 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1493                                     LLVMMetadataRef Replacement) {
1494   auto *Node = unwrapDI<MDNode>(TargetMetadata);
1495   Node->replaceAllUsesWith(unwrap<Metadata>(Replacement));
1496   MDNode::deleteTemporary(Node);
1497 }
1498 
1499 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1500     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1501     size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1502     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1503     LLVMMetadataRef Decl, uint32_t AlignInBits) {
1504   return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1505       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1506       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1507       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1508 }
1509 
1510 LLVMValueRef
1511 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1512                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1513                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
1514   return wrap(unwrap(Builder)->insertDeclare(
1515                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1516                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1517                   unwrap<Instruction>(Instr)));
1518 }
1519 
1520 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1521     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1522     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1523   return wrap(unwrap(Builder)->insertDeclare(
1524                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1525                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1526                   unwrap(Block)));
1527 }
1528 
1529 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1530                                                LLVMValueRef Val,
1531                                                LLVMMetadataRef VarInfo,
1532                                                LLVMMetadataRef Expr,
1533                                                LLVMMetadataRef DebugLoc,
1534                                                LLVMValueRef Instr) {
1535   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1536                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1537                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1538                   unwrap<Instruction>(Instr)));
1539 }
1540 
1541 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1542                                               LLVMValueRef Val,
1543                                               LLVMMetadataRef VarInfo,
1544                                               LLVMMetadataRef Expr,
1545                                               LLVMMetadataRef DebugLoc,
1546                                               LLVMBasicBlockRef Block) {
1547   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1548                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1549                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1550                   unwrap(Block)));
1551 }
1552 
1553 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1554     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1555     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1556     LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1557   return wrap(unwrap(Builder)->createAutoVariable(
1558                   unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1559                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1560                   map_from_llvmDIFlags(Flags), AlignInBits));
1561 }
1562 
1563 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1564     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1565     size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1566     LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1567   return wrap(unwrap(Builder)->createParameterVariable(
1568                   unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1569                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1570                   map_from_llvmDIFlags(Flags)));
1571 }
1572 
1573 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1574                                                  int64_t Lo, int64_t Count) {
1575   return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1576 }
1577 
1578 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1579                                               LLVMMetadataRef *Data,
1580                                               size_t Length) {
1581   Metadata **DataValue = unwrap(Data);
1582   return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1583 }
1584 
1585 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1586   return wrap(unwrap<Function>(Func)->getSubprogram());
1587 }
1588 
1589 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1590   unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1591 }
1592 
1593 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1594   return unwrapDI<DISubprogram>(Subprogram)->getLine();
1595 }
1596 
1597 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1598   return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1599 }
1600 
1601 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1602   if (Loc)
1603     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1604   else
1605     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1606 }
1607 
1608 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1609   switch(unwrap(Metadata)->getMetadataID()) {
1610 #define HANDLE_METADATA_LEAF(CLASS) \
1611   case Metadata::CLASS##Kind: \
1612     return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1613 #include "llvm/IR/Metadata.def"
1614   default:
1615     return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1616   }
1617 }
1618