DIBuilder: Similar to createPointerType, make createMemberPointerType take
[opencl/llvm.git] / lib / IR / DIBuilder.cpp
1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfo.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Dwarf.h"
23 using namespace llvm;
24 using namespace llvm::dwarf;
26 namespace {
27 class HeaderBuilder {
28   SmallVector<char, 256> Chars;
30 public:
31   explicit HeaderBuilder(Twine T) { T.toVector(Chars); }
32   HeaderBuilder(const HeaderBuilder &X) : Chars(X.Chars) {}
33   HeaderBuilder(HeaderBuilder &&X) : Chars(std::move(X.Chars)) {}
35   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
36     Chars.push_back(0);
37     Twine(X).toVector(Chars);
38     return *this;
39   }
41   MDString *get(LLVMContext &Context) const {
42     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
43   }
45   static HeaderBuilder get(unsigned Tag) {
46     return HeaderBuilder("0x" + Twine::utohexstr(Tag));
47   }
48 };
49 }
51 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
52     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
53       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
54       DeclareFn(nullptr), ValueFn(nullptr),
55       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
57 static bool isUnresolved(MDNode *N) {
58   return N && (isa<MDNodeFwdDecl>(N) || !cast<GenericMDNode>(N)->isResolved());
59 }
61 void DIBuilder::trackIfUnresolved(MDNode *N) {
62   if (!AllowUnresolvedNodes) {
63     assert(!isUnresolved(N) && "Cannot handle unresolved nodes");
64     return;
65   }
66   if (isUnresolved(N))
67     UnresolvedNodes.emplace_back(N);
68   return;
69 }
71 void DIBuilder::finalize() {
72   DIArray Enums = getOrCreateArray(AllEnumTypes);
73   DIType(TempEnumTypes).replaceAllUsesWith(Enums);
75   SmallVector<Metadata *, 16> RetainValues;
76   // Declarations and definitions of the same type may be retained. Some
77   // clients RAUW these pairs, leaving duplicates in the retained types
78   // list. Use a set to remove the duplicates while we transform the
79   // TrackingVHs back into Values.
80   SmallPtrSet<Metadata *, 16> RetainSet;
81   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
82     if (RetainSet.insert(AllRetainTypes[I]).second)
83       RetainValues.push_back(AllRetainTypes[I]);
84   DIArray RetainTypes = getOrCreateArray(RetainValues);
85   DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
87   DIArray SPs = getOrCreateArray(AllSubprograms);
88   DIType(TempSubprograms).replaceAllUsesWith(SPs);
89   for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
90     DISubprogram SP(SPs.getElement(i));
91     if (MDNode *Temp = SP.getVariablesNodes()) {
92       SmallVector<Metadata *, 4> Variables;
93       for (Metadata *V : PreservedVariables.lookup(SP))
94         Variables.push_back(V);
95       DIArray AV = getOrCreateArray(Variables);
96       DIType(Temp).replaceAllUsesWith(AV);
97     }
98   }
100   DIArray GVs = getOrCreateArray(AllGVs);
101   DIType(TempGVs).replaceAllUsesWith(GVs);
103   SmallVector<Metadata *, 16> RetainValuesI;
104   for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
105     RetainValuesI.push_back(AllImportedModules[I]);
106   DIArray IMs = getOrCreateArray(RetainValuesI);
107   DIType(TempImportedModules).replaceAllUsesWith(IMs);
109   // Now that all temp nodes have been replaced or deleted, resolve remaining
110   // cycles.
111   for (const auto &N : UnresolvedNodes)
112     if (N)
113       cast<GenericMDNode>(N)->resolveCycles();
114   UnresolvedNodes.clear();
116   // Can't handle unresolved nodes anymore.
117   AllowUnresolvedNodes = false;
120 /// If N is compile unit return NULL otherwise return N.
121 static MDNode *getNonCompileUnitScope(MDNode *N) {
122   if (DIDescriptor(N).isCompileUnit())
123     return nullptr;
124   return N;
127 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
128                                   StringRef Directory) {
129   assert(!Filename.empty() && "Unable to create file without name");
130   Metadata *Pair[] = {MDString::get(VMContext, Filename),
131                       MDString::get(VMContext, Directory)};
132   return MDNode::get(VMContext, Pair);
135 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
136                                            StringRef Directory,
137                                            StringRef Producer, bool isOptimized,
138                                            StringRef Flags, unsigned RunTimeVer,
139                                            StringRef SplitName,
140                                            DebugEmissionKind Kind,
141                                            bool EmitDebugInfo) {
143   assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
144           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
145          "Invalid Language tag");
146   assert(!Filename.empty() &&
147          "Unable to create compile unit without filename");
148   Metadata *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
149   TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
151   TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
153   TempSubprograms = MDNode::getTemporary(VMContext, TElts);
155   TempGVs = MDNode::getTemporary(VMContext, TElts);
157   TempImportedModules = MDNode::getTemporary(VMContext, TElts);
159   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
160                           .concat(Lang)
161                           .concat(Producer)
162                           .concat(isOptimized)
163                           .concat(Flags)
164                           .concat(RunTimeVer)
165                           .concat(SplitName)
166                           .concat(Kind)
167                           .get(VMContext),
168                       createFilePathPair(VMContext, Filename, Directory),
169                       TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
170                       TempImportedModules};
172   MDNode *CUNode = MDNode::get(VMContext, Elts);
174   // Create a named metadata so that it is easier to find cu in a module.
175   // Note that we only generate this when the caller wants to actually
176   // emit debug information. When we are only interested in tracking
177   // source line locations throughout the backend, we prevent codegen from
178   // emitting debug info in the final output by not generating llvm.dbg.cu.
179   if (EmitDebugInfo) {
180     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
181     NMD->addOperand(CUNode);
182   }
184   trackIfUnresolved(CUNode);
185   return DICompileUnit(CUNode);
188 static DIImportedEntity
189 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
190                      Metadata *NS, unsigned Line, StringRef Name,
191                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
192   const MDNode *R;
193   Metadata *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
194                       Context, NS};
195   R = MDNode::get(C, Elts);
196   DIImportedEntity M(R);
197   assert(M.Verify() && "Imported module should be valid");
198   AllImportedModules.emplace_back(M.get());
199   return M;
202 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
203                                                  DINameSpace NS,
204                                                  unsigned Line) {
205   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
206                                 Context, NS, Line, StringRef(), AllImportedModules);
209 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
210                                                  DIImportedEntity NS,
211                                                  unsigned Line) {
212   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
213                                 Context, NS, Line, StringRef(), AllImportedModules);
216 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
217                                                       DIDescriptor Decl,
218                                                       unsigned Line, StringRef Name) {
219   // Make sure to use the unique identifier based metadata reference for
220   // types that have one.
221   Metadata *V =
222       Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
223   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
224                                 Context, V, Line, Name,
225                                 AllImportedModules);
228 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
229                                                       DIImportedEntity Imp,
230                                                       unsigned Line, StringRef Name) {
231   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
232                                 Context, Imp, Line, Name, AllImportedModules);
235 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
236   Metadata *Elts[] = {
237       HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
238       createFilePathPair(VMContext, Filename, Directory)};
239   return DIFile(MDNode::get(VMContext, Elts));
242 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
243   assert(!Name.empty() && "Unable to create enumerator without name");
244   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_enumerator)
245                           .concat(Name)
246                           .concat(Val)
247                           .get(VMContext)};
248   return DIEnumerator(MDNode::get(VMContext, Elts));
251 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
252   assert(!Name.empty() && "Unable to create type without name");
253   // Unspecified types are encoded in DIBasicType format. Line number, filename,
254   // size, alignment, offset and flags are always empty here.
255   Metadata *Elts[] = {
256       HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
257           .concat(Name)
258           .concat(0)
259           .concat(0)
260           .concat(0)
261           .concat(0)
262           .concat(0)
263           .concat(0)
264           .get(VMContext),
265       nullptr, // Filename
266       nullptr  // Unused
267   };
268   return DIBasicType(MDNode::get(VMContext, Elts));
271 DIBasicType DIBuilder::createNullPtrType() {
272   return createUnspecifiedType("decltype(nullptr)");
275 DIBasicType
276 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
277                            uint64_t AlignInBits, unsigned Encoding) {
278   assert(!Name.empty() && "Unable to create type without name");
279   // Basic types are encoded in DIBasicType format. Line number, filename,
280   // offset and flags are always empty here.
281   Metadata *Elts[] = {
282       HeaderBuilder::get(dwarf::DW_TAG_base_type)
283           .concat(Name)
284           .concat(0) // Line
285           .concat(SizeInBits)
286           .concat(AlignInBits)
287           .concat(0) // Offset
288           .concat(0) // Flags
289           .concat(Encoding)
290           .get(VMContext),
291       nullptr, // Filename
292       nullptr  // Unused
293   };
294   return DIBasicType(MDNode::get(VMContext, Elts));
297 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
298   // Qualified types are encoded in DIDerivedType format.
299   Metadata *Elts[] = {HeaderBuilder::get(Tag)
300                           .concat(StringRef()) // Name
301                           .concat(0)           // Line
302                           .concat(0)           // Size
303                           .concat(0)           // Align
304                           .concat(0)           // Offset
305                           .concat(0)           // Flags
306                           .get(VMContext),
307                       nullptr, // Filename
308                       nullptr, // Unused
309                       FromTy.getRef()};
310   return DIDerivedType(MDNode::get(VMContext, Elts));
313 DIDerivedType
314 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
315                              uint64_t AlignInBits, StringRef Name) {
316   // Pointer types are encoded in DIDerivedType format.
317   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
318                           .concat(Name)
319                           .concat(0) // Line
320                           .concat(SizeInBits)
321                           .concat(AlignInBits)
322                           .concat(0) // Offset
323                           .concat(0) // Flags
324                           .get(VMContext),
325                       nullptr, // Filename
326                       nullptr, // Unused
327                       PointeeTy.getRef()};
328   return DIDerivedType(MDNode::get(VMContext, Elts));
331 DIDerivedType
332 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
333                                    uint64_t SizeInBits, uint64_t AlignInBits) {
334   // Pointer types are encoded in DIDerivedType format.
335   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
336                           .concat(StringRef())
337                           .concat(0) // Line
338                           .concat(SizeInBits) // Size
339                           .concat(AlignInBits) // Align
340                           .concat(0) // Offset
341                           .concat(0) // Flags
342                           .get(VMContext),
343                       nullptr, // Filename
344                       nullptr, // Unused
345                       PointeeTy.getRef(), Base.getRef()};
346   return DIDerivedType(MDNode::get(VMContext, Elts));
349 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
350   assert(RTy.isType() && "Unable to create reference type");
351   // References are encoded in DIDerivedType format.
352   Metadata *Elts[] = {HeaderBuilder::get(Tag)
353                           .concat(StringRef()) // Name
354                           .concat(0)           // Line
355                           .concat(0)           // Size
356                           .concat(0)           // Align
357                           .concat(0)           // Offset
358                           .concat(0)           // Flags
359                           .get(VMContext),
360                       nullptr, // Filename
361                       nullptr, // TheCU,
362                       RTy.getRef()};
363   return DIDerivedType(MDNode::get(VMContext, Elts));
366 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
367                                        unsigned LineNo, DIDescriptor Context) {
368   // typedefs are encoded in DIDerivedType format.
369   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
370                           .concat(Name)
371                           .concat(LineNo)
372                           .concat(0) // Size
373                           .concat(0) // Align
374                           .concat(0) // Offset
375                           .concat(0) // Flags
376                           .get(VMContext),
377                       File.getFileNode(),
378                       DIScope(getNonCompileUnitScope(Context)).getRef(),
379                       Ty.getRef()};
380   return DIDerivedType(MDNode::get(VMContext, Elts));
383 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
384   // typedefs are encoded in DIDerivedType format.
385   assert(Ty.isType() && "Invalid type!");
386   assert(FriendTy.isType() && "Invalid friend type!");
387   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
388                           .concat(StringRef()) // Name
389                           .concat(0)           // Line
390                           .concat(0)           // Size
391                           .concat(0)           // Align
392                           .concat(0)           // Offset
393                           .concat(0)           // Flags
394                           .get(VMContext),
395                       nullptr, Ty.getRef(), FriendTy.getRef()};
396   return DIDerivedType(MDNode::get(VMContext, Elts));
399 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
400                                            uint64_t BaseOffset,
401                                            unsigned Flags) {
402   assert(Ty.isType() && "Unable to create inheritance");
403   // TAG_inheritance is encoded in DIDerivedType format.
404   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
405                           .concat(StringRef()) // Name
406                           .concat(0)           // Line
407                           .concat(0)           // Size
408                           .concat(0)           // Align
409                           .concat(BaseOffset)
410                           .concat(Flags)
411                           .get(VMContext),
412                       nullptr, Ty.getRef(), BaseTy.getRef()};
413   return DIDerivedType(MDNode::get(VMContext, Elts));
416 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
417                                           DIFile File, unsigned LineNumber,
418                                           uint64_t SizeInBits,
419                                           uint64_t AlignInBits,
420                                           uint64_t OffsetInBits, unsigned Flags,
421                                           DIType Ty) {
422   // TAG_member is encoded in DIDerivedType format.
423   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
424                           .concat(Name)
425                           .concat(LineNumber)
426                           .concat(SizeInBits)
427                           .concat(AlignInBits)
428                           .concat(OffsetInBits)
429                           .concat(Flags)
430                           .get(VMContext),
431                       File.getFileNode(),
432                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
433                       Ty.getRef()};
434   return DIDerivedType(MDNode::get(VMContext, Elts));
437 static Metadata *getConstantOrNull(Constant *C) {
438   if (C)
439     return ConstantAsMetadata::get(C);
440   return nullptr;
443 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
444                                                 StringRef Name, DIFile File,
445                                                 unsigned LineNumber, DIType Ty,
446                                                 unsigned Flags,
447                                                 llvm::Constant *Val) {
448   // TAG_member is encoded in DIDerivedType format.
449   Flags |= DIDescriptor::FlagStaticMember;
450   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
451                           .concat(Name)
452                           .concat(LineNumber)
453                           .concat(0) // Size
454                           .concat(0) // Align
455                           .concat(0) // Offset
456                           .concat(Flags)
457                           .get(VMContext),
458                       File.getFileNode(),
459                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
460                       Ty.getRef(), getConstantOrNull(Val)};
461   return DIDerivedType(MDNode::get(VMContext, Elts));
464 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
465                                         unsigned LineNumber,
466                                         uint64_t SizeInBits,
467                                         uint64_t AlignInBits,
468                                         uint64_t OffsetInBits, unsigned Flags,
469                                         DIType Ty, MDNode *PropertyNode) {
470   // TAG_member is encoded in DIDerivedType format.
471   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
472                           .concat(Name)
473                           .concat(LineNumber)
474                           .concat(SizeInBits)
475                           .concat(AlignInBits)
476                           .concat(OffsetInBits)
477                           .concat(Flags)
478                           .get(VMContext),
479                       File.getFileNode(), getNonCompileUnitScope(File), Ty,
480                       PropertyNode};
481   return DIDerivedType(MDNode::get(VMContext, Elts));
484 DIObjCProperty
485 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
486                               StringRef GetterName, StringRef SetterName,
487                               unsigned PropertyAttributes, DIType Ty) {
488   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
489                           .concat(Name)
490                           .concat(LineNumber)
491                           .concat(GetterName)
492                           .concat(SetterName)
493                           .concat(PropertyAttributes)
494                           .get(VMContext),
495                       File, Ty};
496   return DIObjCProperty(MDNode::get(VMContext, Elts));
499 DITemplateTypeParameter
500 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
501                                        DIType Ty, MDNode *File, unsigned LineNo,
502                                        unsigned ColumnNo) {
503   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
504                           .concat(Name)
505                           .concat(LineNo)
506                           .concat(ColumnNo)
507                           .get(VMContext),
508                       DIScope(getNonCompileUnitScope(Context)).getRef(),
509                       Ty.getRef(), File};
510   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
513 static DITemplateValueParameter createTemplateValueParameterHelper(
514     LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
515     DIType Ty, Metadata *MD, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
516   Metadata *Elts[] = {
517       HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
518           VMContext),
519       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), MD, File};
520   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
523 DITemplateValueParameter
524 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
525                                         DIType Ty, Constant *Val, MDNode *File,
526                                         unsigned LineNo, unsigned ColumnNo) {
527   return createTemplateValueParameterHelper(
528       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
529       getConstantOrNull(Val), File, LineNo, ColumnNo);
532 DITemplateValueParameter
533 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
534                                            DIType Ty, StringRef Val,
535                                            MDNode *File, unsigned LineNo,
536                                            unsigned ColumnNo) {
537   return createTemplateValueParameterHelper(
538       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
539       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
542 DITemplateValueParameter
543 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
544                                        DIType Ty, DIArray Val,
545                                        MDNode *File, unsigned LineNo,
546                                        unsigned ColumnNo) {
547   return createTemplateValueParameterHelper(
548       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
549       Val, File, LineNo, ColumnNo);
552 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
553                                            DIFile File, unsigned LineNumber,
554                                            uint64_t SizeInBits,
555                                            uint64_t AlignInBits,
556                                            uint64_t OffsetInBits,
557                                            unsigned Flags, DIType DerivedFrom,
558                                            DIArray Elements,
559                                            DIType VTableHolder,
560                                            MDNode *TemplateParams,
561                                            StringRef UniqueIdentifier) {
562   assert((!Context || Context.isScope() || Context.isType()) &&
563          "createClassType should be called with a valid Context");
564   // TAG_class_type is encoded in DICompositeType format.
565   Metadata *Elts[] = {
566       HeaderBuilder::get(dwarf::DW_TAG_class_type)
567           .concat(Name)
568           .concat(LineNumber)
569           .concat(SizeInBits)
570           .concat(AlignInBits)
571           .concat(OffsetInBits)
572           .concat(Flags)
573           .concat(0)
574           .get(VMContext),
575       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
576       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
577       UniqueIdentifier.empty() ? nullptr
578                                : MDString::get(VMContext, UniqueIdentifier)};
579   DICompositeType R(MDNode::get(VMContext, Elts));
580   assert(R.isCompositeType() &&
581          "createClassType should return a DICompositeType");
582   if (!UniqueIdentifier.empty())
583     retainType(R);
584   return R;
587 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
588                                             StringRef Name, DIFile File,
589                                             unsigned LineNumber,
590                                             uint64_t SizeInBits,
591                                             uint64_t AlignInBits,
592                                             unsigned Flags, DIType DerivedFrom,
593                                             DIArray Elements,
594                                             unsigned RunTimeLang,
595                                             DIType VTableHolder,
596                                             StringRef UniqueIdentifier) {
597  // TAG_structure_type is encoded in DICompositeType format.
598   Metadata *Elts[] = {
599       HeaderBuilder::get(dwarf::DW_TAG_structure_type)
600           .concat(Name)
601           .concat(LineNumber)
602           .concat(SizeInBits)
603           .concat(AlignInBits)
604           .concat(0)
605           .concat(Flags)
606           .concat(RunTimeLang)
607           .get(VMContext),
608       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
609       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
610       UniqueIdentifier.empty() ? nullptr
611                                : MDString::get(VMContext, UniqueIdentifier)};
612   DICompositeType R(MDNode::get(VMContext, Elts));
613   assert(R.isCompositeType() &&
614          "createStructType should return a DICompositeType");
615   if (!UniqueIdentifier.empty())
616     retainType(R);
617   return R;
620 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
621                                            DIFile File, unsigned LineNumber,
622                                            uint64_t SizeInBits,
623                                            uint64_t AlignInBits, unsigned Flags,
624                                            DIArray Elements,
625                                            unsigned RunTimeLang,
626                                            StringRef UniqueIdentifier) {
627   // TAG_union_type is encoded in DICompositeType format.
628   Metadata *Elts[] = {
629       HeaderBuilder::get(dwarf::DW_TAG_union_type)
630           .concat(Name)
631           .concat(LineNumber)
632           .concat(SizeInBits)
633           .concat(AlignInBits)
634           .concat(0) // Offset
635           .concat(Flags)
636           .concat(RunTimeLang)
637           .get(VMContext),
638       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
639       nullptr, Elements, nullptr, nullptr,
640       UniqueIdentifier.empty() ? nullptr
641                                : MDString::get(VMContext, UniqueIdentifier)};
642   DICompositeType R(MDNode::get(VMContext, Elts));
643   if (!UniqueIdentifier.empty())
644     retainType(R);
645   return R;
648 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
649                                                  DITypeArray ParameterTypes,
650                                                  unsigned Flags) {
651   // TAG_subroutine_type is encoded in DICompositeType format.
652   Metadata *Elts[] = {
653       HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
654           .concat(StringRef())
655           .concat(0)     // Line
656           .concat(0)     // Size
657           .concat(0)     // Align
658           .concat(0)     // Offset
659           .concat(Flags) // Flags
660           .concat(0)
661           .get(VMContext),
662       nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
663       nullptr // Type Identifer
664   };
665   return DISubroutineType(MDNode::get(VMContext, Elts));
668 DICompositeType DIBuilder::createEnumerationType(
669     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
670     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
671     DIType UnderlyingType, StringRef UniqueIdentifier) {
672   // TAG_enumeration_type is encoded in DICompositeType format.
673   Metadata *Elts[] = {
674       HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
675           .concat(Name)
676           .concat(LineNumber)
677           .concat(SizeInBits)
678           .concat(AlignInBits)
679           .concat(0) // Offset
680           .concat(0) // Flags
681           .concat(0)
682           .get(VMContext),
683       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
684       UnderlyingType.getRef(), Elements, nullptr, nullptr,
685       UniqueIdentifier.empty() ? nullptr
686                                : MDString::get(VMContext, UniqueIdentifier)};
687   DICompositeType CTy(MDNode::get(VMContext, Elts));
688   AllEnumTypes.push_back(CTy);
689   if (!UniqueIdentifier.empty())
690     retainType(CTy);
691   return CTy;
694 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
695                                            DIType Ty, DIArray Subscripts) {
696   // TAG_array_type is encoded in DICompositeType format.
697   Metadata *Elts[] = {
698       HeaderBuilder::get(dwarf::DW_TAG_array_type)
699           .concat(StringRef())
700           .concat(0) // Line
701           .concat(Size)
702           .concat(AlignInBits)
703           .concat(0) // Offset
704           .concat(0) // Flags
705           .concat(0)
706           .get(VMContext),
707       nullptr, // Filename/Directory,
708       nullptr, // Unused
709       Ty.getRef(), Subscripts, nullptr, nullptr,
710       nullptr // Type Identifer
711   };
712   return DICompositeType(MDNode::get(VMContext, Elts));
715 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
716                                             DIType Ty, DIArray Subscripts) {
717   // A vector is an array type with the FlagVector flag applied.
718   Metadata *Elts[] = {
719       HeaderBuilder::get(dwarf::DW_TAG_array_type)
720           .concat("")
721           .concat(0) // Line
722           .concat(Size)
723           .concat(AlignInBits)
724           .concat(0) // Offset
725           .concat(DIType::FlagVector)
726           .concat(0)
727           .get(VMContext),
728       nullptr, // Filename/Directory,
729       nullptr, // Unused
730       Ty.getRef(), Subscripts, nullptr, nullptr,
731       nullptr // Type Identifer
732   };
733   return DICompositeType(MDNode::get(VMContext, Elts));
736 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
737                                           unsigned FlagsToSet) {
738   DIHeaderFieldIterator I(Header);
739   std::advance(I, 6);
741   unsigned Flags;
742   if (I->getAsInteger(0, Flags))
743     Flags = 0;
744   Flags |= FlagsToSet;
746   return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
747       I.getSuffix());
750 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
751                                   unsigned FlagsToSet) {
752   SmallVector<Metadata *, 9> Elts;
753   MDNode *N = Ty;
754   assert(N && "Unexpected input DIType!");
755   // Update header field.
756   Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
757   for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
758     Elts.push_back(N->getOperand(I));
760   return DIType(MDNode::get(Context, Elts));
763 DIType DIBuilder::createArtificialType(DIType Ty) {
764   if (Ty.isArtificial())
765     return Ty;
766   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
769 DIType DIBuilder::createObjectPointerType(DIType Ty) {
770   if (Ty.isObjectPointer())
771     return Ty;
772   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
773   return createTypeWithFlags(VMContext, Ty, Flags);
776 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
778 DIBasicType DIBuilder::createUnspecifiedParameter() {
779   return DIBasicType();
782 DICompositeType
783 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
784                              DIFile F, unsigned Line, unsigned RuntimeLang,
785                              uint64_t SizeInBits, uint64_t AlignInBits,
786                              StringRef UniqueIdentifier) {
787   // Create a temporary MDNode.
788   Metadata *Elts[] = {
789       HeaderBuilder::get(Tag)
790           .concat(Name)
791           .concat(Line)
792           .concat(SizeInBits)
793           .concat(AlignInBits)
794           .concat(0) // Offset
795           .concat(DIDescriptor::FlagFwdDecl)
796           .concat(RuntimeLang)
797           .get(VMContext),
798       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
799       DIArray(), nullptr,
800       nullptr, // TemplateParams
801       UniqueIdentifier.empty() ? nullptr
802                                : MDString::get(VMContext, UniqueIdentifier)};
803   MDNode *Node = MDNode::get(VMContext, Elts);
804   DICompositeType RetTy(Node);
805   assert(RetTy.isCompositeType() &&
806          "createForwardDecl result should be a DIType");
807   if (!UniqueIdentifier.empty())
808     retainType(RetTy);
809   return RetTy;
812 DICompositeType DIBuilder::createReplaceableForwardDecl(
813     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
814     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
815     StringRef UniqueIdentifier) {
816   // Create a temporary MDNode.
817   Metadata *Elts[] = {
818       HeaderBuilder::get(Tag)
819           .concat(Name)
820           .concat(Line)
821           .concat(SizeInBits)
822           .concat(AlignInBits)
823           .concat(0) // Offset
824           .concat(DIDescriptor::FlagFwdDecl)
825           .concat(RuntimeLang)
826           .get(VMContext),
827       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
828       DIArray(), nullptr,
829       nullptr, // TemplateParams
830       UniqueIdentifier.empty() ? nullptr
831                                : MDString::get(VMContext, UniqueIdentifier)};
832   DICompositeType RetTy(MDNode::getTemporary(VMContext, Elts));
833   assert(RetTy.isCompositeType() &&
834          "createReplaceableForwardDecl result should be a DIType");
835   if (!UniqueIdentifier.empty())
836     retainType(RetTy);
837   return RetTy;
840 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
841   return DIArray(MDNode::get(VMContext, Elements));
844 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
845   SmallVector<llvm::Metadata *, 16> Elts;
846   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
847     if (Elements[i] && isa<MDNode>(Elements[i]))
848       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
849     else
850       Elts.push_back(Elements[i]);
851   }
852   return DITypeArray(MDNode::get(VMContext, Elts));
855 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
856   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
857                           .concat(Lo)
858                           .concat(Count)
859                           .get(VMContext)};
861   return DISubrange(MDNode::get(VMContext, Elts));
864 static DIGlobalVariable createGlobalVariableHelper(
865     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
866     StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
867     bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
868     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
870   MDNode *TheCtx = getNonCompileUnitScope(Context);
871   if (DIScope(TheCtx).isCompositeType()) {
872     assert(!DICompositeType(TheCtx).getIdentifier() &&
873            "Context of a global variable should not be a type with identifier");
874   }
876   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
877                           .concat(Name)
878                           .concat(Name)
879                           .concat(LinkageName)
880                           .concat(LineNumber)
881                           .concat(isLocalToUnit)
882                           .concat(isDefinition)
883                           .get(VMContext),
884                       TheCtx, F, Ty, getConstantOrNull(Val),
885                       DIDescriptor(Decl)};
887   return DIGlobalVariable(CreateFunc(Elts));
890 DIGlobalVariable DIBuilder::createGlobalVariable(
891     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
892     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
893     MDNode *Decl) {
894   return createGlobalVariableHelper(
895       VMContext, Context, Name, LinkageName, F, LineNumber, Ty, isLocalToUnit,
896       Val, Decl, true, [&](ArrayRef<Metadata *> Elts) -> MDNode *{
897         MDNode *Node = MDNode::get(VMContext, Elts);
898         AllGVs.push_back(Node);
899         return Node;
900       });
903 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
904     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
905     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
906     MDNode *Decl) {
907   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
908                                     LineNumber, Ty, isLocalToUnit, Val, Decl,
909                                     false, [&](ArrayRef<Metadata *> Elts) {
910     return MDNode::getTemporary(VMContext, Elts);
911   });
914 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
915                                           StringRef Name, DIFile File,
916                                           unsigned LineNo, DITypeRef Ty,
917                                           bool AlwaysPreserve, unsigned Flags,
918                                           unsigned ArgNo) {
919   DIDescriptor Context(getNonCompileUnitScope(Scope));
920   assert((!Context || Context.isScope()) &&
921          "createLocalVariable should be called with a valid Context");
922   Metadata *Elts[] = {HeaderBuilder::get(Tag)
923                           .concat(Name)
924                           .concat(LineNo | (ArgNo << 24))
925                           .concat(Flags)
926                           .get(VMContext),
927                       getNonCompileUnitScope(Scope), File, Ty};
928   MDNode *Node = MDNode::get(VMContext, Elts);
929   if (AlwaysPreserve) {
930     // The optimizer may remove local variable. If there is an interest
931     // to preserve variable info in such situation then stash it in a
932     // named mdnode.
933     DISubprogram Fn(getDISubprogram(Scope));
934     assert(Fn && "Missing subprogram for local variable");
935     PreservedVariables[Fn].emplace_back(Node);
936   }
937   DIVariable RetVar(Node);
938   assert(RetVar.isVariable() &&
939          "createLocalVariable should return a valid DIVariable");
940   return RetVar;
943 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
944   auto Header = HeaderBuilder::get(DW_TAG_expression);
945   for (int64_t I : Addr)
946     Header.concat(I);
947   Metadata *Elts[] = {Header.get(VMContext)};
948   return DIExpression(MDNode::get(VMContext, Elts));
951 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
952                                               unsigned SizeInBytes) {
953   int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
954   return createExpression(Addr);
957 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
958                                        StringRef LinkageName, DIFile File,
959                                        unsigned LineNo, DICompositeType Ty,
960                                        bool isLocalToUnit, bool isDefinition,
961                                        unsigned ScopeLine, unsigned Flags,
962                                        bool isOptimized, Function *Fn,
963                                        MDNode *TParams, MDNode *Decl) {
964   // dragonegg does not generate identifier for types, so using an empty map
965   // to resolve the context should be fine.
966   DITypeIdentifierMap EmptyMap;
967   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
968                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
969                         Flags, isOptimized, Fn, TParams, Decl);
972 static DISubprogram createFunctionHelper(
973     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
974     StringRef LinkageName, DIFile File, unsigned LineNo, DICompositeType Ty,
975     bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags,
976     bool isOptimized, Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
977     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
978   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
979          "function types should be subroutines");
980   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
981                           .concat(Name)
982                           .concat(Name)
983                           .concat(LinkageName)
984                           .concat(LineNo)
985                           .concat(isLocalToUnit)
986                           .concat(isDefinition)
987                           .concat(0)
988                           .concat(0)
989                           .concat(Flags)
990                           .concat(isOptimized)
991                           .concat(ScopeLine)
992                           .get(VMContext),
993                       File.getFileNode(),
994                       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
995                       nullptr, getConstantOrNull(Fn), TParams, Decl, Vars};
997   DISubprogram S(CreateFunc(Elts));
998   assert(S.isSubprogram() &&
999          "createFunction should return a valid DISubprogram");
1000   return S;
1004 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1005                                        StringRef LinkageName, DIFile File,
1006                                        unsigned LineNo, DICompositeType Ty,
1007                                        bool isLocalToUnit, bool isDefinition,
1008                                        unsigned ScopeLine, unsigned Flags,
1009                                        bool isOptimized, Function *Fn,
1010                                        MDNode *TParams, MDNode *Decl) {
1011   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1012                               LineNo, Ty, isLocalToUnit, isDefinition,
1013                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1014                               MDNode::getTemporary(VMContext, None),
1015                               [&](ArrayRef<Metadata *> Elts) -> MDNode *{
1016     MDNode *Node = MDNode::get(VMContext, Elts);
1017     // Create a named metadata so that we
1018     // do not lose this mdnode.
1019     if (isDefinition)
1020       AllSubprograms.push_back(Node);
1021     return Node;
1022   });
1025 DISubprogram
1026 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1027                                      StringRef LinkageName, DIFile File,
1028                                      unsigned LineNo, DICompositeType Ty,
1029                                      bool isLocalToUnit, bool isDefinition,
1030                                      unsigned ScopeLine, unsigned Flags,
1031                                      bool isOptimized, Function *Fn,
1032                                      MDNode *TParams, MDNode *Decl) {
1033   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1034                               LineNo, Ty, isLocalToUnit, isDefinition,
1035                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1036                               nullptr, [&](ArrayRef<Metadata *> Elts) {
1037     return MDNode::getTemporary(VMContext, Elts);
1038   });
1041 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1042                                      StringRef LinkageName, DIFile F,
1043                                      unsigned LineNo, DICompositeType Ty,
1044                                      bool isLocalToUnit, bool isDefinition,
1045                                      unsigned VK, unsigned VIndex,
1046                                      DIType VTableHolder, unsigned Flags,
1047                                      bool isOptimized, Function *Fn,
1048                                      MDNode *TParam) {
1049   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1050          "function types should be subroutines");
1051   assert(getNonCompileUnitScope(Context) &&
1052          "Methods should have both a Context and a context that isn't "
1053          "the compile unit.");
1054   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1055                           .concat(Name)
1056                           .concat(Name)
1057                           .concat(LinkageName)
1058                           .concat(LineNo)
1059                           .concat(isLocalToUnit)
1060                           .concat(isDefinition)
1061                           .concat(VK)
1062                           .concat(VIndex)
1063                           .concat(Flags)
1064                           .concat(isOptimized)
1065                           .concat(LineNo)
1066                           // FIXME: Do we want to use different scope/lines?
1067                           .get(VMContext),
1068                       F.getFileNode(), DIScope(Context).getRef(), Ty,
1069                       VTableHolder.getRef(), getConstantOrNull(Fn), TParam,
1070                       nullptr, nullptr};
1071   MDNode *Node = MDNode::get(VMContext, Elts);
1072   if (isDefinition)
1073     AllSubprograms.push_back(Node);
1074   DISubprogram S(Node);
1075   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1076   return S;
1079 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1080                                        DIFile File, unsigned LineNo) {
1081   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1082                           .concat(Name)
1083                           .concat(LineNo)
1084                           .get(VMContext),
1085                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1086   DINameSpace R(MDNode::get(VMContext, Elts));
1087   assert(R.Verify() &&
1088          "createNameSpace should return a verifiable DINameSpace");
1089   return R;
1092 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1093                                                      DIFile File,
1094                                                      unsigned Discriminator) {
1095   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1096                           .concat(Discriminator)
1097                           .get(VMContext),
1098                       File.getFileNode(), Scope};
1099   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1100   assert(
1101       R.Verify() &&
1102       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1103   return R;
1106 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1107                                              unsigned Line, unsigned Col) {
1108   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1109   // I believe the right way is to have a self-referential element in the node.
1110   // Also: why do we bother with line/column - they're not used and the
1111   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1112   // for uniquing, yet then we have this other solution (because line/col were
1113   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1115   // Defeat MDNode uniquing for lexical blocks by using unique id.
1116   static unsigned int unique_id = 0;
1117   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1118                           .concat(Line)
1119                           .concat(Col)
1120                           .concat(unique_id++)
1121                           .get(VMContext),
1122                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1123   DILexicalBlock R(MDNode::get(VMContext, Elts));
1124   assert(R.Verify() &&
1125          "createLexicalBlock should return a verifiable DILexicalBlock");
1126   return R;
1129 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
1130   assert(V && "no value passed to dbg intrinsic");
1131   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
1134 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1135                                       DIExpression Expr,
1136                                       Instruction *InsertBefore) {
1137   assert(VarInfo.isVariable() &&
1138          "empty or invalid DIVariable passed to dbg.declare");
1139   if (!DeclareFn)
1140     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1142   trackIfUnresolved(VarInfo);
1143   trackIfUnresolved(Expr);
1144   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1145                    MetadataAsValue::get(VMContext, VarInfo),
1146                    MetadataAsValue::get(VMContext, Expr)};
1147   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1150 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1151                                       DIExpression Expr,
1152                                       BasicBlock *InsertAtEnd) {
1153   assert(VarInfo.isVariable() &&
1154          "empty or invalid DIVariable passed to dbg.declare");
1155   if (!DeclareFn)
1156     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1158   trackIfUnresolved(VarInfo);
1159   trackIfUnresolved(Expr);
1160   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1161                    MetadataAsValue::get(VMContext, VarInfo),
1162                    MetadataAsValue::get(VMContext, Expr)};
1164   // If this block already has a terminator then insert this intrinsic
1165   // before the terminator.
1166   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1167     return CallInst::Create(DeclareFn, Args, "", T);
1168   else
1169     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1172 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1173                                                 DIVariable VarInfo,
1174                                                 DIExpression Expr,
1175                                                 Instruction *InsertBefore) {
1176   assert(V && "no value passed to dbg.value");
1177   assert(VarInfo.isVariable() &&
1178          "empty or invalid DIVariable passed to dbg.value");
1179   if (!ValueFn)
1180     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1182   trackIfUnresolved(VarInfo);
1183   trackIfUnresolved(Expr);
1184   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1185                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1186                    MetadataAsValue::get(VMContext, VarInfo),
1187                    MetadataAsValue::get(VMContext, Expr)};
1188   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1191 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1192                                                 DIVariable VarInfo,
1193                                                 DIExpression Expr,
1194                                                 BasicBlock *InsertAtEnd) {
1195   assert(V && "no value passed to dbg.value");
1196   assert(VarInfo.isVariable() &&
1197          "empty or invalid DIVariable passed to dbg.value");
1198   if (!ValueFn)
1199     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1201   trackIfUnresolved(VarInfo);
1202   trackIfUnresolved(Expr);
1203   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1204                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1205                    MetadataAsValue::get(VMContext, VarInfo),
1206                    MetadataAsValue::get(VMContext, Expr)};
1207   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1210 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
1211   T.setContainingType(VTableHolder);
1213   // If this didn't create a self-reference, just return.
1214   if (T != VTableHolder)
1215     return;
1217   // Look for unresolved operands.  T has dropped RAUW support and is already
1218   // marked resolved, orphaning any cycles underneath it.
1219   assert(T->isResolved() && "Expected self-reference to be resolved");
1220   for (const MDOperand &O : T->operands())
1221     if (auto *N = dyn_cast_or_null<MDNode>(O))
1222       trackIfUnresolved(N);
1225 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
1226                               DIArray TParams) {
1227   T.setArrays(Elements, TParams);
1229   // If T isn't resolved, there's no problem.
1230   if (!T->isResolved())
1231     return;
1233   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
1234   // arrays explicitly if they're unresolved, or else the cycles will be
1235   // orphaned.
1236   if (Elements)
1237     trackIfUnresolved(Elements);
1238   if (TParams)
1239     trackIfUnresolved(TParams);