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