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