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