xref: /freebsd/contrib/llvm-project/llvm/lib/IR/DIBuilder.cpp (revision d9a42747950146bf03cda7f6e25d219253f8a57a)
1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
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 DIBuilder.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/DIBuilder.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfo.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 
23 using namespace llvm;
24 using namespace llvm::dwarf;
25 
26 static cl::opt<bool>
27     UseDbgAddr("use-dbg-addr",
28                llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
29                cl::init(false), cl::Hidden);
30 
31 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
32     : M(m), VMContext(M.getContext()), CUNode(CU), DeclareFn(nullptr),
33       ValueFn(nullptr), LabelFn(nullptr), AddrFn(nullptr),
34       AllowUnresolvedNodes(AllowUnresolvedNodes) {
35   if (CUNode) {
36     if (const auto &ETs = CUNode->getEnumTypes())
37       AllEnumTypes.assign(ETs.begin(), ETs.end());
38     if (const auto &RTs = CUNode->getRetainedTypes())
39       AllRetainTypes.assign(RTs.begin(), RTs.end());
40     if (const auto &GVs = CUNode->getGlobalVariables())
41       AllGVs.assign(GVs.begin(), GVs.end());
42     if (const auto &IMs = CUNode->getImportedEntities())
43       AllImportedModules.assign(IMs.begin(), IMs.end());
44     if (const auto &MNs = CUNode->getMacros())
45       AllMacrosPerParent.insert({nullptr, {MNs.begin(), MNs.end()}});
46   }
47 }
48 
49 void DIBuilder::trackIfUnresolved(MDNode *N) {
50   if (!N)
51     return;
52   if (N->isResolved())
53     return;
54 
55   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
56   UnresolvedNodes.emplace_back(N);
57 }
58 
59 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
60   MDTuple *Temp = SP->getRetainedNodes().get();
61   if (!Temp || !Temp->isTemporary())
62     return;
63 
64   SmallVector<Metadata *, 16> RetainedNodes;
65 
66   auto PV = PreservedVariables.find(SP);
67   if (PV != PreservedVariables.end())
68     RetainedNodes.append(PV->second.begin(), PV->second.end());
69 
70   auto PL = PreservedLabels.find(SP);
71   if (PL != PreservedLabels.end())
72     RetainedNodes.append(PL->second.begin(), PL->second.end());
73 
74   DINodeArray Node = getOrCreateArray(RetainedNodes);
75 
76   TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
77 }
78 
79 void DIBuilder::finalize() {
80   if (!CUNode) {
81     assert(!AllowUnresolvedNodes &&
82            "creating type nodes without a CU is not supported");
83     return;
84   }
85 
86   if (!AllEnumTypes.empty())
87     CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
88 
89   SmallVector<Metadata *, 16> RetainValues;
90   // Declarations and definitions of the same type may be retained. Some
91   // clients RAUW these pairs, leaving duplicates in the retained types
92   // list. Use a set to remove the duplicates while we transform the
93   // TrackingVHs back into Values.
94   SmallPtrSet<Metadata *, 16> RetainSet;
95   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
96     if (RetainSet.insert(AllRetainTypes[I]).second)
97       RetainValues.push_back(AllRetainTypes[I]);
98 
99   if (!RetainValues.empty())
100     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
101 
102   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
103   for (auto *SP : SPs)
104     finalizeSubprogram(SP);
105   for (auto *N : RetainValues)
106     if (auto *SP = dyn_cast<DISubprogram>(N))
107       finalizeSubprogram(SP);
108 
109   if (!AllGVs.empty())
110     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
111 
112   if (!AllImportedModules.empty())
113     CUNode->replaceImportedEntities(MDTuple::get(
114         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
115                                                AllImportedModules.end())));
116 
117   for (const auto &I : AllMacrosPerParent) {
118     // DIMacroNode's with nullptr parent are DICompileUnit direct children.
119     if (!I.first) {
120       CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
121       continue;
122     }
123     // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
124     auto *TMF = cast<DIMacroFile>(I.first);
125     auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
126                                 TMF->getLine(), TMF->getFile(),
127                                 getOrCreateMacroArray(I.second.getArrayRef()));
128     replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
129   }
130 
131   // Now that all temp nodes have been replaced or deleted, resolve remaining
132   // cycles.
133   for (const auto &N : UnresolvedNodes)
134     if (N && !N->isResolved())
135       N->resolveCycles();
136   UnresolvedNodes.clear();
137 
138   // Can't handle unresolved nodes anymore.
139   AllowUnresolvedNodes = false;
140 }
141 
142 /// If N is compile unit return NULL otherwise return N.
143 static DIScope *getNonCompileUnitScope(DIScope *N) {
144   if (!N || isa<DICompileUnit>(N))
145     return nullptr;
146   return cast<DIScope>(N);
147 }
148 
149 DICompileUnit *DIBuilder::createCompileUnit(
150     unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
151     StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
152     DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
153     bool SplitDebugInlining, bool DebugInfoForProfiling,
154     DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
155     StringRef SysRoot, StringRef SDK) {
156 
157   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
158           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
159          "Invalid Language tag");
160 
161   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
162   CUNode = DICompileUnit::getDistinct(
163       VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
164       SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
165       SplitDebugInlining, DebugInfoForProfiling, NameTableKind,
166       RangesBaseAddress, SysRoot, SDK);
167 
168   // Create a named metadata so that it is easier to find cu in a module.
169   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
170   NMD->addOperand(CUNode);
171   trackIfUnresolved(CUNode);
172   return CUNode;
173 }
174 
175 static DIImportedEntity *
176 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
177                      Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
178                      DINodeArray Elements,
179                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
180   if (Line)
181     assert(File && "Source location has line number but no file");
182   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
183   auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS),
184                                   File, Line, Name, Elements);
185   if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
186     // A new Imported Entity was just added to the context.
187     // Add it to the Imported Modules list.
188     AllImportedModules.emplace_back(M);
189   return M;
190 }
191 
192 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
193                                                   DINamespace *NS, DIFile *File,
194                                                   unsigned Line,
195                                                   DINodeArray Elements) {
196   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
197                                 Context, NS, File, Line, StringRef(), Elements,
198                                 AllImportedModules);
199 }
200 
201 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
202                                                   DIImportedEntity *NS,
203                                                   DIFile *File, unsigned Line,
204                                                   DINodeArray Elements) {
205   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
206                                 Context, NS, File, Line, StringRef(), Elements,
207                                 AllImportedModules);
208 }
209 
210 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
211                                                   DIFile *File, unsigned Line,
212                                                   DINodeArray Elements) {
213   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
214                                 Context, M, File, Line, StringRef(), Elements,
215                                 AllImportedModules);
216 }
217 
218 DIImportedEntity *
219 DIBuilder::createImportedDeclaration(DIScope *Context, DINode *Decl,
220                                      DIFile *File, unsigned Line,
221                                      StringRef Name, DINodeArray Elements) {
222   // Make sure to use the unique identifier based metadata reference for
223   // types that have one.
224   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
225                                 Context, Decl, File, Line, Name, Elements,
226                                 AllImportedModules);
227 }
228 
229 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
230                               Optional<DIFile::ChecksumInfo<StringRef>> CS,
231                               Optional<StringRef> Source) {
232   return DIFile::get(VMContext, Filename, Directory, CS, Source);
233 }
234 
235 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
236                                 unsigned MacroType, StringRef Name,
237                                 StringRef Value) {
238   assert(!Name.empty() && "Unable to create macro without name");
239   assert((MacroType == dwarf::DW_MACINFO_undef ||
240           MacroType == dwarf::DW_MACINFO_define) &&
241          "Unexpected macro type");
242   auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
243   AllMacrosPerParent[Parent].insert(M);
244   return M;
245 }
246 
247 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
248                                             unsigned LineNumber, DIFile *File) {
249   auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
250                                        LineNumber, File, DIMacroNodeArray())
251                  .release();
252   AllMacrosPerParent[Parent].insert(MF);
253   // Add the new temporary DIMacroFile to the macro per parent map as a parent.
254   // This is needed to assure DIMacroFile with no children to have an entry in
255   // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
256   AllMacrosPerParent.insert({MF, {}});
257   return MF;
258 }
259 
260 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, uint64_t Val,
261                                           bool IsUnsigned) {
262   assert(!Name.empty() && "Unable to create enumerator without name");
263   return DIEnumerator::get(VMContext, APInt(64, Val, !IsUnsigned), IsUnsigned,
264                            Name);
265 }
266 
267 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, const APSInt &Value) {
268   assert(!Name.empty() && "Unable to create enumerator without name");
269   return DIEnumerator::get(VMContext, APInt(Value), Value.isUnsigned(), Name);
270 }
271 
272 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
273   assert(!Name.empty() && "Unable to create type without name");
274   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
275 }
276 
277 DIBasicType *DIBuilder::createNullPtrType() {
278   return createUnspecifiedType("decltype(nullptr)");
279 }
280 
281 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
282                                         unsigned Encoding,
283                                         DINode::DIFlags Flags) {
284   assert(!Name.empty() && "Unable to create type without name");
285   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
286                           0, Encoding, Flags);
287 }
288 
289 DIStringType *DIBuilder::createStringType(StringRef Name, uint64_t SizeInBits) {
290   assert(!Name.empty() && "Unable to create type without name");
291   return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name,
292                            SizeInBits, 0);
293 }
294 
295 DIStringType *DIBuilder::createStringType(StringRef Name,
296                                           DIVariable *StringLength,
297                                           DIExpression *StrLocationExp) {
298   assert(!Name.empty() && "Unable to create type without name");
299   return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name,
300                            StringLength, nullptr, StrLocationExp, 0, 0, 0);
301 }
302 
303 DIStringType *DIBuilder::createStringType(StringRef Name,
304                                           DIExpression *StringLengthExp,
305                                           DIExpression *StrLocationExp) {
306   assert(!Name.empty() && "Unable to create type without name");
307   return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name, nullptr,
308                            StringLengthExp, StrLocationExp, 0, 0, 0);
309 }
310 
311 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
312   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
313                             0, 0, None, DINode::FlagZero);
314 }
315 
316 DIDerivedType *
317 DIBuilder::createPointerType(DIType *PointeeTy, uint64_t SizeInBits,
318                              uint32_t AlignInBits,
319                              Optional<unsigned> DWARFAddressSpace,
320                              StringRef Name, DINodeArray Annotations) {
321   // FIXME: Why is there a name here?
322   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
323                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
324                             AlignInBits, 0, DWARFAddressSpace, DINode::FlagZero,
325                             nullptr, Annotations);
326 }
327 
328 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
329                                                   DIType *Base,
330                                                   uint64_t SizeInBits,
331                                                   uint32_t AlignInBits,
332                                                   DINode::DIFlags Flags) {
333   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
334                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
335                             AlignInBits, 0, None, Flags, Base);
336 }
337 
338 DIDerivedType *
339 DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, uint64_t SizeInBits,
340                                uint32_t AlignInBits,
341                                Optional<unsigned> DWARFAddressSpace) {
342   assert(RTy && "Unable to create reference type");
343   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
344                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
345                             DINode::FlagZero);
346 }
347 
348 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
349                                         DIFile *File, unsigned LineNo,
350                                         DIScope *Context, uint32_t AlignInBits,
351                                         DINodeArray Annotations) {
352   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
353                             LineNo, getNonCompileUnitScope(Context), Ty, 0,
354                             AlignInBits, 0, None, DINode::FlagZero, nullptr,
355                             Annotations);
356 }
357 
358 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
359   assert(Ty && "Invalid type!");
360   assert(FriendTy && "Invalid friend type!");
361   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
362                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
363 }
364 
365 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
366                                             uint64_t BaseOffset,
367                                             uint32_t VBPtrOffset,
368                                             DINode::DIFlags Flags) {
369   assert(Ty && "Unable to create inheritance");
370   Metadata *ExtraData = ConstantAsMetadata::get(
371       ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
372   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
373                             0, Ty, BaseTy, 0, 0, BaseOffset, None, Flags,
374                             ExtraData);
375 }
376 
377 DIDerivedType *DIBuilder::createMemberType(
378     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
379     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
380     DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) {
381   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
382                             LineNumber, getNonCompileUnitScope(Scope), Ty,
383                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
384                             nullptr, Annotations);
385 }
386 
387 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
388   if (C)
389     return ConstantAsMetadata::get(C);
390   return nullptr;
391 }
392 
393 DIDerivedType *DIBuilder::createVariantMemberType(
394     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
395     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
396     Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
397   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
398                             LineNumber, getNonCompileUnitScope(Scope), Ty,
399                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
400                             getConstantOrNull(Discriminant));
401 }
402 
403 DIDerivedType *DIBuilder::createBitFieldMemberType(
404     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
405     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
406     DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) {
407   Flags |= DINode::FlagBitField;
408   return DIDerivedType::get(
409       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
410       getNonCompileUnitScope(Scope), Ty, SizeInBits, /*AlignInBits=*/0,
411       OffsetInBits, None, Flags,
412       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
413                                                StorageOffsetInBits)),
414       Annotations);
415 }
416 
417 DIDerivedType *
418 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
419                                   unsigned LineNumber, DIType *Ty,
420                                   DINode::DIFlags Flags, llvm::Constant *Val,
421                                   uint32_t AlignInBits) {
422   Flags |= DINode::FlagStaticMember;
423   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
424                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
425                             AlignInBits, 0, None, Flags,
426                             getConstantOrNull(Val));
427 }
428 
429 DIDerivedType *
430 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
431                           uint64_t SizeInBits, uint32_t AlignInBits,
432                           uint64_t OffsetInBits, DINode::DIFlags Flags,
433                           DIType *Ty, MDNode *PropertyNode) {
434   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
435                             LineNumber, getNonCompileUnitScope(File), Ty,
436                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
437                             PropertyNode);
438 }
439 
440 DIObjCProperty *
441 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
442                               StringRef GetterName, StringRef SetterName,
443                               unsigned PropertyAttributes, DIType *Ty) {
444   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
445                              SetterName, PropertyAttributes, Ty);
446 }
447 
448 DITemplateTypeParameter *
449 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
450                                        DIType *Ty, bool isDefault) {
451   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
452   return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault);
453 }
454 
455 static DITemplateValueParameter *
456 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
457                                    DIScope *Context, StringRef Name, DIType *Ty,
458                                    bool IsDefault, Metadata *MD) {
459   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
460   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD);
461 }
462 
463 DITemplateValueParameter *
464 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
465                                         DIType *Ty, bool isDefault,
466                                         Constant *Val) {
467   return createTemplateValueParameterHelper(
468       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
469       isDefault, getConstantOrNull(Val));
470 }
471 
472 DITemplateValueParameter *
473 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
474                                            DIType *Ty, StringRef Val) {
475   return createTemplateValueParameterHelper(
476       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
477       false, MDString::get(VMContext, Val));
478 }
479 
480 DITemplateValueParameter *
481 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
482                                        DIType *Ty, DINodeArray Val) {
483   return createTemplateValueParameterHelper(
484       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
485       false, Val.get());
486 }
487 
488 DICompositeType *DIBuilder::createClassType(
489     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
490     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
491     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
492     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
493   assert((!Context || isa<DIScope>(Context)) &&
494          "createClassType should be called with a valid Context");
495 
496   auto *R = DICompositeType::get(
497       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
498       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
499       OffsetInBits, Flags, Elements, 0, VTableHolder,
500       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
501   trackIfUnresolved(R);
502   return R;
503 }
504 
505 DICompositeType *DIBuilder::createStructType(
506     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
507     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
508     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
509     DIType *VTableHolder, StringRef UniqueIdentifier) {
510   auto *R = DICompositeType::get(
511       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
512       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
513       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
514   trackIfUnresolved(R);
515   return R;
516 }
517 
518 DICompositeType *DIBuilder::createUnionType(
519     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
520     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
521     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
522   auto *R = DICompositeType::get(
523       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
524       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
525       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
526   trackIfUnresolved(R);
527   return R;
528 }
529 
530 DICompositeType *
531 DIBuilder::createVariantPart(DIScope *Scope, StringRef Name, DIFile *File,
532                              unsigned LineNumber, uint64_t SizeInBits,
533                              uint32_t AlignInBits, DINode::DIFlags Flags,
534                              DIDerivedType *Discriminator, DINodeArray Elements,
535                              StringRef UniqueIdentifier) {
536   auto *R = DICompositeType::get(
537       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
538       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
539       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
540   trackIfUnresolved(R);
541   return R;
542 }
543 
544 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
545                                                   DINode::DIFlags Flags,
546                                                   unsigned CC) {
547   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
548 }
549 
550 DICompositeType *DIBuilder::createEnumerationType(
551     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
552     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
553     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
554   auto *CTy = DICompositeType::get(
555       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
556       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
557       IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
558       nullptr, UniqueIdentifier);
559   AllEnumTypes.push_back(CTy);
560   trackIfUnresolved(CTy);
561   return CTy;
562 }
563 
564 DIDerivedType *DIBuilder::createSetType(DIScope *Scope, StringRef Name,
565                                         DIFile *File, unsigned LineNo,
566                                         uint64_t SizeInBits,
567                                         uint32_t AlignInBits, DIType *Ty) {
568   auto *R =
569       DIDerivedType::get(VMContext, dwarf::DW_TAG_set_type, Name, File, LineNo,
570                          getNonCompileUnitScope(Scope), Ty, SizeInBits,
571                          AlignInBits, 0, None, DINode::FlagZero);
572   trackIfUnresolved(R);
573   return R;
574 }
575 
576 DICompositeType *
577 DIBuilder::createArrayType(uint64_t Size, uint32_t AlignInBits, DIType *Ty,
578                            DINodeArray Subscripts,
579                            PointerUnion<DIExpression *, DIVariable *> DL,
580                            PointerUnion<DIExpression *, DIVariable *> AS,
581                            PointerUnion<DIExpression *, DIVariable *> AL,
582                            PointerUnion<DIExpression *, DIVariable *> RK) {
583   auto *R = DICompositeType::get(
584       VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty, Size,
585       AlignInBits, 0, DINode::FlagZero, Subscripts, 0, nullptr, nullptr, "",
586       nullptr,
587       DL.is<DIExpression *>() ? (Metadata *)DL.get<DIExpression *>()
588                               : (Metadata *)DL.get<DIVariable *>(),
589       AS.is<DIExpression *>() ? (Metadata *)AS.get<DIExpression *>()
590                               : (Metadata *)AS.get<DIVariable *>(),
591       AL.is<DIExpression *>() ? (Metadata *)AL.get<DIExpression *>()
592                               : (Metadata *)AL.get<DIVariable *>(),
593       RK.is<DIExpression *>() ? (Metadata *)RK.get<DIExpression *>()
594                               : (Metadata *)RK.get<DIVariable *>());
595   trackIfUnresolved(R);
596   return R;
597 }
598 
599 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
600                                              uint32_t AlignInBits, DIType *Ty,
601                                              DINodeArray Subscripts) {
602   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
603                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
604                                  DINode::FlagVector, Subscripts, 0, nullptr);
605   trackIfUnresolved(R);
606   return R;
607 }
608 
609 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
610   auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
611   return MDNode::replaceWithDistinct(std::move(NewSP));
612 }
613 
614 static DIType *createTypeWithFlags(const DIType *Ty,
615                                    DINode::DIFlags FlagsToSet) {
616   auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
617   return MDNode::replaceWithUniqued(std::move(NewTy));
618 }
619 
620 DIType *DIBuilder::createArtificialType(DIType *Ty) {
621   // FIXME: Restrict this to the nodes where it's valid.
622   if (Ty->isArtificial())
623     return Ty;
624   return createTypeWithFlags(Ty, DINode::FlagArtificial);
625 }
626 
627 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
628   // FIXME: Restrict this to the nodes where it's valid.
629   if (Ty->isObjectPointer())
630     return Ty;
631   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
632   return createTypeWithFlags(Ty, Flags);
633 }
634 
635 void DIBuilder::retainType(DIScope *T) {
636   assert(T && "Expected non-null type");
637   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
638                              cast<DISubprogram>(T)->isDefinition() == false)) &&
639          "Expected type or subprogram declaration");
640   AllRetainTypes.emplace_back(T);
641 }
642 
643 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
644 
645 DICompositeType *
646 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
647                              DIFile *F, unsigned Line, unsigned RuntimeLang,
648                              uint64_t SizeInBits, uint32_t AlignInBits,
649                              StringRef UniqueIdentifier) {
650   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
651   // replaceWithUniqued().
652   auto *RetTy = DICompositeType::get(
653       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
654       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
655       nullptr, nullptr, UniqueIdentifier);
656   trackIfUnresolved(RetTy);
657   return RetTy;
658 }
659 
660 DICompositeType *DIBuilder::createReplaceableCompositeType(
661     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
662     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
663     DINode::DIFlags Flags, StringRef UniqueIdentifier,
664     DINodeArray Annotations) {
665   auto *RetTy =
666       DICompositeType::getTemporary(
667           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
668           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
669           nullptr, UniqueIdentifier, nullptr, nullptr, nullptr, nullptr,
670           nullptr, Annotations)
671           .release();
672   trackIfUnresolved(RetTy);
673   return RetTy;
674 }
675 
676 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
677   return MDTuple::get(VMContext, Elements);
678 }
679 
680 DIMacroNodeArray
681 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
682   return MDTuple::get(VMContext, Elements);
683 }
684 
685 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
686   SmallVector<llvm::Metadata *, 16> Elts;
687   for (Metadata *E : Elements) {
688     if (isa_and_nonnull<MDNode>(E))
689       Elts.push_back(cast<DIType>(E));
690     else
691       Elts.push_back(E);
692   }
693   return DITypeRefArray(MDNode::get(VMContext, Elts));
694 }
695 
696 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
697   auto *LB = ConstantAsMetadata::get(
698       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
699   auto *CountNode = ConstantAsMetadata::get(
700       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Count));
701   return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
702 }
703 
704 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
705   auto *LB = ConstantAsMetadata::get(
706       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
707   return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
708 }
709 
710 DISubrange *DIBuilder::getOrCreateSubrange(Metadata *CountNode, Metadata *LB,
711                                            Metadata *UB, Metadata *Stride) {
712   return DISubrange::get(VMContext, CountNode, LB, UB, Stride);
713 }
714 
715 DIGenericSubrange *DIBuilder::getOrCreateGenericSubrange(
716     DIGenericSubrange::BoundType CountNode, DIGenericSubrange::BoundType LB,
717     DIGenericSubrange::BoundType UB, DIGenericSubrange::BoundType Stride) {
718   auto ConvToMetadata = [&](DIGenericSubrange::BoundType Bound) -> Metadata * {
719     return Bound.is<DIExpression *>() ? (Metadata *)Bound.get<DIExpression *>()
720                                       : (Metadata *)Bound.get<DIVariable *>();
721   };
722   return DIGenericSubrange::get(VMContext, ConvToMetadata(CountNode),
723                                 ConvToMetadata(LB), ConvToMetadata(UB),
724                                 ConvToMetadata(Stride));
725 }
726 
727 static void checkGlobalVariableScope(DIScope *Context) {
728 #ifndef NDEBUG
729   if (auto *CT =
730           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
731     assert(CT->getIdentifier().empty() &&
732            "Context of a global variable should not be a type with identifier");
733 #endif
734 }
735 
736 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
737     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
738     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, bool isDefined,
739     DIExpression *Expr, MDNode *Decl, MDTuple *TemplateParams,
740     uint32_t AlignInBits, DINodeArray Annotations) {
741   checkGlobalVariableScope(Context);
742 
743   auto *GV = DIGlobalVariable::getDistinct(
744       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
745       LineNumber, Ty, IsLocalToUnit, isDefined,
746       cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits,
747       Annotations);
748   if (!Expr)
749     Expr = createExpression();
750   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
751   AllGVs.push_back(N);
752   return N;
753 }
754 
755 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
756     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
757     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
758     MDTuple *TemplateParams, uint32_t AlignInBits) {
759   checkGlobalVariableScope(Context);
760 
761   return DIGlobalVariable::getTemporary(
762              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
763              LineNumber, Ty, IsLocalToUnit, false,
764              cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits,
765              nullptr)
766       .release();
767 }
768 
769 static DILocalVariable *createLocalVariable(
770     LLVMContext &VMContext,
771     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
772     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
773     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
774     uint32_t AlignInBits, DINodeArray Annotations = nullptr) {
775   // FIXME: Why getNonCompileUnitScope()?
776   // FIXME: Why is "!Context" okay here?
777   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
778   // the only valid scopes)?
779   DIScope *Context = getNonCompileUnitScope(Scope);
780 
781   auto *Node = DILocalVariable::get(
782       VMContext, cast_or_null<DILocalScope>(Context), Name, File, LineNo, Ty,
783       ArgNo, Flags, AlignInBits, Annotations);
784   if (AlwaysPreserve) {
785     // The optimizer may remove local variables. If there is an interest
786     // to preserve variable info in such situation then stash it in a
787     // named mdnode.
788     DISubprogram *Fn = getDISubprogram(Scope);
789     assert(Fn && "Missing subprogram for local variable");
790     PreservedVariables[Fn].emplace_back(Node);
791   }
792   return Node;
793 }
794 
795 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
796                                                DIFile *File, unsigned LineNo,
797                                                DIType *Ty, bool AlwaysPreserve,
798                                                DINode::DIFlags Flags,
799                                                uint32_t AlignInBits) {
800   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
801                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
802                              Flags, AlignInBits);
803 }
804 
805 DILocalVariable *DIBuilder::createParameterVariable(
806     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
807     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
808     DINodeArray Annotations) {
809   assert(ArgNo && "Expected non-zero argument number for parameter");
810   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
811                              File, LineNo, Ty, AlwaysPreserve, Flags,
812                              /*AlignInBits=*/0, Annotations);
813 }
814 
815 DILabel *DIBuilder::createLabel(DIScope *Scope, StringRef Name, DIFile *File,
816                                 unsigned LineNo, bool AlwaysPreserve) {
817   DIScope *Context = getNonCompileUnitScope(Scope);
818 
819   auto *Node = DILabel::get(VMContext, cast_or_null<DILocalScope>(Context),
820                             Name, File, LineNo);
821 
822   if (AlwaysPreserve) {
823     /// The optimizer may remove labels. If there is an interest
824     /// to preserve label info in such situation then append it to
825     /// the list of retained nodes of the DISubprogram.
826     DISubprogram *Fn = getDISubprogram(Scope);
827     assert(Fn && "Missing subprogram for label");
828     PreservedLabels[Fn].emplace_back(Node);
829   }
830   return Node;
831 }
832 
833 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
834   return DIExpression::get(VMContext, Addr);
835 }
836 
837 template <class... Ts>
838 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&...Args) {
839   if (IsDistinct)
840     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
841   return DISubprogram::get(std::forward<Ts>(Args)...);
842 }
843 
844 DISubprogram *DIBuilder::createFunction(
845     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
846     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
847     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
848     DITemplateParameterArray TParams, DISubprogram *Decl,
849     DITypeArray ThrownTypes, DINodeArray Annotations,
850     StringRef TargetFuncName) {
851   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
852   auto *Node = getSubprogram(
853       /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
854       Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
855       SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
856       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes,
857       Annotations, TargetFuncName);
858 
859   if (IsDefinition)
860     AllSubprograms.push_back(Node);
861   trackIfUnresolved(Node);
862   return Node;
863 }
864 
865 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
866     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
867     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
868     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
869     DITemplateParameterArray TParams, DISubprogram *Decl,
870     DITypeArray ThrownTypes) {
871   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
872   return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
873                                     Name, LinkageName, File, LineNo, Ty,
874                                     ScopeLine, nullptr, 0, 0, Flags, SPFlags,
875                                     IsDefinition ? CUNode : nullptr, TParams,
876                                     Decl, nullptr, ThrownTypes)
877       .release();
878 }
879 
880 DISubprogram *DIBuilder::createMethod(
881     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
882     unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
883     DIType *VTableHolder, DINode::DIFlags Flags,
884     DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
885     DITypeArray ThrownTypes) {
886   assert(getNonCompileUnitScope(Context) &&
887          "Methods should have both a Context and a context that isn't "
888          "the compile unit.");
889   // FIXME: Do we want to use different scope/lines?
890   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
891   auto *SP = getSubprogram(
892       /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
893       LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
894       Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
895       nullptr, ThrownTypes);
896 
897   if (IsDefinition)
898     AllSubprograms.push_back(SP);
899   trackIfUnresolved(SP);
900   return SP;
901 }
902 
903 DICommonBlock *DIBuilder::createCommonBlock(DIScope *Scope,
904                                             DIGlobalVariable *Decl,
905                                             StringRef Name, DIFile *File,
906                                             unsigned LineNo) {
907   return DICommonBlock::get(VMContext, Scope, Decl, Name, File, LineNo);
908 }
909 
910 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
911                                         bool ExportSymbols) {
912 
913   // It is okay to *not* make anonymous top-level namespaces distinct, because
914   // all nodes that have an anonymous namespace as their parent scope are
915   // guaranteed to be unique and/or are linked to their containing
916   // DICompileUnit. This decision is an explicit tradeoff of link time versus
917   // memory usage versus code simplicity and may get revisited in the future.
918   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
919                           ExportSymbols);
920 }
921 
922 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
923                                   StringRef ConfigurationMacros,
924                                   StringRef IncludePath, StringRef APINotesFile,
925                                   DIFile *File, unsigned LineNo, bool IsDecl) {
926   return DIModule::get(VMContext, File, getNonCompileUnitScope(Scope), Name,
927                        ConfigurationMacros, IncludePath, APINotesFile, LineNo,
928                        IsDecl);
929 }
930 
931 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
932                                                       DIFile *File,
933                                                       unsigned Discriminator) {
934   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
935 }
936 
937 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
938                                               unsigned Line, unsigned Col) {
939   // Make these distinct, to avoid merging two lexical blocks on the same
940   // file/line/column.
941   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
942                                      File, Line, Col);
943 }
944 
945 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
946                                       DIExpression *Expr, const DILocation *DL,
947                                       Instruction *InsertBefore) {
948   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
949                        InsertBefore);
950 }
951 
952 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
953                                       DIExpression *Expr, const DILocation *DL,
954                                       BasicBlock *InsertAtEnd) {
955   // If this block already has a terminator then insert this intrinsic before
956   // the terminator. Otherwise, put it at the end of the block.
957   Instruction *InsertBefore = InsertAtEnd->getTerminator();
958   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
959 }
960 
961 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
962                                     Instruction *InsertBefore) {
963   return insertLabel(LabelInfo, DL,
964                      InsertBefore ? InsertBefore->getParent() : nullptr,
965                      InsertBefore);
966 }
967 
968 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
969                                     BasicBlock *InsertAtEnd) {
970   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
971 }
972 
973 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
974                                                 DILocalVariable *VarInfo,
975                                                 DIExpression *Expr,
976                                                 const DILocation *DL,
977                                                 Instruction *InsertBefore) {
978   return insertDbgValueIntrinsic(
979       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
980       InsertBefore);
981 }
982 
983 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
984                                                 DILocalVariable *VarInfo,
985                                                 DIExpression *Expr,
986                                                 const DILocation *DL,
987                                                 BasicBlock *InsertAtEnd) {
988   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
989 }
990 
991 Instruction *DIBuilder::insertDbgAddrIntrinsic(Value *V,
992                                                DILocalVariable *VarInfo,
993                                                DIExpression *Expr,
994                                                const DILocation *DL,
995                                                Instruction *InsertBefore) {
996   return insertDbgAddrIntrinsic(
997       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
998       InsertBefore);
999 }
1000 
1001 Instruction *DIBuilder::insertDbgAddrIntrinsic(Value *V,
1002                                                DILocalVariable *VarInfo,
1003                                                DIExpression *Expr,
1004                                                const DILocation *DL,
1005                                                BasicBlock *InsertAtEnd) {
1006   return insertDbgAddrIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
1007 }
1008 
1009 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
1010 /// This abstracts over the various ways to specify an insert position.
1011 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
1012                           BasicBlock *InsertBB, Instruction *InsertBefore) {
1013   if (InsertBefore)
1014     Builder.SetInsertPoint(InsertBefore);
1015   else if (InsertBB)
1016     Builder.SetInsertPoint(InsertBB);
1017   Builder.SetCurrentDebugLocation(DL);
1018 }
1019 
1020 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
1021   assert(V && "no value passed to dbg intrinsic");
1022   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
1023 }
1024 
1025 static Function *getDeclareIntrin(Module &M) {
1026   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
1027                                                   : Intrinsic::dbg_declare);
1028 }
1029 
1030 Instruction *DIBuilder::insertDbgValueIntrinsic(
1031     llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
1032     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
1033   if (!ValueFn)
1034     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1035   return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
1036                             InsertBefore);
1037 }
1038 
1039 Instruction *DIBuilder::insertDbgAddrIntrinsic(
1040     llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
1041     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
1042   if (!AddrFn)
1043     AddrFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_addr);
1044   return insertDbgIntrinsic(AddrFn, Val, VarInfo, Expr, DL, InsertBB,
1045                             InsertBefore);
1046 }
1047 
1048 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
1049                                       DIExpression *Expr, const DILocation *DL,
1050                                       BasicBlock *InsertBB,
1051                                       Instruction *InsertBefore) {
1052   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
1053   assert(DL && "Expected debug loc");
1054   assert(DL->getScope()->getSubprogram() ==
1055              VarInfo->getScope()->getSubprogram() &&
1056          "Expected matching subprograms");
1057   if (!DeclareFn)
1058     DeclareFn = getDeclareIntrin(M);
1059 
1060   trackIfUnresolved(VarInfo);
1061   trackIfUnresolved(Expr);
1062   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1063                    MetadataAsValue::get(VMContext, VarInfo),
1064                    MetadataAsValue::get(VMContext, Expr)};
1065 
1066   IRBuilder<> B(DL->getContext());
1067   initIRBuilder(B, DL, InsertBB, InsertBefore);
1068   return B.CreateCall(DeclareFn, Args);
1069 }
1070 
1071 Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn,
1072                                            Value *V, DILocalVariable *VarInfo,
1073                                            DIExpression *Expr,
1074                                            const DILocation *DL,
1075                                            BasicBlock *InsertBB,
1076                                            Instruction *InsertBefore) {
1077   assert(IntrinsicFn && "must pass a non-null intrinsic function");
1078   assert(V && "must pass a value to a dbg intrinsic");
1079   assert(VarInfo &&
1080          "empty or invalid DILocalVariable* passed to debug intrinsic");
1081   assert(DL && "Expected debug loc");
1082   assert(DL->getScope()->getSubprogram() ==
1083              VarInfo->getScope()->getSubprogram() &&
1084          "Expected matching subprograms");
1085 
1086   trackIfUnresolved(VarInfo);
1087   trackIfUnresolved(Expr);
1088   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1089                    MetadataAsValue::get(VMContext, VarInfo),
1090                    MetadataAsValue::get(VMContext, Expr)};
1091 
1092   IRBuilder<> B(DL->getContext());
1093   initIRBuilder(B, DL, InsertBB, InsertBefore);
1094   return B.CreateCall(IntrinsicFn, Args);
1095 }
1096 
1097 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
1098                                     BasicBlock *InsertBB,
1099                                     Instruction *InsertBefore) {
1100   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
1101   assert(DL && "Expected debug loc");
1102   assert(DL->getScope()->getSubprogram() ==
1103              LabelInfo->getScope()->getSubprogram() &&
1104          "Expected matching subprograms");
1105   if (!LabelFn)
1106     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
1107 
1108   trackIfUnresolved(LabelInfo);
1109   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
1110 
1111   IRBuilder<> B(DL->getContext());
1112   initIRBuilder(B, DL, InsertBB, InsertBefore);
1113   return B.CreateCall(LabelFn, Args);
1114 }
1115 
1116 void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) {
1117   {
1118     TypedTrackingMDRef<DICompositeType> N(T);
1119     N->replaceVTableHolder(VTableHolder);
1120     T = N.get();
1121   }
1122 
1123   // If this didn't create a self-reference, just return.
1124   if (T != VTableHolder)
1125     return;
1126 
1127   // Look for unresolved operands.  T will drop RAUW support, orphaning any
1128   // cycles underneath it.
1129   if (T->isResolved())
1130     for (const MDOperand &O : T->operands())
1131       if (auto *N = dyn_cast_or_null<MDNode>(O))
1132         trackIfUnresolved(N);
1133 }
1134 
1135 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1136                               DINodeArray TParams) {
1137   {
1138     TypedTrackingMDRef<DICompositeType> N(T);
1139     if (Elements)
1140       N->replaceElements(Elements);
1141     if (TParams)
1142       N->replaceTemplateParams(DITemplateParameterArray(TParams));
1143     T = N.get();
1144   }
1145 
1146   // If T isn't resolved, there's no problem.
1147   if (!T->isResolved())
1148     return;
1149 
1150   // If T is resolved, it may be due to a self-reference cycle.  Track the
1151   // arrays explicitly if they're unresolved, or else the cycles will be
1152   // orphaned.
1153   if (Elements)
1154     trackIfUnresolved(Elements.get());
1155   if (TParams)
1156     trackIfUnresolved(TParams.get());
1157 }
1158