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