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) {
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);
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, Val, IsUnsigned, Name);
250 }
251 
252 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
253   assert(!Name.empty() && "Unable to create type without name");
254   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
255 }
256 
257 DIBasicType *DIBuilder::createNullPtrType() {
258   return createUnspecifiedType("decltype(nullptr)");
259 }
260 
261 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
262                                         unsigned Encoding,
263                                         DINode::DIFlags Flags) {
264   assert(!Name.empty() && "Unable to create type without name");
265   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
266                           0, Encoding, Flags);
267 }
268 
269 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
270   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
271                             0, 0, None, DINode::FlagZero);
272 }
273 
274 DIDerivedType *DIBuilder::createPointerType(
275     DIType *PointeeTy,
276     uint64_t SizeInBits,
277     uint32_t AlignInBits,
278     Optional<unsigned> DWARFAddressSpace,
279     StringRef Name) {
280   // FIXME: Why is there a name here?
281   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
282                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
283                             AlignInBits, 0, DWARFAddressSpace,
284                             DINode::FlagZero);
285 }
286 
287 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
288                                                   DIType *Base,
289                                                   uint64_t SizeInBits,
290                                                   uint32_t AlignInBits,
291                                                   DINode::DIFlags Flags) {
292   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
293                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
294                             AlignInBits, 0, None, Flags, Base);
295 }
296 
297 DIDerivedType *DIBuilder::createReferenceType(
298     unsigned Tag, DIType *RTy,
299     uint64_t SizeInBits,
300     uint32_t AlignInBits,
301     Optional<unsigned> DWARFAddressSpace) {
302   assert(RTy && "Unable to create reference type");
303   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
304                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
305                             DINode::FlagZero);
306 }
307 
308 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
309                                         DIFile *File, unsigned LineNo,
310                                         DIScope *Context,
311                                         uint32_t AlignInBits) {
312   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
313                             LineNo, getNonCompileUnitScope(Context), Ty, 0,
314                             AlignInBits, 0, None, DINode::FlagZero);
315 }
316 
317 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
318   assert(Ty && "Invalid type!");
319   assert(FriendTy && "Invalid friend type!");
320   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
321                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
322 }
323 
324 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
325                                             uint64_t BaseOffset,
326                                             uint32_t VBPtrOffset,
327                                             DINode::DIFlags Flags) {
328   assert(Ty && "Unable to create inheritance");
329   Metadata *ExtraData = ConstantAsMetadata::get(
330       ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
331   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
332                             0, Ty, BaseTy, 0, 0, BaseOffset, None,
333                             Flags, ExtraData);
334 }
335 
336 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
337                                            DIFile *File, unsigned LineNumber,
338                                            uint64_t SizeInBits,
339                                            uint32_t AlignInBits,
340                                            uint64_t OffsetInBits,
341                                            DINode::DIFlags Flags, DIType *Ty) {
342   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
343                             LineNumber, getNonCompileUnitScope(Scope), Ty,
344                             SizeInBits, AlignInBits, OffsetInBits, None, Flags);
345 }
346 
347 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
348   if (C)
349     return ConstantAsMetadata::get(C);
350   return nullptr;
351 }
352 
353 DIDerivedType *DIBuilder::createVariantMemberType(
354     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
355     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
356     Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
357   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
358                             LineNumber, getNonCompileUnitScope(Scope), Ty,
359                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
360                             getConstantOrNull(Discriminant));
361 }
362 
363 DIDerivedType *DIBuilder::createBitFieldMemberType(
364     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
365     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
366     DINode::DIFlags Flags, DIType *Ty) {
367   Flags |= DINode::FlagBitField;
368   return DIDerivedType::get(
369       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
370       getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
371       OffsetInBits, None, Flags,
372       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
373                                                StorageOffsetInBits)));
374 }
375 
376 DIDerivedType *
377 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
378                                   unsigned LineNumber, DIType *Ty,
379                                   DINode::DIFlags Flags, llvm::Constant *Val,
380                                   uint32_t AlignInBits) {
381   Flags |= DINode::FlagStaticMember;
382   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
383                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
384                             AlignInBits, 0, None, Flags,
385                             getConstantOrNull(Val));
386 }
387 
388 DIDerivedType *
389 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
390                           uint64_t SizeInBits, uint32_t AlignInBits,
391                           uint64_t OffsetInBits, DINode::DIFlags Flags,
392                           DIType *Ty, MDNode *PropertyNode) {
393   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
394                             LineNumber, getNonCompileUnitScope(File), Ty,
395                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
396                             PropertyNode);
397 }
398 
399 DIObjCProperty *
400 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
401                               StringRef GetterName, StringRef SetterName,
402                               unsigned PropertyAttributes, DIType *Ty) {
403   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
404                              SetterName, PropertyAttributes, Ty);
405 }
406 
407 DITemplateTypeParameter *
408 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
409                                        DIType *Ty) {
410   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
411   return DITemplateTypeParameter::get(VMContext, Name, Ty);
412 }
413 
414 static DITemplateValueParameter *
415 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
416                                    DIScope *Context, StringRef Name, DIType *Ty,
417                                    Metadata *MD) {
418   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
419   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
420 }
421 
422 DITemplateValueParameter *
423 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
424                                         DIType *Ty, Constant *Val) {
425   return createTemplateValueParameterHelper(
426       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
427       getConstantOrNull(Val));
428 }
429 
430 DITemplateValueParameter *
431 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
432                                            DIType *Ty, StringRef Val) {
433   return createTemplateValueParameterHelper(
434       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
435       MDString::get(VMContext, Val));
436 }
437 
438 DITemplateValueParameter *
439 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
440                                        DIType *Ty, DINodeArray Val) {
441   return createTemplateValueParameterHelper(
442       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
443       Val.get());
444 }
445 
446 DICompositeType *DIBuilder::createClassType(
447     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
448     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
449     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
450     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
451   assert((!Context || isa<DIScope>(Context)) &&
452          "createClassType should be called with a valid Context");
453 
454   auto *R = DICompositeType::get(
455       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
456       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
457       OffsetInBits, Flags, Elements, 0, VTableHolder,
458       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
459   trackIfUnresolved(R);
460   return R;
461 }
462 
463 DICompositeType *DIBuilder::createStructType(
464     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
465     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
466     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
467     DIType *VTableHolder, StringRef UniqueIdentifier) {
468   auto *R = DICompositeType::get(
469       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
470       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
471       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
472   trackIfUnresolved(R);
473   return R;
474 }
475 
476 DICompositeType *DIBuilder::createUnionType(
477     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
478     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
479     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
480   auto *R = DICompositeType::get(
481       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
482       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
483       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
484   trackIfUnresolved(R);
485   return R;
486 }
487 
488 DICompositeType *DIBuilder::createVariantPart(
489     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
490     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
491     DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
492   auto *R = DICompositeType::get(
493       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
494       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
495       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
496   trackIfUnresolved(R);
497   return R;
498 }
499 
500 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
501                                                   DINode::DIFlags Flags,
502                                                   unsigned CC) {
503   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
504 }
505 
506 DICompositeType *DIBuilder::createEnumerationType(
507     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
508     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
509     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
510   auto *CTy = DICompositeType::get(
511       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
512       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
513       IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
514       nullptr, UniqueIdentifier);
515   AllEnumTypes.push_back(CTy);
516   trackIfUnresolved(CTy);
517   return CTy;
518 }
519 
520 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
521                                             uint32_t AlignInBits, DIType *Ty,
522                                             DINodeArray Subscripts) {
523   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
524                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
525                                  DINode::FlagZero, Subscripts, 0, nullptr);
526   trackIfUnresolved(R);
527   return R;
528 }
529 
530 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
531                                              uint32_t AlignInBits, DIType *Ty,
532                                              DINodeArray Subscripts) {
533   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
534                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
535                                  DINode::FlagVector, Subscripts, 0, nullptr);
536   trackIfUnresolved(R);
537   return R;
538 }
539 
540 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
541   auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
542   return MDNode::replaceWithDistinct(std::move(NewSP));
543 }
544 
545 static DIType *createTypeWithFlags(const DIType *Ty,
546                                    DINode::DIFlags FlagsToSet) {
547   auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
548   return MDNode::replaceWithUniqued(std::move(NewTy));
549 }
550 
551 DIType *DIBuilder::createArtificialType(DIType *Ty) {
552   // FIXME: Restrict this to the nodes where it's valid.
553   if (Ty->isArtificial())
554     return Ty;
555   return createTypeWithFlags(Ty, DINode::FlagArtificial);
556 }
557 
558 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
559   // FIXME: Restrict this to the nodes where it's valid.
560   if (Ty->isObjectPointer())
561     return Ty;
562   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
563   return createTypeWithFlags(Ty, Flags);
564 }
565 
566 void DIBuilder::retainType(DIScope *T) {
567   assert(T && "Expected non-null type");
568   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
569                              cast<DISubprogram>(T)->isDefinition() == false)) &&
570          "Expected type or subprogram declaration");
571   AllRetainTypes.emplace_back(T);
572 }
573 
574 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
575 
576 DICompositeType *
577 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
578                              DIFile *F, unsigned Line, unsigned RuntimeLang,
579                              uint64_t SizeInBits, uint32_t AlignInBits,
580                              StringRef UniqueIdentifier) {
581   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
582   // replaceWithUniqued().
583   auto *RetTy = DICompositeType::get(
584       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
585       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
586       nullptr, nullptr, UniqueIdentifier);
587   trackIfUnresolved(RetTy);
588   return RetTy;
589 }
590 
591 DICompositeType *DIBuilder::createReplaceableCompositeType(
592     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
593     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
594     DINode::DIFlags Flags, StringRef UniqueIdentifier) {
595   auto *RetTy =
596       DICompositeType::getTemporary(
597           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
598           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
599           nullptr, UniqueIdentifier)
600           .release();
601   trackIfUnresolved(RetTy);
602   return RetTy;
603 }
604 
605 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
606   return MDTuple::get(VMContext, Elements);
607 }
608 
609 DIMacroNodeArray
610 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
611   return MDTuple::get(VMContext, Elements);
612 }
613 
614 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
615   SmallVector<llvm::Metadata *, 16> Elts;
616   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
617     if (Elements[i] && isa<MDNode>(Elements[i]))
618       Elts.push_back(cast<DIType>(Elements[i]));
619     else
620       Elts.push_back(Elements[i]);
621   }
622   return DITypeRefArray(MDNode::get(VMContext, Elts));
623 }
624 
625 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
626   return DISubrange::get(VMContext, Count, Lo);
627 }
628 
629 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
630   return DISubrange::get(VMContext, CountNode, Lo);
631 }
632 
633 static void checkGlobalVariableScope(DIScope *Context) {
634 #ifndef NDEBUG
635   if (auto *CT =
636           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
637     assert(CT->getIdentifier().empty() &&
638            "Context of a global variable should not be a type with identifier");
639 #endif
640 }
641 
642 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
643     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
644     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit,
645     bool isDefined, DIExpression *Expr,
646     MDNode *Decl, MDTuple *TemplateParams, uint32_t AlignInBits) {
647   checkGlobalVariableScope(Context);
648 
649   auto *GV = DIGlobalVariable::getDistinct(
650       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
651       LineNumber, Ty, IsLocalToUnit, isDefined, cast_or_null<DIDerivedType>(Decl),
652       TemplateParams, AlignInBits);
653   if (!Expr)
654     Expr = createExpression();
655   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
656   AllGVs.push_back(N);
657   return N;
658 }
659 
660 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
661     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
662     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
663     MDTuple *TemplateParams, uint32_t AlignInBits) {
664   checkGlobalVariableScope(Context);
665 
666   return DIGlobalVariable::getTemporary(
667              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
668              LineNumber, Ty, IsLocalToUnit, false,
669              cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits)
670       .release();
671 }
672 
673 static DILocalVariable *createLocalVariable(
674     LLVMContext &VMContext,
675     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
676     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
677     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
678     uint32_t AlignInBits) {
679   // FIXME: Why getNonCompileUnitScope()?
680   // FIXME: Why is "!Context" okay here?
681   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
682   // the only valid scopes)?
683   DIScope *Context = getNonCompileUnitScope(Scope);
684 
685   auto *Node =
686       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
687                            File, LineNo, Ty, ArgNo, Flags, AlignInBits);
688   if (AlwaysPreserve) {
689     // The optimizer may remove local variables. If there is an interest
690     // to preserve variable info in such situation then stash it in a
691     // named mdnode.
692     DISubprogram *Fn = getDISubprogram(Scope);
693     assert(Fn && "Missing subprogram for local variable");
694     PreservedVariables[Fn].emplace_back(Node);
695   }
696   return Node;
697 }
698 
699 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
700                                                DIFile *File, unsigned LineNo,
701                                                DIType *Ty, bool AlwaysPreserve,
702                                                DINode::DIFlags Flags,
703                                                uint32_t AlignInBits) {
704   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
705                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
706                              Flags, AlignInBits);
707 }
708 
709 DILocalVariable *DIBuilder::createParameterVariable(
710     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
711     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
712   assert(ArgNo && "Expected non-zero argument number for parameter");
713   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
714                              File, LineNo, Ty, AlwaysPreserve, Flags,
715                              /* AlignInBits */0);
716 }
717 
718 DILabel *DIBuilder::createLabel(
719     DIScope *Scope, StringRef Name, DIFile *File,
720     unsigned LineNo, bool AlwaysPreserve) {
721   DIScope *Context = getNonCompileUnitScope(Scope);
722 
723   auto *Node =
724       DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
725                    File, LineNo);
726 
727   if (AlwaysPreserve) {
728     /// The optimizer may remove labels. If there is an interest
729     /// to preserve label info in such situation then append it to
730     /// the list of retained nodes of the DISubprogram.
731     DISubprogram *Fn = getDISubprogram(Scope);
732     assert(Fn && "Missing subprogram for label");
733     PreservedLabels[Fn].emplace_back(Node);
734   }
735   return Node;
736 }
737 
738 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
739   return DIExpression::get(VMContext, Addr);
740 }
741 
742 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
743   // TODO: Remove the callers of this signed version and delete.
744   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
745   return createExpression(Addr);
746 }
747 
748 template <class... Ts>
749 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
750   if (IsDistinct)
751     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
752   return DISubprogram::get(std::forward<Ts>(Args)...);
753 }
754 
755 DISubprogram *DIBuilder::createFunction(
756     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
757     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
758     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
759     DITemplateParameterArray TParams, DISubprogram *Decl,
760     DITypeArray ThrownTypes) {
761   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
762   auto *Node = getSubprogram(
763       /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
764       Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
765       SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
766       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
767 
768   if (IsDefinition)
769     AllSubprograms.push_back(Node);
770   trackIfUnresolved(Node);
771   return Node;
772 }
773 
774 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
775     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
776     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
777     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
778     DITemplateParameterArray TParams, DISubprogram *Decl,
779     DITypeArray ThrownTypes) {
780   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
781   return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
782                                     Name, LinkageName, File, LineNo, Ty,
783                                     ScopeLine, nullptr, 0, 0, Flags, SPFlags,
784                                     IsDefinition ? CUNode : nullptr, TParams,
785                                     Decl, nullptr, ThrownTypes)
786       .release();
787 }
788 
789 DISubprogram *DIBuilder::createMethod(
790     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
791     unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
792     DIType *VTableHolder, DINode::DIFlags Flags,
793     DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
794     DITypeArray ThrownTypes) {
795   assert(getNonCompileUnitScope(Context) &&
796          "Methods should have both a Context and a context that isn't "
797          "the compile unit.");
798   // FIXME: Do we want to use different scope/lines?
799   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
800   auto *SP = getSubprogram(
801       /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
802       LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
803       Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
804       nullptr, ThrownTypes);
805 
806   if (IsDefinition)
807     AllSubprograms.push_back(SP);
808   trackIfUnresolved(SP);
809   return SP;
810 }
811 
812 DICommonBlock *DIBuilder::createCommonBlock(
813     DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
814     unsigned LineNo) {
815   return DICommonBlock::get(
816       VMContext, Scope, Decl, Name, File, LineNo);
817 }
818 
819 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
820                                         bool ExportSymbols) {
821 
822   // It is okay to *not* make anonymous top-level namespaces distinct, because
823   // all nodes that have an anonymous namespace as their parent scope are
824   // guaranteed to be unique and/or are linked to their containing
825   // DICompileUnit. This decision is an explicit tradeoff of link time versus
826   // memory usage versus code simplicity and may get revisited in the future.
827   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
828                           ExportSymbols);
829 }
830 
831 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
832                                   StringRef ConfigurationMacros,
833                                   StringRef IncludePath) {
834   return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
835                        ConfigurationMacros, IncludePath);
836 }
837 
838 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
839                                                       DIFile *File,
840                                                       unsigned Discriminator) {
841   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
842 }
843 
844 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
845                                               unsigned Line, unsigned Col) {
846   // Make these distinct, to avoid merging two lexical blocks on the same
847   // file/line/column.
848   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
849                                      File, Line, Col);
850 }
851 
852 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
853                                       DIExpression *Expr, const DILocation *DL,
854                                       Instruction *InsertBefore) {
855   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
856                        InsertBefore);
857 }
858 
859 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
860                                       DIExpression *Expr, const DILocation *DL,
861                                       BasicBlock *InsertAtEnd) {
862   // If this block already has a terminator then insert this intrinsic before
863   // the terminator. Otherwise, put it at the end of the block.
864   Instruction *InsertBefore = InsertAtEnd->getTerminator();
865   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
866 }
867 
868 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
869                                     Instruction *InsertBefore) {
870   return insertLabel(
871       LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
872       InsertBefore);
873 }
874 
875 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
876                                     BasicBlock *InsertAtEnd) {
877   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
878 }
879 
880 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
881                                                 DILocalVariable *VarInfo,
882                                                 DIExpression *Expr,
883                                                 const DILocation *DL,
884                                                 Instruction *InsertBefore) {
885   return insertDbgValueIntrinsic(
886       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
887       InsertBefore);
888 }
889 
890 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
891                                                 DILocalVariable *VarInfo,
892                                                 DIExpression *Expr,
893                                                 const DILocation *DL,
894                                                 BasicBlock *InsertAtEnd) {
895   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
896 }
897 
898 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
899 /// This abstracts over the various ways to specify an insert position.
900 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
901                           BasicBlock *InsertBB, Instruction *InsertBefore) {
902   if (InsertBefore)
903     Builder.SetInsertPoint(InsertBefore);
904   else if (InsertBB)
905     Builder.SetInsertPoint(InsertBB);
906   Builder.SetCurrentDebugLocation(DL);
907 }
908 
909 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
910   assert(V && "no value passed to dbg intrinsic");
911   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
912 }
913 
914 static Function *getDeclareIntrin(Module &M) {
915   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
916                                                   : Intrinsic::dbg_declare);
917 }
918 
919 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
920                                       DIExpression *Expr, const DILocation *DL,
921                                       BasicBlock *InsertBB, Instruction *InsertBefore) {
922   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
923   assert(DL && "Expected debug loc");
924   assert(DL->getScope()->getSubprogram() ==
925              VarInfo->getScope()->getSubprogram() &&
926          "Expected matching subprograms");
927   if (!DeclareFn)
928     DeclareFn = getDeclareIntrin(M);
929 
930   trackIfUnresolved(VarInfo);
931   trackIfUnresolved(Expr);
932   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
933                    MetadataAsValue::get(VMContext, VarInfo),
934                    MetadataAsValue::get(VMContext, Expr)};
935 
936   IRBuilder<> B(DL->getContext());
937   initIRBuilder(B, DL, InsertBB, InsertBefore);
938   return B.CreateCall(DeclareFn, Args);
939 }
940 
941 Instruction *DIBuilder::insertDbgValueIntrinsic(
942     Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
943     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
944   assert(V && "no value passed to dbg.value");
945   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
946   assert(DL && "Expected debug loc");
947   assert(DL->getScope()->getSubprogram() ==
948              VarInfo->getScope()->getSubprogram() &&
949          "Expected matching subprograms");
950   if (!ValueFn)
951     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
952 
953   trackIfUnresolved(VarInfo);
954   trackIfUnresolved(Expr);
955   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
956                    MetadataAsValue::get(VMContext, VarInfo),
957                    MetadataAsValue::get(VMContext, Expr)};
958 
959   IRBuilder<> B(DL->getContext());
960   initIRBuilder(B, DL, InsertBB, InsertBefore);
961   return B.CreateCall(ValueFn, Args);
962 }
963 
964 Instruction *DIBuilder::insertLabel(
965     DILabel *LabelInfo, const DILocation *DL,
966     BasicBlock *InsertBB, Instruction *InsertBefore) {
967   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
968   assert(DL && "Expected debug loc");
969   assert(DL->getScope()->getSubprogram() ==
970              LabelInfo->getScope()->getSubprogram() &&
971          "Expected matching subprograms");
972   if (!LabelFn)
973     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
974 
975   trackIfUnresolved(LabelInfo);
976   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
977 
978   IRBuilder<> B(DL->getContext());
979   initIRBuilder(B, DL, InsertBB, InsertBefore);
980   return B.CreateCall(LabelFn, Args);
981 }
982 
983 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
984                                     DIType *VTableHolder) {
985   {
986     TypedTrackingMDRef<DICompositeType> N(T);
987     N->replaceVTableHolder(VTableHolder);
988     T = N.get();
989   }
990 
991   // If this didn't create a self-reference, just return.
992   if (T != VTableHolder)
993     return;
994 
995   // Look for unresolved operands.  T will drop RAUW support, orphaning any
996   // cycles underneath it.
997   if (T->isResolved())
998     for (const MDOperand &O : T->operands())
999       if (auto *N = dyn_cast_or_null<MDNode>(O))
1000         trackIfUnresolved(N);
1001 }
1002 
1003 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1004                               DINodeArray TParams) {
1005   {
1006     TypedTrackingMDRef<DICompositeType> N(T);
1007     if (Elements)
1008       N->replaceElements(Elements);
1009     if (TParams)
1010       N->replaceTemplateParams(DITemplateParameterArray(TParams));
1011     T = N.get();
1012   }
1013 
1014   // If T isn't resolved, there's no problem.
1015   if (!T->isResolved())
1016     return;
1017 
1018   // If T is resolved, it may be due to a self-reference cycle.  Track the
1019   // arrays explicitly if they're unresolved, or else the cycles will be
1020   // orphaned.
1021   if (Elements)
1022     trackIfUnresolved(Elements.get());
1023   if (TParams)
1024     trackIfUnresolved(TParams.get());
1025 }
1026