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