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