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