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