1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the DIBuilder.
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"
24 using namespace llvm::dwarf;
28 SmallVector<char, 256> Chars;
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) {
37 Twine(X).toVector(Chars);
41 MDString *get(LLVMContext &Context) const {
42 return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
45 static HeaderBuilder get(unsigned Tag) {
46 return HeaderBuilder("0x" + Twine::utohexstr(Tag));
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) {
59 (isa<MDNodeFwdDecl>(N) || !cast<UniquableMDNode>(N)->isResolved());
62 void DIBuilder::trackIfUnresolved(MDNode *N) {
63 if (!AllowUnresolvedNodes) {
64 assert(!isUnresolved(N) && "Cannot handle unresolved nodes");
68 UnresolvedNodes.emplace_back(N);
72 void DIBuilder::finalize() {
73 DIArray Enums = getOrCreateArray(AllEnumTypes);
74 DIType(TempEnumTypes).replaceAllUsesWith(Enums);
76 SmallVector<Metadata *, 16> RetainValues;
77 // Declarations and definitions of the same type may be retained. Some
78 // clients RAUW these pairs, leaving duplicates in the retained types
79 // list. Use a set to remove the duplicates while we transform the
80 // TrackingVHs back into Values.
81 SmallPtrSet<Metadata *, 16> RetainSet;
82 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
83 if (RetainSet.insert(AllRetainTypes[I]).second)
84 RetainValues.push_back(AllRetainTypes[I]);
85 DIArray RetainTypes = getOrCreateArray(RetainValues);
86 DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
88 DIArray SPs = getOrCreateArray(AllSubprograms);
89 DIType(TempSubprograms).replaceAllUsesWith(SPs);
90 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
91 DISubprogram SP(SPs.getElement(i));
92 if (MDNode *Temp = SP.getVariablesNodes()) {
93 SmallVector<Metadata *, 4> Variables;
94 for (Metadata *V : PreservedVariables.lookup(SP))
95 Variables.push_back(V);
96 DIArray AV = getOrCreateArray(Variables);
97 DIType(Temp).replaceAllUsesWith(AV);
101 DIArray GVs = getOrCreateArray(AllGVs);
102 DIType(TempGVs).replaceAllUsesWith(GVs);
104 SmallVector<Metadata *, 16> RetainValuesI;
105 for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
106 RetainValuesI.push_back(AllImportedModules[I]);
107 DIArray IMs = getOrCreateArray(RetainValuesI);
108 DIType(TempImportedModules).replaceAllUsesWith(IMs);
110 // Now that all temp nodes have been replaced or deleted, resolve remaining
112 for (const auto &N : UnresolvedNodes)
114 cast<UniquableMDNode>(N)->resolveCycles();
115 UnresolvedNodes.clear();
117 // Can't handle unresolved nodes anymore.
118 AllowUnresolvedNodes = false;
121 /// If N is compile unit return NULL otherwise return N.
122 static MDNode *getNonCompileUnitScope(MDNode *N) {
123 if (DIDescriptor(N).isCompileUnit())
128 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
129 StringRef Directory) {
130 assert(!Filename.empty() && "Unable to create file without name");
131 Metadata *Pair[] = {MDString::get(VMContext, Filename),
132 MDString::get(VMContext, Directory)};
133 return MDNode::get(VMContext, Pair);
136 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
138 StringRef Producer, bool isOptimized,
139 StringRef Flags, unsigned RunTimeVer,
141 DebugEmissionKind Kind,
142 bool EmitDebugInfo) {
144 assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
145 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
146 "Invalid Language tag");
147 assert(!Filename.empty() &&
148 "Unable to create compile unit without filename");
149 Metadata *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
150 TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
152 TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
154 TempSubprograms = MDNode::getTemporary(VMContext, TElts);
156 TempGVs = MDNode::getTemporary(VMContext, TElts);
158 TempImportedModules = MDNode::getTemporary(VMContext, TElts);
160 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
169 createFilePathPair(VMContext, Filename, Directory),
170 TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
171 TempImportedModules};
173 MDNode *CUNode = MDNode::get(VMContext, Elts);
175 // Create a named metadata so that it is easier to find cu in a module.
176 // Note that we only generate this when the caller wants to actually
177 // emit debug information. When we are only interested in tracking
178 // source line locations throughout the backend, we prevent codegen from
179 // emitting debug info in the final output by not generating llvm.dbg.cu.
181 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
182 NMD->addOperand(CUNode);
185 trackIfUnresolved(CUNode);
186 return DICompileUnit(CUNode);
189 static DIImportedEntity
190 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
191 Metadata *NS, unsigned Line, StringRef Name,
192 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
194 Metadata *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
196 R = MDNode::get(C, Elts);
197 DIImportedEntity M(R);
198 assert(M.Verify() && "Imported module should be valid");
199 AllImportedModules.emplace_back(M.get());
203 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
206 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
207 Context, NS, Line, StringRef(), AllImportedModules);
210 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
213 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
214 Context, NS, Line, StringRef(), AllImportedModules);
217 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
219 unsigned Line, StringRef Name) {
220 // Make sure to use the unique identifier based metadata reference for
221 // types that have one.
223 Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
224 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
225 Context, V, Line, Name,
229 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
230 DIImportedEntity Imp,
231 unsigned Line, StringRef Name) {
232 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
233 Context, Imp, Line, Name, AllImportedModules);
236 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
238 HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
239 createFilePathPair(VMContext, Filename, Directory)};
240 return DIFile(MDNode::get(VMContext, Elts));
243 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
244 assert(!Name.empty() && "Unable to create enumerator without name");
245 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_enumerator)
249 return DIEnumerator(MDNode::get(VMContext, Elts));
252 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
253 assert(!Name.empty() && "Unable to create type without name");
254 // Unspecified types are encoded in DIBasicType format. Line number, filename,
255 // size, alignment, offset and flags are always empty here.
257 HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
269 return DIBasicType(MDNode::get(VMContext, Elts));
272 DIBasicType DIBuilder::createNullPtrType() {
273 return createUnspecifiedType("decltype(nullptr)");
277 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
278 uint64_t AlignInBits, unsigned Encoding) {
279 assert(!Name.empty() && "Unable to create type without name");
280 // Basic types are encoded in DIBasicType format. Line number, filename,
281 // offset and flags are always empty here.
283 HeaderBuilder::get(dwarf::DW_TAG_base_type)
295 return DIBasicType(MDNode::get(VMContext, Elts));
298 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
299 // Qualified types are encoded in DIDerivedType format.
300 Metadata *Elts[] = {HeaderBuilder::get(Tag)
301 .concat(StringRef()) // Name
311 return DIDerivedType(MDNode::get(VMContext, Elts));
315 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
316 uint64_t AlignInBits, StringRef Name) {
317 // Pointer types are encoded in DIDerivedType format.
318 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
329 return DIDerivedType(MDNode::get(VMContext, Elts));
333 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
334 uint64_t SizeInBits, uint64_t AlignInBits) {
335 // Pointer types are encoded in DIDerivedType format.
336 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
339 .concat(SizeInBits) // Size
340 .concat(AlignInBits) // Align
346 PointeeTy.getRef(), Base.getRef()};
347 return DIDerivedType(MDNode::get(VMContext, Elts));
350 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
351 assert(RTy.isType() && "Unable to create reference type");
352 // References are encoded in DIDerivedType format.
353 Metadata *Elts[] = {HeaderBuilder::get(Tag)
354 .concat(StringRef()) // Name
364 return DIDerivedType(MDNode::get(VMContext, Elts));
367 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
368 unsigned LineNo, DIDescriptor Context) {
369 // typedefs are encoded in DIDerivedType format.
370 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
379 DIScope(getNonCompileUnitScope(Context)).getRef(),
381 return DIDerivedType(MDNode::get(VMContext, Elts));
384 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
385 // typedefs are encoded in DIDerivedType format.
386 assert(Ty.isType() && "Invalid type!");
387 assert(FriendTy.isType() && "Invalid friend type!");
388 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
389 .concat(StringRef()) // Name
396 nullptr, Ty.getRef(), FriendTy.getRef()};
397 return DIDerivedType(MDNode::get(VMContext, Elts));
400 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
403 assert(Ty.isType() && "Unable to create inheritance");
404 // TAG_inheritance is encoded in DIDerivedType format.
405 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
406 .concat(StringRef()) // Name
413 nullptr, Ty.getRef(), BaseTy.getRef()};
414 return DIDerivedType(MDNode::get(VMContext, Elts));
417 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
418 DIFile File, unsigned LineNumber,
420 uint64_t AlignInBits,
421 uint64_t OffsetInBits, unsigned Flags,
423 // TAG_member is encoded in DIDerivedType format.
424 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
429 .concat(OffsetInBits)
433 DIScope(getNonCompileUnitScope(Scope)).getRef(),
435 return DIDerivedType(MDNode::get(VMContext, Elts));
438 static Metadata *getConstantOrNull(Constant *C) {
440 return ConstantAsMetadata::get(C);
444 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
445 StringRef Name, DIFile File,
446 unsigned LineNumber, DIType Ty,
448 llvm::Constant *Val) {
449 // TAG_member is encoded in DIDerivedType format.
450 Flags |= DIDescriptor::FlagStaticMember;
451 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
460 DIScope(getNonCompileUnitScope(Scope)).getRef(),
461 Ty.getRef(), getConstantOrNull(Val)};
462 return DIDerivedType(MDNode::get(VMContext, Elts));
465 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
468 uint64_t AlignInBits,
469 uint64_t OffsetInBits, unsigned Flags,
470 DIType Ty, MDNode *PropertyNode) {
471 // TAG_member is encoded in DIDerivedType format.
472 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
477 .concat(OffsetInBits)
480 File.getFileNode(), getNonCompileUnitScope(File), Ty,
482 return DIDerivedType(MDNode::get(VMContext, Elts));
486 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
487 StringRef GetterName, StringRef SetterName,
488 unsigned PropertyAttributes, DIType Ty) {
489 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
494 .concat(PropertyAttributes)
497 return DIObjCProperty(MDNode::get(VMContext, Elts));
500 DITemplateTypeParameter
501 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
502 DIType Ty, MDNode *File, unsigned LineNo,
504 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
509 DIScope(getNonCompileUnitScope(Context)).getRef(),
511 return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
514 static DITemplateValueParameter createTemplateValueParameterHelper(
515 LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
516 DIType Ty, Metadata *MD, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
518 HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
520 DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), MD, File};
521 return DITemplateValueParameter(MDNode::get(VMContext, Elts));
524 DITemplateValueParameter
525 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
526 DIType Ty, Constant *Val, MDNode *File,
527 unsigned LineNo, unsigned ColumnNo) {
528 return createTemplateValueParameterHelper(
529 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
530 getConstantOrNull(Val), File, LineNo, ColumnNo);
533 DITemplateValueParameter
534 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
535 DIType Ty, StringRef Val,
536 MDNode *File, unsigned LineNo,
538 return createTemplateValueParameterHelper(
539 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
540 MDString::get(VMContext, Val), File, LineNo, ColumnNo);
543 DITemplateValueParameter
544 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
545 DIType Ty, DIArray Val,
546 MDNode *File, unsigned LineNo,
548 return createTemplateValueParameterHelper(
549 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
550 Val, File, LineNo, ColumnNo);
553 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
554 DIFile File, unsigned LineNumber,
556 uint64_t AlignInBits,
557 uint64_t OffsetInBits,
558 unsigned Flags, DIType DerivedFrom,
561 MDNode *TemplateParams,
562 StringRef UniqueIdentifier) {
563 assert((!Context || Context.isScope() || Context.isType()) &&
564 "createClassType should be called with a valid Context");
565 // TAG_class_type is encoded in DICompositeType format.
567 HeaderBuilder::get(dwarf::DW_TAG_class_type)
572 .concat(OffsetInBits)
576 File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
577 DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
578 UniqueIdentifier.empty() ? nullptr
579 : MDString::get(VMContext, UniqueIdentifier)};
580 DICompositeType R(MDNode::get(VMContext, Elts));
581 assert(R.isCompositeType() &&
582 "createClassType should return a DICompositeType");
583 if (!UniqueIdentifier.empty())
588 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
589 StringRef Name, DIFile File,
592 uint64_t AlignInBits,
593 unsigned Flags, DIType DerivedFrom,
595 unsigned RunTimeLang,
597 StringRef UniqueIdentifier) {
598 // TAG_structure_type is encoded in DICompositeType format.
600 HeaderBuilder::get(dwarf::DW_TAG_structure_type)
609 File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
610 DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
611 UniqueIdentifier.empty() ? nullptr
612 : MDString::get(VMContext, UniqueIdentifier)};
613 DICompositeType R(MDNode::get(VMContext, Elts));
614 assert(R.isCompositeType() &&
615 "createStructType should return a DICompositeType");
616 if (!UniqueIdentifier.empty())
621 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
622 DIFile File, unsigned LineNumber,
624 uint64_t AlignInBits, unsigned Flags,
626 unsigned RunTimeLang,
627 StringRef UniqueIdentifier) {
628 // TAG_union_type is encoded in DICompositeType format.
630 HeaderBuilder::get(dwarf::DW_TAG_union_type)
639 File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
640 nullptr, Elements, nullptr, nullptr,
641 UniqueIdentifier.empty() ? nullptr
642 : MDString::get(VMContext, UniqueIdentifier)};
643 DICompositeType R(MDNode::get(VMContext, Elts));
644 if (!UniqueIdentifier.empty())
649 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
650 DITypeArray ParameterTypes,
652 // TAG_subroutine_type is encoded in DICompositeType format.
654 HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
660 .concat(Flags) // Flags
663 nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
664 nullptr // Type Identifer
666 return DISubroutineType(MDNode::get(VMContext, Elts));
669 DICompositeType DIBuilder::createEnumerationType(
670 DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
671 uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
672 DIType UnderlyingType, StringRef UniqueIdentifier) {
673 // TAG_enumeration_type is encoded in DICompositeType format.
675 HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
684 File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
685 UnderlyingType.getRef(), Elements, nullptr, nullptr,
686 UniqueIdentifier.empty() ? nullptr
687 : MDString::get(VMContext, UniqueIdentifier)};
688 DICompositeType CTy(MDNode::get(VMContext, Elts));
689 AllEnumTypes.push_back(CTy);
690 if (!UniqueIdentifier.empty())
695 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
696 DIType Ty, DIArray Subscripts) {
697 // TAG_array_type is encoded in DICompositeType format.
699 HeaderBuilder::get(dwarf::DW_TAG_array_type)
708 nullptr, // Filename/Directory,
710 Ty.getRef(), Subscripts, nullptr, nullptr,
711 nullptr // Type Identifer
713 return DICompositeType(MDNode::get(VMContext, Elts));
716 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
717 DIType Ty, DIArray Subscripts) {
718 // A vector is an array type with the FlagVector flag applied.
720 HeaderBuilder::get(dwarf::DW_TAG_array_type)
726 .concat(DIType::FlagVector)
729 nullptr, // Filename/Directory,
731 Ty.getRef(), Subscripts, nullptr, nullptr,
732 nullptr // Type Identifer
734 return DICompositeType(MDNode::get(VMContext, Elts));
737 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
738 unsigned FlagsToSet) {
739 DIHeaderFieldIterator I(Header);
743 if (I->getAsInteger(0, Flags))
747 return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
751 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
752 unsigned FlagsToSet) {
753 SmallVector<Metadata *, 9> Elts;
755 assert(N && "Unexpected input DIType!");
756 // Update header field.
757 Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
758 for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
759 Elts.push_back(N->getOperand(I));
761 return DIType(MDNode::get(Context, Elts));
764 DIType DIBuilder::createArtificialType(DIType Ty) {
765 if (Ty.isArtificial())
767 return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
770 DIType DIBuilder::createObjectPointerType(DIType Ty) {
771 if (Ty.isObjectPointer())
773 unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
774 return createTypeWithFlags(VMContext, Ty, Flags);
777 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
779 DIBasicType DIBuilder::createUnspecifiedParameter() {
780 return DIBasicType();
784 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
785 DIFile F, unsigned Line, unsigned RuntimeLang,
786 uint64_t SizeInBits, uint64_t AlignInBits,
787 StringRef UniqueIdentifier) {
788 // Create a temporary MDNode.
790 HeaderBuilder::get(Tag)
796 .concat(DIDescriptor::FlagFwdDecl)
799 F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
801 nullptr, // TemplateParams
802 UniqueIdentifier.empty() ? nullptr
803 : MDString::get(VMContext, UniqueIdentifier)};
804 MDNode *Node = MDNode::get(VMContext, Elts);
805 DICompositeType RetTy(Node);
806 assert(RetTy.isCompositeType() &&
807 "createForwardDecl result should be a DIType");
808 if (!UniqueIdentifier.empty())
813 DICompositeType DIBuilder::createReplaceableForwardDecl(
814 unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
815 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
816 StringRef UniqueIdentifier) {
817 // Create a temporary MDNode.
819 HeaderBuilder::get(Tag)
825 .concat(DIDescriptor::FlagFwdDecl)
828 F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
830 nullptr, // TemplateParams
831 UniqueIdentifier.empty() ? nullptr
832 : MDString::get(VMContext, UniqueIdentifier)};
833 DICompositeType RetTy(MDNode::getTemporary(VMContext, Elts));
834 assert(RetTy.isCompositeType() &&
835 "createReplaceableForwardDecl result should be a DIType");
836 if (!UniqueIdentifier.empty())
841 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
842 return DIArray(MDNode::get(VMContext, Elements));
845 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
846 SmallVector<llvm::Metadata *, 16> Elts;
847 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
848 if (Elements[i] && isa<MDNode>(Elements[i]))
849 Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
851 Elts.push_back(Elements[i]);
853 return DITypeArray(MDNode::get(VMContext, Elts));
856 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
857 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
862 return DISubrange(MDNode::get(VMContext, Elts));
865 static DIGlobalVariable createGlobalVariableHelper(
866 LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
867 StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
868 bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
869 std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
871 MDNode *TheCtx = getNonCompileUnitScope(Context);
872 if (DIScope(TheCtx).isCompositeType()) {
873 assert(!DICompositeType(TheCtx).getIdentifier() &&
874 "Context of a global variable should not be a type with identifier");
877 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
882 .concat(isLocalToUnit)
883 .concat(isDefinition)
885 TheCtx, F, Ty, getConstantOrNull(Val),
888 return DIGlobalVariable(CreateFunc(Elts));
891 DIGlobalVariable DIBuilder::createGlobalVariable(
892 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
893 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
895 return createGlobalVariableHelper(
896 VMContext, Context, Name, LinkageName, F, LineNumber, Ty, isLocalToUnit,
897 Val, Decl, true, [&](ArrayRef<Metadata *> Elts) -> MDNode *{
898 MDNode *Node = MDNode::get(VMContext, Elts);
899 AllGVs.push_back(Node);
904 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
905 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
906 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
908 return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
909 LineNumber, Ty, isLocalToUnit, Val, Decl,
910 false, [&](ArrayRef<Metadata *> Elts) {
911 return MDNode::getTemporary(VMContext, Elts);
915 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
916 StringRef Name, DIFile File,
917 unsigned LineNo, DITypeRef Ty,
918 bool AlwaysPreserve, unsigned Flags,
920 DIDescriptor Context(getNonCompileUnitScope(Scope));
921 assert((!Context || Context.isScope()) &&
922 "createLocalVariable should be called with a valid Context");
923 Metadata *Elts[] = {HeaderBuilder::get(Tag)
925 .concat(LineNo | (ArgNo << 24))
928 getNonCompileUnitScope(Scope), File, Ty};
929 MDNode *Node = MDNode::get(VMContext, Elts);
930 if (AlwaysPreserve) {
931 // The optimizer may remove local variable. If there is an interest
932 // to preserve variable info in such situation then stash it in a
934 DISubprogram Fn(getDISubprogram(Scope));
935 assert(Fn && "Missing subprogram for local variable");
936 PreservedVariables[Fn].emplace_back(Node);
938 DIVariable RetVar(Node);
939 assert(RetVar.isVariable() &&
940 "createLocalVariable should return a valid DIVariable");
944 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
945 auto Header = HeaderBuilder::get(DW_TAG_expression);
946 for (int64_t I : Addr)
948 Metadata *Elts[] = {Header.get(VMContext)};
949 return DIExpression(MDNode::get(VMContext, Elts));
952 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
953 unsigned SizeInBytes) {
954 int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
955 return createExpression(Addr);
958 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
959 StringRef LinkageName, DIFile File,
960 unsigned LineNo, DICompositeType Ty,
961 bool isLocalToUnit, bool isDefinition,
962 unsigned ScopeLine, unsigned Flags,
963 bool isOptimized, Function *Fn,
964 MDNode *TParams, MDNode *Decl) {
965 // dragonegg does not generate identifier for types, so using an empty map
966 // to resolve the context should be fine.
967 DITypeIdentifierMap EmptyMap;
968 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
969 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
970 Flags, isOptimized, Fn, TParams, Decl);
973 static DISubprogram createFunctionHelper(
974 LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
975 StringRef LinkageName, DIFile File, unsigned LineNo, DICompositeType Ty,
976 bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags,
977 bool isOptimized, Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
978 std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
979 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
980 "function types should be subroutines");
981 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
986 .concat(isLocalToUnit)
987 .concat(isDefinition)
995 DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
996 nullptr, getConstantOrNull(Fn), TParams, Decl, Vars};
998 DISubprogram S(CreateFunc(Elts));
999 assert(S.isSubprogram() &&
1000 "createFunction should return a valid DISubprogram");
1005 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1006 StringRef LinkageName, DIFile File,
1007 unsigned LineNo, DICompositeType Ty,
1008 bool isLocalToUnit, bool isDefinition,
1009 unsigned ScopeLine, unsigned Flags,
1010 bool isOptimized, Function *Fn,
1011 MDNode *TParams, MDNode *Decl) {
1012 return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1013 LineNo, Ty, isLocalToUnit, isDefinition,
1014 ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1015 MDNode::getTemporary(VMContext, None),
1016 [&](ArrayRef<Metadata *> Elts) -> MDNode *{
1017 MDNode *Node = MDNode::get(VMContext, Elts);
1018 // Create a named metadata so that we
1019 // do not lose this mdnode.
1021 AllSubprograms.push_back(Node);
1027 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1028 StringRef LinkageName, DIFile File,
1029 unsigned LineNo, DICompositeType Ty,
1030 bool isLocalToUnit, bool isDefinition,
1031 unsigned ScopeLine, unsigned Flags,
1032 bool isOptimized, Function *Fn,
1033 MDNode *TParams, MDNode *Decl) {
1034 return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1035 LineNo, Ty, isLocalToUnit, isDefinition,
1036 ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1037 nullptr, [&](ArrayRef<Metadata *> Elts) {
1038 return MDNode::getTemporary(VMContext, Elts);
1042 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1043 StringRef LinkageName, DIFile F,
1044 unsigned LineNo, DICompositeType Ty,
1045 bool isLocalToUnit, bool isDefinition,
1046 unsigned VK, unsigned VIndex,
1047 DIType VTableHolder, unsigned Flags,
1048 bool isOptimized, Function *Fn,
1050 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1051 "function types should be subroutines");
1052 assert(getNonCompileUnitScope(Context) &&
1053 "Methods should have both a Context and a context that isn't "
1054 "the compile unit.");
1055 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1058 .concat(LinkageName)
1060 .concat(isLocalToUnit)
1061 .concat(isDefinition)
1065 .concat(isOptimized)
1067 // FIXME: Do we want to use different scope/lines?
1069 F.getFileNode(), DIScope(Context).getRef(), Ty,
1070 VTableHolder.getRef(), getConstantOrNull(Fn), TParam,
1072 MDNode *Node = MDNode::get(VMContext, Elts);
1074 AllSubprograms.push_back(Node);
1075 DISubprogram S(Node);
1076 assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1080 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1081 DIFile File, unsigned LineNo) {
1082 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1086 File.getFileNode(), getNonCompileUnitScope(Scope)};
1087 DINameSpace R(MDNode::get(VMContext, Elts));
1088 assert(R.Verify() &&
1089 "createNameSpace should return a verifiable DINameSpace");
1093 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1095 unsigned Discriminator) {
1096 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1097 .concat(Discriminator)
1099 File.getFileNode(), Scope};
1100 DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1103 "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1107 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1108 unsigned Line, unsigned Col) {
1109 // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1110 // I believe the right way is to have a self-referential element in the node.
1111 // Also: why do we bother with line/column - they're not used and the
1112 // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1113 // for uniquing, yet then we have this other solution (because line/col were
1114 // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1116 // Defeat MDNode uniquing for lexical blocks by using unique id.
1117 static unsigned int unique_id = 0;
1118 Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1121 .concat(unique_id++)
1123 File.getFileNode(), getNonCompileUnitScope(Scope)};
1124 DILexicalBlock R(MDNode::get(VMContext, Elts));
1125 assert(R.Verify() &&
1126 "createLexicalBlock should return a verifiable DILexicalBlock");
1130 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
1131 assert(V && "no value passed to dbg intrinsic");
1132 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
1135 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1137 Instruction *InsertBefore) {
1138 assert(VarInfo.isVariable() &&
1139 "empty or invalid DIVariable passed to dbg.declare");
1141 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1143 trackIfUnresolved(VarInfo);
1144 trackIfUnresolved(Expr);
1145 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1146 MetadataAsValue::get(VMContext, VarInfo),
1147 MetadataAsValue::get(VMContext, Expr)};
1148 return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1151 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1153 BasicBlock *InsertAtEnd) {
1154 assert(VarInfo.isVariable() &&
1155 "empty or invalid DIVariable passed to dbg.declare");
1157 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1159 trackIfUnresolved(VarInfo);
1160 trackIfUnresolved(Expr);
1161 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1162 MetadataAsValue::get(VMContext, VarInfo),
1163 MetadataAsValue::get(VMContext, Expr)};
1165 // If this block already has a terminator then insert this intrinsic
1166 // before the terminator.
1167 if (TerminatorInst *T = InsertAtEnd->getTerminator())
1168 return CallInst::Create(DeclareFn, Args, "", T);
1170 return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1173 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1176 Instruction *InsertBefore) {
1177 assert(V && "no value passed to dbg.value");
1178 assert(VarInfo.isVariable() &&
1179 "empty or invalid DIVariable passed to dbg.value");
1181 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1183 trackIfUnresolved(VarInfo);
1184 trackIfUnresolved(Expr);
1185 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1186 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1187 MetadataAsValue::get(VMContext, VarInfo),
1188 MetadataAsValue::get(VMContext, Expr)};
1189 return CallInst::Create(ValueFn, Args, "", InsertBefore);
1192 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1195 BasicBlock *InsertAtEnd) {
1196 assert(V && "no value passed to dbg.value");
1197 assert(VarInfo.isVariable() &&
1198 "empty or invalid DIVariable passed to dbg.value");
1200 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1202 trackIfUnresolved(VarInfo);
1203 trackIfUnresolved(Expr);
1204 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1205 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1206 MetadataAsValue::get(VMContext, VarInfo),
1207 MetadataAsValue::get(VMContext, Expr)};
1208 return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1211 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
1212 T.setContainingType(VTableHolder);
1214 // If this didn't create a self-reference, just return.
1215 if (T != VTableHolder)
1218 // Look for unresolved operands. T has dropped RAUW support and is already
1219 // marked resolved, orphaning any cycles underneath it.
1220 assert(T->isResolved() && "Expected self-reference to be resolved");
1221 for (const MDOperand &O : T->operands())
1222 if (auto *N = dyn_cast_or_null<MDNode>(O))
1223 trackIfUnresolved(N);
1226 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
1228 T.setArrays(Elements, TParams);
1230 // If T isn't resolved, there's no problem.
1231 if (!T->isResolved())
1234 // If "T" is resolved, it may be due to a self-reference cycle. Track the
1235 // arrays explicitly if they're unresolved, or else the cycles will be
1238 trackIfUnresolved(Elements);
1240 trackIfUnresolved(TParams);