1874d31e0a56c22527d4bfbbec190525ae6264fb
[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 DIBuilder::createMemberPointerType(DIType PointeeTy,
332                                                  DIType Base) {
333   // Pointer types are encoded in DIDerivedType format.
334   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
335                           .concat(StringRef())
336                           .concat(0) // Line
337                           .concat(0) // Size
338                           .concat(0) // Align
339                           .concat(0) // Offset
340                           .concat(0) // Flags
341                           .get(VMContext),
342                       nullptr, // Filename
343                       nullptr, // Unused
344                       PointeeTy.getRef(), Base.getRef()};
345   return DIDerivedType(MDNode::get(VMContext, Elts));
348 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
349   assert(RTy.isType() && "Unable to create reference type");
350   // References are encoded in DIDerivedType format.
351   Metadata *Elts[] = {HeaderBuilder::get(Tag)
352                           .concat(StringRef()) // Name
353                           .concat(0)           // Line
354                           .concat(0)           // Size
355                           .concat(0)           // Align
356                           .concat(0)           // Offset
357                           .concat(0)           // Flags
358                           .get(VMContext),
359                       nullptr, // Filename
360                       nullptr, // TheCU,
361                       RTy.getRef()};
362   return DIDerivedType(MDNode::get(VMContext, Elts));
365 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
366                                        unsigned LineNo, DIDescriptor Context) {
367   // typedefs are encoded in DIDerivedType format.
368   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
369                           .concat(Name)
370                           .concat(LineNo)
371                           .concat(0) // Size
372                           .concat(0) // Align
373                           .concat(0) // Offset
374                           .concat(0) // Flags
375                           .get(VMContext),
376                       File.getFileNode(),
377                       DIScope(getNonCompileUnitScope(Context)).getRef(),
378                       Ty.getRef()};
379   return DIDerivedType(MDNode::get(VMContext, Elts));
382 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
383   // typedefs are encoded in DIDerivedType format.
384   assert(Ty.isType() && "Invalid type!");
385   assert(FriendTy.isType() && "Invalid friend type!");
386   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
387                           .concat(StringRef()) // Name
388                           .concat(0)           // Line
389                           .concat(0)           // Size
390                           .concat(0)           // Align
391                           .concat(0)           // Offset
392                           .concat(0)           // Flags
393                           .get(VMContext),
394                       nullptr, Ty.getRef(), FriendTy.getRef()};
395   return DIDerivedType(MDNode::get(VMContext, Elts));
398 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
399                                            uint64_t BaseOffset,
400                                            unsigned Flags) {
401   assert(Ty.isType() && "Unable to create inheritance");
402   // TAG_inheritance is encoded in DIDerivedType format.
403   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
404                           .concat(StringRef()) // Name
405                           .concat(0)           // Line
406                           .concat(0)           // Size
407                           .concat(0)           // Align
408                           .concat(BaseOffset)
409                           .concat(Flags)
410                           .get(VMContext),
411                       nullptr, Ty.getRef(), BaseTy.getRef()};
412   return DIDerivedType(MDNode::get(VMContext, Elts));
415 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
416                                           DIFile File, unsigned LineNumber,
417                                           uint64_t SizeInBits,
418                                           uint64_t AlignInBits,
419                                           uint64_t OffsetInBits, unsigned Flags,
420                                           DIType Ty) {
421   // TAG_member is encoded in DIDerivedType format.
422   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
423                           .concat(Name)
424                           .concat(LineNumber)
425                           .concat(SizeInBits)
426                           .concat(AlignInBits)
427                           .concat(OffsetInBits)
428                           .concat(Flags)
429                           .get(VMContext),
430                       File.getFileNode(),
431                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
432                       Ty.getRef()};
433   return DIDerivedType(MDNode::get(VMContext, Elts));
436 static Metadata *getConstantOrNull(Constant *C) {
437   if (C)
438     return ConstantAsMetadata::get(C);
439   return nullptr;
442 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
443                                                 StringRef Name, DIFile File,
444                                                 unsigned LineNumber, DIType Ty,
445                                                 unsigned Flags,
446                                                 llvm::Constant *Val) {
447   // TAG_member is encoded in DIDerivedType format.
448   Flags |= DIDescriptor::FlagStaticMember;
449   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
450                           .concat(Name)
451                           .concat(LineNumber)
452                           .concat(0) // Size
453                           .concat(0) // Align
454                           .concat(0) // Offset
455                           .concat(Flags)
456                           .get(VMContext),
457                       File.getFileNode(),
458                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
459                       Ty.getRef(), getConstantOrNull(Val)};
460   return DIDerivedType(MDNode::get(VMContext, Elts));
463 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
464                                         unsigned LineNumber,
465                                         uint64_t SizeInBits,
466                                         uint64_t AlignInBits,
467                                         uint64_t OffsetInBits, unsigned Flags,
468                                         DIType Ty, MDNode *PropertyNode) {
469   // TAG_member is encoded in DIDerivedType format.
470   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
471                           .concat(Name)
472                           .concat(LineNumber)
473                           .concat(SizeInBits)
474                           .concat(AlignInBits)
475                           .concat(OffsetInBits)
476                           .concat(Flags)
477                           .get(VMContext),
478                       File.getFileNode(), getNonCompileUnitScope(File), Ty,
479                       PropertyNode};
480   return DIDerivedType(MDNode::get(VMContext, Elts));
483 DIObjCProperty
484 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
485                               StringRef GetterName, StringRef SetterName,
486                               unsigned PropertyAttributes, DIType Ty) {
487   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
488                           .concat(Name)
489                           .concat(LineNumber)
490                           .concat(GetterName)
491                           .concat(SetterName)
492                           .concat(PropertyAttributes)
493                           .get(VMContext),
494                       File, Ty};
495   return DIObjCProperty(MDNode::get(VMContext, Elts));
498 DITemplateTypeParameter
499 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
500                                        DIType Ty, MDNode *File, unsigned LineNo,
501                                        unsigned ColumnNo) {
502   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
503                           .concat(Name)
504                           .concat(LineNo)
505                           .concat(ColumnNo)
506                           .get(VMContext),
507                       DIScope(getNonCompileUnitScope(Context)).getRef(),
508                       Ty.getRef(), File};
509   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
512 static DITemplateValueParameter createTemplateValueParameterHelper(
513     LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
514     DIType Ty, Metadata *MD, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
515   Metadata *Elts[] = {
516       HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
517           VMContext),
518       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), MD, File};
519   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
522 DITemplateValueParameter
523 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
524                                         DIType Ty, Constant *Val, MDNode *File,
525                                         unsigned LineNo, unsigned ColumnNo) {
526   return createTemplateValueParameterHelper(
527       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
528       getConstantOrNull(Val), File, LineNo, ColumnNo);
531 DITemplateValueParameter
532 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
533                                            DIType Ty, StringRef Val,
534                                            MDNode *File, unsigned LineNo,
535                                            unsigned ColumnNo) {
536   return createTemplateValueParameterHelper(
537       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
538       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
541 DITemplateValueParameter
542 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
543                                        DIType Ty, DIArray Val,
544                                        MDNode *File, unsigned LineNo,
545                                        unsigned ColumnNo) {
546   return createTemplateValueParameterHelper(
547       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
548       Val, File, LineNo, ColumnNo);
551 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
552                                            DIFile File, unsigned LineNumber,
553                                            uint64_t SizeInBits,
554                                            uint64_t AlignInBits,
555                                            uint64_t OffsetInBits,
556                                            unsigned Flags, DIType DerivedFrom,
557                                            DIArray Elements,
558                                            DIType VTableHolder,
559                                            MDNode *TemplateParams,
560                                            StringRef UniqueIdentifier) {
561   assert((!Context || Context.isScope() || Context.isType()) &&
562          "createClassType should be called with a valid Context");
563   // TAG_class_type is encoded in DICompositeType format.
564   Metadata *Elts[] = {
565       HeaderBuilder::get(dwarf::DW_TAG_class_type)
566           .concat(Name)
567           .concat(LineNumber)
568           .concat(SizeInBits)
569           .concat(AlignInBits)
570           .concat(OffsetInBits)
571           .concat(Flags)
572           .concat(0)
573           .get(VMContext),
574       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
575       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
576       UniqueIdentifier.empty() ? nullptr
577                                : MDString::get(VMContext, UniqueIdentifier)};
578   DICompositeType R(MDNode::get(VMContext, Elts));
579   assert(R.isCompositeType() &&
580          "createClassType should return a DICompositeType");
581   if (!UniqueIdentifier.empty())
582     retainType(R);
583   return R;
586 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
587                                             StringRef Name, DIFile File,
588                                             unsigned LineNumber,
589                                             uint64_t SizeInBits,
590                                             uint64_t AlignInBits,
591                                             unsigned Flags, DIType DerivedFrom,
592                                             DIArray Elements,
593                                             unsigned RunTimeLang,
594                                             DIType VTableHolder,
595                                             StringRef UniqueIdentifier) {
596  // TAG_structure_type is encoded in DICompositeType format.
597   Metadata *Elts[] = {
598       HeaderBuilder::get(dwarf::DW_TAG_structure_type)
599           .concat(Name)
600           .concat(LineNumber)
601           .concat(SizeInBits)
602           .concat(AlignInBits)
603           .concat(0)
604           .concat(Flags)
605           .concat(RunTimeLang)
606           .get(VMContext),
607       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
608       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
609       UniqueIdentifier.empty() ? nullptr
610                                : MDString::get(VMContext, UniqueIdentifier)};
611   DICompositeType R(MDNode::get(VMContext, Elts));
612   assert(R.isCompositeType() &&
613          "createStructType should return a DICompositeType");
614   if (!UniqueIdentifier.empty())
615     retainType(R);
616   return R;
619 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
620                                            DIFile File, unsigned LineNumber,
621                                            uint64_t SizeInBits,
622                                            uint64_t AlignInBits, unsigned Flags,
623                                            DIArray Elements,
624                                            unsigned RunTimeLang,
625                                            StringRef UniqueIdentifier) {
626   // TAG_union_type is encoded in DICompositeType format.
627   Metadata *Elts[] = {
628       HeaderBuilder::get(dwarf::DW_TAG_union_type)
629           .concat(Name)
630           .concat(LineNumber)
631           .concat(SizeInBits)
632           .concat(AlignInBits)
633           .concat(0) // Offset
634           .concat(Flags)
635           .concat(RunTimeLang)
636           .get(VMContext),
637       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
638       nullptr, Elements, nullptr, nullptr,
639       UniqueIdentifier.empty() ? nullptr
640                                : MDString::get(VMContext, UniqueIdentifier)};
641   DICompositeType R(MDNode::get(VMContext, Elts));
642   if (!UniqueIdentifier.empty())
643     retainType(R);
644   return R;
647 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
648                                                  DITypeArray ParameterTypes,
649                                                  unsigned Flags) {
650   // TAG_subroutine_type is encoded in DICompositeType format.
651   Metadata *Elts[] = {
652       HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
653           .concat(StringRef())
654           .concat(0)     // Line
655           .concat(0)     // Size
656           .concat(0)     // Align
657           .concat(0)     // Offset
658           .concat(Flags) // Flags
659           .concat(0)
660           .get(VMContext),
661       nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
662       nullptr // Type Identifer
663   };
664   return DISubroutineType(MDNode::get(VMContext, Elts));
667 DICompositeType DIBuilder::createEnumerationType(
668     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
669     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
670     DIType UnderlyingType, StringRef UniqueIdentifier) {
671   // TAG_enumeration_type is encoded in DICompositeType format.
672   Metadata *Elts[] = {
673       HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
674           .concat(Name)
675           .concat(LineNumber)
676           .concat(SizeInBits)
677           .concat(AlignInBits)
678           .concat(0) // Offset
679           .concat(0) // Flags
680           .concat(0)
681           .get(VMContext),
682       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
683       UnderlyingType.getRef(), Elements, nullptr, nullptr,
684       UniqueIdentifier.empty() ? nullptr
685                                : MDString::get(VMContext, UniqueIdentifier)};
686   DICompositeType CTy(MDNode::get(VMContext, Elts));
687   AllEnumTypes.push_back(CTy);
688   if (!UniqueIdentifier.empty())
689     retainType(CTy);
690   return CTy;
693 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
694                                            DIType Ty, DIArray Subscripts) {
695   // TAG_array_type is encoded in DICompositeType format.
696   Metadata *Elts[] = {
697       HeaderBuilder::get(dwarf::DW_TAG_array_type)
698           .concat(StringRef())
699           .concat(0) // Line
700           .concat(Size)
701           .concat(AlignInBits)
702           .concat(0) // Offset
703           .concat(0) // Flags
704           .concat(0)
705           .get(VMContext),
706       nullptr, // Filename/Directory,
707       nullptr, // Unused
708       Ty.getRef(), Subscripts, nullptr, nullptr,
709       nullptr // Type Identifer
710   };
711   return DICompositeType(MDNode::get(VMContext, Elts));
714 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
715                                             DIType Ty, DIArray Subscripts) {
716   // A vector is an array type with the FlagVector flag applied.
717   Metadata *Elts[] = {
718       HeaderBuilder::get(dwarf::DW_TAG_array_type)
719           .concat("")
720           .concat(0) // Line
721           .concat(Size)
722           .concat(AlignInBits)
723           .concat(0) // Offset
724           .concat(DIType::FlagVector)
725           .concat(0)
726           .get(VMContext),
727       nullptr, // Filename/Directory,
728       nullptr, // Unused
729       Ty.getRef(), Subscripts, nullptr, nullptr,
730       nullptr // Type Identifer
731   };
732   return DICompositeType(MDNode::get(VMContext, Elts));
735 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
736                                           unsigned FlagsToSet) {
737   DIHeaderFieldIterator I(Header);
738   std::advance(I, 6);
740   unsigned Flags;
741   if (I->getAsInteger(0, Flags))
742     Flags = 0;
743   Flags |= FlagsToSet;
745   return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
746       I.getSuffix());
749 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
750                                   unsigned FlagsToSet) {
751   SmallVector<Metadata *, 9> Elts;
752   MDNode *N = Ty;
753   assert(N && "Unexpected input DIType!");
754   // Update header field.
755   Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
756   for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
757     Elts.push_back(N->getOperand(I));
759   return DIType(MDNode::get(Context, Elts));
762 DIType DIBuilder::createArtificialType(DIType Ty) {
763   if (Ty.isArtificial())
764     return Ty;
765   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
768 DIType DIBuilder::createObjectPointerType(DIType Ty) {
769   if (Ty.isObjectPointer())
770     return Ty;
771   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
772   return createTypeWithFlags(VMContext, Ty, Flags);
775 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
777 DIBasicType DIBuilder::createUnspecifiedParameter() {
778   return DIBasicType();
781 DICompositeType
782 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
783                              DIFile F, unsigned Line, unsigned RuntimeLang,
784                              uint64_t SizeInBits, uint64_t AlignInBits,
785                              StringRef UniqueIdentifier) {
786   // Create a temporary MDNode.
787   Metadata *Elts[] = {
788       HeaderBuilder::get(Tag)
789           .concat(Name)
790           .concat(Line)
791           .concat(SizeInBits)
792           .concat(AlignInBits)
793           .concat(0) // Offset
794           .concat(DIDescriptor::FlagFwdDecl)
795           .concat(RuntimeLang)
796           .get(VMContext),
797       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
798       DIArray(), nullptr,
799       nullptr, // TemplateParams
800       UniqueIdentifier.empty() ? nullptr
801                                : MDString::get(VMContext, UniqueIdentifier)};
802   MDNode *Node = MDNode::get(VMContext, Elts);
803   DICompositeType RetTy(Node);
804   assert(RetTy.isCompositeType() &&
805          "createForwardDecl result should be a DIType");
806   if (!UniqueIdentifier.empty())
807     retainType(RetTy);
808   return RetTy;
811 DICompositeType DIBuilder::createReplaceableForwardDecl(
812     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
813     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
814     StringRef UniqueIdentifier) {
815   // Create a temporary MDNode.
816   Metadata *Elts[] = {
817       HeaderBuilder::get(Tag)
818           .concat(Name)
819           .concat(Line)
820           .concat(SizeInBits)
821           .concat(AlignInBits)
822           .concat(0) // Offset
823           .concat(DIDescriptor::FlagFwdDecl)
824           .concat(RuntimeLang)
825           .get(VMContext),
826       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
827       DIArray(), nullptr,
828       nullptr, // TemplateParams
829       UniqueIdentifier.empty() ? nullptr
830                                : MDString::get(VMContext, UniqueIdentifier)};
831   DICompositeType RetTy(MDNode::getTemporary(VMContext, Elts));
832   assert(RetTy.isCompositeType() &&
833          "createReplaceableForwardDecl result should be a DIType");
834   if (!UniqueIdentifier.empty())
835     retainType(RetTy);
836   return RetTy;
839 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
840   return DIArray(MDNode::get(VMContext, Elements));
843 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
844   SmallVector<llvm::Metadata *, 16> Elts;
845   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
846     if (Elements[i] && isa<MDNode>(Elements[i]))
847       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
848     else
849       Elts.push_back(Elements[i]);
850   }
851   return DITypeArray(MDNode::get(VMContext, Elts));
854 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
855   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
856                           .concat(Lo)
857                           .concat(Count)
858                           .get(VMContext)};
860   return DISubrange(MDNode::get(VMContext, Elts));
863 static DIGlobalVariable createGlobalVariableHelper(
864     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
865     StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
866     bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
867     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
869   MDNode *TheCtx = getNonCompileUnitScope(Context);
870   if (DIScope(TheCtx).isCompositeType()) {
871     assert(!DICompositeType(TheCtx).getIdentifier() &&
872            "Context of a global variable should not be a type with identifier");
873   }
875   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
876                           .concat(Name)
877                           .concat(Name)
878                           .concat(LinkageName)
879                           .concat(LineNumber)
880                           .concat(isLocalToUnit)
881                           .concat(isDefinition)
882                           .get(VMContext),
883                       TheCtx, F, Ty, getConstantOrNull(Val),
884                       DIDescriptor(Decl)};
886   return DIGlobalVariable(CreateFunc(Elts));
889 DIGlobalVariable DIBuilder::createGlobalVariable(
890     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
891     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
892     MDNode *Decl) {
893   return createGlobalVariableHelper(
894       VMContext, Context, Name, LinkageName, F, LineNumber, Ty, isLocalToUnit,
895       Val, Decl, true, [&](ArrayRef<Metadata *> Elts) -> MDNode *{
896         MDNode *Node = MDNode::get(VMContext, Elts);
897         AllGVs.push_back(Node);
898         return Node;
899       });
902 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
903     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
904     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
905     MDNode *Decl) {
906   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
907                                     LineNumber, Ty, isLocalToUnit, Val, Decl,
908                                     false, [&](ArrayRef<Metadata *> Elts) {
909     return MDNode::getTemporary(VMContext, Elts);
910   });
913 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
914                                           StringRef Name, DIFile File,
915                                           unsigned LineNo, DITypeRef Ty,
916                                           bool AlwaysPreserve, unsigned Flags,
917                                           unsigned ArgNo) {
918   DIDescriptor Context(getNonCompileUnitScope(Scope));
919   assert((!Context || Context.isScope()) &&
920          "createLocalVariable should be called with a valid Context");
921   Metadata *Elts[] = {HeaderBuilder::get(Tag)
922                           .concat(Name)
923                           .concat(LineNo | (ArgNo << 24))
924                           .concat(Flags)
925                           .get(VMContext),
926                       getNonCompileUnitScope(Scope), File, Ty};
927   MDNode *Node = MDNode::get(VMContext, Elts);
928   if (AlwaysPreserve) {
929     // The optimizer may remove local variable. If there is an interest
930     // to preserve variable info in such situation then stash it in a
931     // named mdnode.
932     DISubprogram Fn(getDISubprogram(Scope));
933     assert(Fn && "Missing subprogram for local variable");
934     PreservedVariables[Fn].emplace_back(Node);
935   }
936   DIVariable RetVar(Node);
937   assert(RetVar.isVariable() &&
938          "createLocalVariable should return a valid DIVariable");
939   return RetVar;
942 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
943   auto Header = HeaderBuilder::get(DW_TAG_expression);
944   for (int64_t I : Addr)
945     Header.concat(I);
946   Metadata *Elts[] = {Header.get(VMContext)};
947   return DIExpression(MDNode::get(VMContext, Elts));
950 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
951                                               unsigned SizeInBytes) {
952   int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
953   return createExpression(Addr);
956 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
957                                        StringRef LinkageName, DIFile File,
958                                        unsigned LineNo, DICompositeType Ty,
959                                        bool isLocalToUnit, bool isDefinition,
960                                        unsigned ScopeLine, unsigned Flags,
961                                        bool isOptimized, Function *Fn,
962                                        MDNode *TParams, MDNode *Decl) {
963   // dragonegg does not generate identifier for types, so using an empty map
964   // to resolve the context should be fine.
965   DITypeIdentifierMap EmptyMap;
966   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
967                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
968                         Flags, isOptimized, Fn, TParams, Decl);
971 static DISubprogram createFunctionHelper(
972     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
973     StringRef LinkageName, DIFile File, unsigned LineNo, DICompositeType Ty,
974     bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags,
975     bool isOptimized, Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
976     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
977   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
978          "function types should be subroutines");
979   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
980                           .concat(Name)
981                           .concat(Name)
982                           .concat(LinkageName)
983                           .concat(LineNo)
984                           .concat(isLocalToUnit)
985                           .concat(isDefinition)
986                           .concat(0)
987                           .concat(0)
988                           .concat(Flags)
989                           .concat(isOptimized)
990                           .concat(ScopeLine)
991                           .get(VMContext),
992                       File.getFileNode(),
993                       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
994                       nullptr, getConstantOrNull(Fn), TParams, Decl, Vars};
996   DISubprogram S(CreateFunc(Elts));
997   assert(S.isSubprogram() &&
998          "createFunction should return a valid DISubprogram");
999   return S;
1003 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1004                                        StringRef LinkageName, DIFile File,
1005                                        unsigned LineNo, DICompositeType Ty,
1006                                        bool isLocalToUnit, bool isDefinition,
1007                                        unsigned ScopeLine, unsigned Flags,
1008                                        bool isOptimized, Function *Fn,
1009                                        MDNode *TParams, MDNode *Decl) {
1010   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1011                               LineNo, Ty, isLocalToUnit, isDefinition,
1012                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1013                               MDNode::getTemporary(VMContext, None),
1014                               [&](ArrayRef<Metadata *> Elts) -> MDNode *{
1015     MDNode *Node = MDNode::get(VMContext, Elts);
1016     // Create a named metadata so that we
1017     // do not lose this mdnode.
1018     if (isDefinition)
1019       AllSubprograms.push_back(Node);
1020     return Node;
1021   });
1024 DISubprogram
1025 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1026                                      StringRef LinkageName, DIFile File,
1027                                      unsigned LineNo, DICompositeType Ty,
1028                                      bool isLocalToUnit, bool isDefinition,
1029                                      unsigned ScopeLine, unsigned Flags,
1030                                      bool isOptimized, Function *Fn,
1031                                      MDNode *TParams, MDNode *Decl) {
1032   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1033                               LineNo, Ty, isLocalToUnit, isDefinition,
1034                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1035                               nullptr, [&](ArrayRef<Metadata *> Elts) {
1036     return MDNode::getTemporary(VMContext, Elts);
1037   });
1040 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1041                                      StringRef LinkageName, DIFile F,
1042                                      unsigned LineNo, DICompositeType Ty,
1043                                      bool isLocalToUnit, bool isDefinition,
1044                                      unsigned VK, unsigned VIndex,
1045                                      DIType VTableHolder, unsigned Flags,
1046                                      bool isOptimized, Function *Fn,
1047                                      MDNode *TParam) {
1048   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1049          "function types should be subroutines");
1050   assert(getNonCompileUnitScope(Context) &&
1051          "Methods should have both a Context and a context that isn't "
1052          "the compile unit.");
1053   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1054                           .concat(Name)
1055                           .concat(Name)
1056                           .concat(LinkageName)
1057                           .concat(LineNo)
1058                           .concat(isLocalToUnit)
1059                           .concat(isDefinition)
1060                           .concat(VK)
1061                           .concat(VIndex)
1062                           .concat(Flags)
1063                           .concat(isOptimized)
1064                           .concat(LineNo)
1065                           // FIXME: Do we want to use different scope/lines?
1066                           .get(VMContext),
1067                       F.getFileNode(), DIScope(Context).getRef(), Ty,
1068                       VTableHolder.getRef(), getConstantOrNull(Fn), TParam,
1069                       nullptr, nullptr};
1070   MDNode *Node = MDNode::get(VMContext, Elts);
1071   if (isDefinition)
1072     AllSubprograms.push_back(Node);
1073   DISubprogram S(Node);
1074   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1075   return S;
1078 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1079                                        DIFile File, unsigned LineNo) {
1080   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1081                           .concat(Name)
1082                           .concat(LineNo)
1083                           .get(VMContext),
1084                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1085   DINameSpace R(MDNode::get(VMContext, Elts));
1086   assert(R.Verify() &&
1087          "createNameSpace should return a verifiable DINameSpace");
1088   return R;
1091 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1092                                                      DIFile File,
1093                                                      unsigned Discriminator) {
1094   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1095                           .concat(Discriminator)
1096                           .get(VMContext),
1097                       File.getFileNode(), Scope};
1098   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1099   assert(
1100       R.Verify() &&
1101       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1102   return R;
1105 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1106                                              unsigned Line, unsigned Col) {
1107   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1108   // I believe the right way is to have a self-referential element in the node.
1109   // Also: why do we bother with line/column - they're not used and the
1110   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1111   // for uniquing, yet then we have this other solution (because line/col were
1112   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1114   // Defeat MDNode uniquing for lexical blocks by using unique id.
1115   static unsigned int unique_id = 0;
1116   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1117                           .concat(Line)
1118                           .concat(Col)
1119                           .concat(unique_id++)
1120                           .get(VMContext),
1121                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1122   DILexicalBlock R(MDNode::get(VMContext, Elts));
1123   assert(R.Verify() &&
1124          "createLexicalBlock should return a verifiable DILexicalBlock");
1125   return R;
1128 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
1129   assert(V && "no value passed to dbg intrinsic");
1130   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
1133 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1134                                       DIExpression Expr,
1135                                       Instruction *InsertBefore) {
1136   assert(VarInfo.isVariable() &&
1137          "empty or invalid DIVariable passed to dbg.declare");
1138   if (!DeclareFn)
1139     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1141   trackIfUnresolved(VarInfo);
1142   trackIfUnresolved(Expr);
1143   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1144                    MetadataAsValue::get(VMContext, VarInfo),
1145                    MetadataAsValue::get(VMContext, Expr)};
1146   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1149 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1150                                       DIExpression Expr,
1151                                       BasicBlock *InsertAtEnd) {
1152   assert(VarInfo.isVariable() &&
1153          "empty or invalid DIVariable passed to dbg.declare");
1154   if (!DeclareFn)
1155     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1157   trackIfUnresolved(VarInfo);
1158   trackIfUnresolved(Expr);
1159   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1160                    MetadataAsValue::get(VMContext, VarInfo),
1161                    MetadataAsValue::get(VMContext, Expr)};
1163   // If this block already has a terminator then insert this intrinsic
1164   // before the terminator.
1165   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1166     return CallInst::Create(DeclareFn, Args, "", T);
1167   else
1168     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1171 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1172                                                 DIVariable VarInfo,
1173                                                 DIExpression Expr,
1174                                                 Instruction *InsertBefore) {
1175   assert(V && "no value passed to dbg.value");
1176   assert(VarInfo.isVariable() &&
1177          "empty or invalid DIVariable passed to dbg.value");
1178   if (!ValueFn)
1179     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1181   trackIfUnresolved(VarInfo);
1182   trackIfUnresolved(Expr);
1183   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1184                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1185                    MetadataAsValue::get(VMContext, VarInfo),
1186                    MetadataAsValue::get(VMContext, Expr)};
1187   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1190 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1191                                                 DIVariable VarInfo,
1192                                                 DIExpression Expr,
1193                                                 BasicBlock *InsertAtEnd) {
1194   assert(V && "no value passed to dbg.value");
1195   assert(VarInfo.isVariable() &&
1196          "empty or invalid DIVariable passed to dbg.value");
1197   if (!ValueFn)
1198     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1200   trackIfUnresolved(VarInfo);
1201   trackIfUnresolved(Expr);
1202   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1203                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1204                    MetadataAsValue::get(VMContext, VarInfo),
1205                    MetadataAsValue::get(VMContext, Expr)};
1206   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1209 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
1210   T.setContainingType(VTableHolder);
1212   // If this didn't create a self-reference, just return.
1213   if (T != VTableHolder)
1214     return;
1216   // Look for unresolved operands.  T has dropped RAUW support and is already
1217   // marked resolved, orphaning any cycles underneath it.
1218   assert(T->isResolved() && "Expected self-reference to be resolved");
1219   for (const MDOperand &O : T->operands())
1220     if (auto *N = dyn_cast_or_null<MDNode>(O))
1221       trackIfUnresolved(N);
1224 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
1225                               DIArray TParams) {
1226   T.setArrays(Elements, TParams);
1228   // If T isn't resolved, there's no problem.
1229   if (!T->isResolved())
1230     return;
1232   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
1233   // arrays explicitly if they're unresolved, or else the cycles will be
1234   // orphaned.
1235   if (Elements)
1236     trackIfUnresolved(Elements);
1237   if (TParams)
1238     trackIfUnresolved(TParams);