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)
52 : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
53 TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
54 DeclareFn(nullptr), ValueFn(nullptr) {}
56 void DIBuilder::finalize() {
57 DIArray Enums = getOrCreateArray(AllEnumTypes);
58 DIType(TempEnumTypes).replaceAllUsesWith(Enums);
60 SmallVector<Value *, 16> RetainValues;
61 // Declarations and definitions of the same type may be retained. Some
62 // clients RAUW these pairs, leaving duplicates in the retained types
63 // list. Use a set to remove the duplicates while we transform the
64 // TrackingVHs back into Values.
65 SmallPtrSet<Value *, 16> RetainSet;
66 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
67 if (RetainSet.insert(AllRetainTypes[I]).second)
68 RetainValues.push_back(AllRetainTypes[I]);
69 DIArray RetainTypes = getOrCreateArray(RetainValues);
70 DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
72 DIArray SPs = getOrCreateArray(AllSubprograms);
73 DIType(TempSubprograms).replaceAllUsesWith(SPs);
74 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
75 DISubprogram SP(SPs.getElement(i));
76 if (MDNode *Temp = SP.getVariablesNodes()) {
77 SmallVector<Value *, 4> Variables;
78 for (Value *V : PreservedVariables.lookup(SP))
79 Variables.push_back(V);
80 DIArray AV = getOrCreateArray(Variables);
81 DIType(Temp).replaceAllUsesWith(AV);
85 DIArray GVs = getOrCreateArray(AllGVs);
86 DIType(TempGVs).replaceAllUsesWith(GVs);
88 SmallVector<Value *, 16> RetainValuesI;
89 for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
90 RetainValuesI.push_back(AllImportedModules[I]);
91 DIArray IMs = getOrCreateArray(RetainValuesI);
92 DIType(TempImportedModules).replaceAllUsesWith(IMs);
95 /// If N is compile unit return NULL otherwise return N.
96 static MDNode *getNonCompileUnitScope(MDNode *N) {
97 if (DIDescriptor(N).isCompileUnit())
102 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
103 StringRef Directory) {
104 assert(!Filename.empty() && "Unable to create file without name");
106 MDString::get(VMContext, Filename),
107 MDString::get(VMContext, Directory)
109 return MDNode::get(VMContext, Pair);
112 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
114 StringRef Producer, bool isOptimized,
115 StringRef Flags, unsigned RunTimeVer,
117 DebugEmissionKind Kind,
118 bool EmitDebugInfo) {
120 assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
121 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
122 "Invalid Language tag");
123 assert(!Filename.empty() &&
124 "Unable to create compile unit without filename");
125 Value *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
126 TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
128 TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
130 TempSubprograms = MDNode::getTemporary(VMContext, TElts);
132 TempGVs = MDNode::getTemporary(VMContext, TElts);
134 TempImportedModules = MDNode::getTemporary(VMContext, TElts);
136 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
145 createFilePathPair(VMContext, Filename, Directory),
146 TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
147 TempImportedModules};
149 MDNode *CUNode = MDNode::get(VMContext, Elts);
151 // Create a named metadata so that it is easier to find cu in a module.
152 // Note that we only generate this when the caller wants to actually
153 // emit debug information. When we are only interested in tracking
154 // source line locations throughout the backend, we prevent codegen from
155 // emitting debug info in the final output by not generating llvm.dbg.cu.
157 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
158 NMD->addOperand(CUNode);
161 return DICompileUnit(CUNode);
164 static DIImportedEntity
165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
166 Value *NS, unsigned Line, StringRef Name,
167 SmallVectorImpl<TrackingVH<MDNode>> &AllImportedModules) {
169 Value *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
171 R = MDNode::get(C, Elts);
172 DIImportedEntity M(R);
173 assert(M.Verify() && "Imported module should be valid");
174 AllImportedModules.push_back(TrackingVH<MDNode>(M));
178 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
181 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
182 Context, NS, Line, StringRef(), AllImportedModules);
185 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
188 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
189 Context, NS, Line, StringRef(), AllImportedModules);
192 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
194 unsigned Line, StringRef Name) {
195 // Make sure to use the unique identifier based metadata reference for
196 // types that have one.
197 Value *V = Decl.isType() ? static_cast<Value*>(DIType(Decl).getRef()) : Decl;
198 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
199 Context, V, Line, Name,
203 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
204 DIImportedEntity Imp,
205 unsigned Line, StringRef Name) {
206 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
207 Context, Imp, Line, Name, AllImportedModules);
210 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
211 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
212 createFilePathPair(VMContext, Filename, Directory)};
213 return DIFile(MDNode::get(VMContext, Elts));
216 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
217 assert(!Name.empty() && "Unable to create enumerator without name");
219 HeaderBuilder::get(dwarf::DW_TAG_enumerator).concat(Name).concat(Val).get(
221 return DIEnumerator(MDNode::get(VMContext, Elts));
224 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
225 assert(!Name.empty() && "Unable to create type without name");
226 // Unspecified types are encoded in DIBasicType format. Line number, filename,
227 // size, alignment, offset and flags are always empty here.
229 HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
241 return DIBasicType(MDNode::get(VMContext, Elts));
244 DIBasicType DIBuilder::createNullPtrType() {
245 return createUnspecifiedType("decltype(nullptr)");
249 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
250 uint64_t AlignInBits, unsigned Encoding) {
251 assert(!Name.empty() && "Unable to create type without name");
252 // Basic types are encoded in DIBasicType format. Line number, filename,
253 // offset and flags are always empty here.
255 HeaderBuilder::get(dwarf::DW_TAG_base_type)
267 return DIBasicType(MDNode::get(VMContext, Elts));
270 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
271 // Qualified types are encoded in DIDerivedType format.
272 Value *Elts[] = {HeaderBuilder::get(Tag)
273 .concat(StringRef()) // Name
283 return DIDerivedType(MDNode::get(VMContext, Elts));
287 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
288 uint64_t AlignInBits, StringRef Name) {
289 // Pointer types are encoded in DIDerivedType format.
290 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
301 return DIDerivedType(MDNode::get(VMContext, Elts));
304 DIDerivedType DIBuilder::createMemberPointerType(DIType PointeeTy,
306 // Pointer types are encoded in DIDerivedType format.
307 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
317 PointeeTy.getRef(), Base.getRef()};
318 return DIDerivedType(MDNode::get(VMContext, Elts));
321 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
322 assert(RTy.isType() && "Unable to create reference type");
323 // References are encoded in DIDerivedType format.
324 Value *Elts[] = {HeaderBuilder::get(Tag)
325 .concat(StringRef()) // Name
335 return DIDerivedType(MDNode::get(VMContext, Elts));
338 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
339 unsigned LineNo, DIDescriptor Context) {
340 // typedefs are encoded in DIDerivedType format.
341 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
350 DIScope(getNonCompileUnitScope(Context)).getRef(),
352 return DIDerivedType(MDNode::get(VMContext, Elts));
355 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
356 // typedefs are encoded in DIDerivedType format.
357 assert(Ty.isType() && "Invalid type!");
358 assert(FriendTy.isType() && "Invalid friend type!");
359 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
360 .concat(StringRef()) // Name
367 nullptr, Ty.getRef(), FriendTy.getRef()};
368 return DIDerivedType(MDNode::get(VMContext, Elts));
371 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
374 assert(Ty.isType() && "Unable to create inheritance");
375 // TAG_inheritance is encoded in DIDerivedType format.
376 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
377 .concat(StringRef()) // Name
384 nullptr, Ty.getRef(), BaseTy.getRef()};
385 return DIDerivedType(MDNode::get(VMContext, Elts));
388 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
389 DIFile File, unsigned LineNumber,
391 uint64_t AlignInBits,
392 uint64_t OffsetInBits, unsigned Flags,
394 // TAG_member is encoded in DIDerivedType format.
395 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
400 .concat(OffsetInBits)
404 DIScope(getNonCompileUnitScope(Scope)).getRef(),
406 return DIDerivedType(MDNode::get(VMContext, Elts));
409 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
410 StringRef Name, DIFile File,
411 unsigned LineNumber, DIType Ty,
413 llvm::Constant *Val) {
414 // TAG_member is encoded in DIDerivedType format.
415 Flags |= DIDescriptor::FlagStaticMember;
416 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
425 DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(),
427 return DIDerivedType(MDNode::get(VMContext, Elts));
430 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
433 uint64_t AlignInBits,
434 uint64_t OffsetInBits, unsigned Flags,
435 DIType Ty, MDNode *PropertyNode) {
436 // TAG_member is encoded in DIDerivedType format.
437 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
442 .concat(OffsetInBits)
445 File.getFileNode(), getNonCompileUnitScope(File), Ty,
447 return DIDerivedType(MDNode::get(VMContext, Elts));
451 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
452 StringRef GetterName, StringRef SetterName,
453 unsigned PropertyAttributes, DIType Ty) {
454 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
459 .concat(PropertyAttributes)
462 return DIObjCProperty(MDNode::get(VMContext, Elts));
465 DITemplateTypeParameter
466 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
467 DIType Ty, MDNode *File, unsigned LineNo,
469 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
474 DIScope(getNonCompileUnitScope(Context)).getRef(),
476 return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
479 static DITemplateValueParameter createTemplateValueParameterHelper(
480 LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
481 DIType Ty, Value *Val, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
483 HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
485 DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), Val,
487 return DITemplateValueParameter(MDNode::get(VMContext, Elts));
490 DITemplateValueParameter
491 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
492 DIType Ty, Constant *Val, MDNode *File,
493 unsigned LineNo, unsigned ColumnNo) {
494 return createTemplateValueParameterHelper(
495 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, Val,
496 File, LineNo, ColumnNo);
499 DITemplateValueParameter
500 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
501 DIType Ty, StringRef Val,
502 MDNode *File, unsigned LineNo,
504 return createTemplateValueParameterHelper(
505 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
506 MDString::get(VMContext, Val), File, LineNo, ColumnNo);
509 DITemplateValueParameter
510 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
511 DIType Ty, DIArray Val,
512 MDNode *File, unsigned LineNo,
514 return createTemplateValueParameterHelper(
515 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
516 Val, File, LineNo, ColumnNo);
519 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
520 DIFile File, unsigned LineNumber,
522 uint64_t AlignInBits,
523 uint64_t OffsetInBits,
524 unsigned Flags, DIType DerivedFrom,
527 MDNode *TemplateParams,
528 StringRef UniqueIdentifier) {
529 assert((!Context || Context.isScope() || Context.isType()) &&
530 "createClassType should be called with a valid Context");
531 // TAG_class_type is encoded in DICompositeType format.
533 HeaderBuilder::get(dwarf::DW_TAG_class_type)
538 .concat(OffsetInBits)
542 File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
543 DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
544 UniqueIdentifier.empty() ? nullptr
545 : MDString::get(VMContext, UniqueIdentifier)};
546 DICompositeType R(MDNode::get(VMContext, Elts));
547 assert(R.isCompositeType() &&
548 "createClassType should return a DICompositeType");
549 if (!UniqueIdentifier.empty())
554 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
555 StringRef Name, DIFile File,
558 uint64_t AlignInBits,
559 unsigned Flags, DIType DerivedFrom,
561 unsigned RunTimeLang,
563 StringRef UniqueIdentifier) {
564 // TAG_structure_type is encoded in DICompositeType format.
566 HeaderBuilder::get(dwarf::DW_TAG_structure_type)
575 File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
576 DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
577 UniqueIdentifier.empty() ? nullptr
578 : MDString::get(VMContext, UniqueIdentifier)};
579 DICompositeType R(MDNode::get(VMContext, Elts));
580 assert(R.isCompositeType() &&
581 "createStructType should return a DICompositeType");
582 if (!UniqueIdentifier.empty())
587 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
588 DIFile File, unsigned LineNumber,
590 uint64_t AlignInBits, unsigned Flags,
592 unsigned RunTimeLang,
593 StringRef UniqueIdentifier) {
594 // TAG_union_type is encoded in DICompositeType format.
596 HeaderBuilder::get(dwarf::DW_TAG_union_type)
605 File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
606 nullptr, Elements, nullptr, nullptr,
607 UniqueIdentifier.empty() ? nullptr
608 : MDString::get(VMContext, UniqueIdentifier)};
609 DICompositeType R(MDNode::get(VMContext, Elts));
610 if (!UniqueIdentifier.empty())
615 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
616 DITypeArray ParameterTypes,
618 // TAG_subroutine_type is encoded in DICompositeType format.
620 HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
626 .concat(Flags) // Flags
629 nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
630 nullptr // Type Identifer
632 return DISubroutineType(MDNode::get(VMContext, Elts));
635 DICompositeType DIBuilder::createEnumerationType(
636 DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
637 uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
638 DIType UnderlyingType, StringRef UniqueIdentifier) {
639 // TAG_enumeration_type is encoded in DICompositeType format.
641 HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
650 File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
651 UnderlyingType.getRef(), Elements, nullptr, nullptr,
652 UniqueIdentifier.empty() ? nullptr
653 : MDString::get(VMContext, UniqueIdentifier)};
654 DICompositeType CTy(MDNode::get(VMContext, Elts));
655 AllEnumTypes.push_back(CTy);
656 if (!UniqueIdentifier.empty())
661 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
662 DIType Ty, DIArray Subscripts) {
663 // TAG_array_type is encoded in DICompositeType format.
665 HeaderBuilder::get(dwarf::DW_TAG_array_type)
674 nullptr, // Filename/Directory,
676 Ty.getRef(), Subscripts, nullptr, nullptr,
677 nullptr // Type Identifer
679 return DICompositeType(MDNode::get(VMContext, Elts));
682 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
683 DIType Ty, DIArray Subscripts) {
684 // A vector is an array type with the FlagVector flag applied.
686 HeaderBuilder::get(dwarf::DW_TAG_array_type)
692 .concat(DIType::FlagVector)
695 nullptr, // Filename/Directory,
697 Ty.getRef(), Subscripts, nullptr, nullptr,
698 nullptr // Type Identifer
700 return DICompositeType(MDNode::get(VMContext, Elts));
703 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
704 unsigned FlagsToSet) {
705 DIHeaderFieldIterator I(Header);
709 if (I->getAsInteger(0, Flags))
713 return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
717 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
718 unsigned FlagsToSet) {
719 SmallVector<Value *, 9> Elts;
721 assert(N && "Unexpected input DIType!");
722 // Update header field.
723 Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
724 for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
725 Elts.push_back(N->getOperand(I));
727 return DIType(MDNode::get(Context, Elts));
730 DIType DIBuilder::createArtificialType(DIType Ty) {
731 if (Ty.isArtificial())
733 return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
736 DIType DIBuilder::createObjectPointerType(DIType Ty) {
737 if (Ty.isObjectPointer())
739 unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
740 return createTypeWithFlags(VMContext, Ty, Flags);
743 void DIBuilder::retainType(DIType T) {
744 AllRetainTypes.push_back(TrackingVH<MDNode>(T));
747 DIBasicType DIBuilder::createUnspecifiedParameter() {
748 return DIBasicType();
752 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
753 DIFile F, unsigned Line, unsigned RuntimeLang,
754 uint64_t SizeInBits, uint64_t AlignInBits,
755 StringRef UniqueIdentifier) {
756 // Create a temporary MDNode.
758 HeaderBuilder::get(Tag)
764 .concat(DIDescriptor::FlagFwdDecl)
767 F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
769 nullptr, // TemplateParams
770 UniqueIdentifier.empty() ? nullptr
771 : MDString::get(VMContext, UniqueIdentifier)};
772 MDNode *Node = MDNode::get(VMContext, Elts);
773 DICompositeType RetTy(Node);
774 assert(RetTy.isCompositeType() &&
775 "createForwardDecl result should be a DIType");
776 if (!UniqueIdentifier.empty())
781 DICompositeType DIBuilder::createReplaceableForwardDecl(
782 unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
783 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
784 StringRef UniqueIdentifier) {
785 // Create a temporary MDNode.
787 HeaderBuilder::get(Tag)
793 .concat(DIDescriptor::FlagFwdDecl)
796 F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
798 nullptr, // TemplateParams
799 UniqueIdentifier.empty() ? nullptr
800 : MDString::get(VMContext, UniqueIdentifier)};
801 MDNode *Node = MDNode::getTemporary(VMContext, Elts);
802 DICompositeType RetTy(Node);
803 assert(RetTy.isCompositeType() &&
804 "createReplaceableForwardDecl result should be a DIType");
805 if (!UniqueIdentifier.empty())
810 DIArray DIBuilder::getOrCreateArray(ArrayRef<Value *> Elements) {
811 return DIArray(MDNode::get(VMContext, Elements));
814 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Value *> Elements) {
815 SmallVector<llvm::Value *, 16> Elts;
816 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
817 if (Elements[i] && isa<MDNode>(Elements[i]))
818 Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
820 Elts.push_back(Elements[i]);
822 return DITypeArray(MDNode::get(VMContext, Elts));
825 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
826 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
831 return DISubrange(MDNode::get(VMContext, Elts));
834 static DIGlobalVariable createGlobalVariableHelper(
835 LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
836 StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
837 bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
838 std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
840 MDNode *TheCtx = getNonCompileUnitScope(Context);
841 if (DIScope(TheCtx).isCompositeType()) {
842 assert(!DICompositeType(TheCtx).getIdentifier() &&
843 "Context of a global variable should not be a type with identifier");
846 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
851 .concat(isLocalToUnit)
852 .concat(isDefinition)
857 return DIGlobalVariable(CreateFunc(Elts));
860 DIGlobalVariable DIBuilder::createGlobalVariable(
861 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
862 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
864 return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
865 LineNumber, Ty, isLocalToUnit, Val, Decl, true,
866 [&] (ArrayRef<Value *> Elts) -> MDNode * {
867 MDNode *Node = MDNode::get(VMContext, Elts);
868 AllGVs.push_back(Node);
873 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
874 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
875 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
877 return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
878 LineNumber, Ty, isLocalToUnit, Val, Decl, false,
879 [&] (ArrayRef<Value *> Elts) {
880 return MDNode::getTemporary(VMContext, Elts);
884 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
885 StringRef Name, DIFile File,
886 unsigned LineNo, DITypeRef Ty,
887 bool AlwaysPreserve, unsigned Flags,
889 DIDescriptor Context(getNonCompileUnitScope(Scope));
890 assert((!Context || Context.isScope()) &&
891 "createLocalVariable should be called with a valid Context");
892 Value *Elts[] = {HeaderBuilder::get(Tag)
894 .concat(LineNo | (ArgNo << 24))
897 getNonCompileUnitScope(Scope), File, Ty};
898 MDNode *Node = MDNode::get(VMContext, Elts);
899 if (AlwaysPreserve) {
900 // The optimizer may remove local variable. If there is an interest
901 // to preserve variable info in such situation then stash it in a
903 DISubprogram Fn(getDISubprogram(Scope));
904 assert(Fn && "Missing subprogram for local variable");
905 PreservedVariables[Fn].push_back(Node);
907 DIVariable RetVar(Node);
908 assert(RetVar.isVariable() &&
909 "createLocalVariable should return a valid DIVariable");
913 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
914 auto Header = HeaderBuilder::get(DW_TAG_expression);
915 for (int64_t I : Addr)
917 Value *Elts[] = {Header.get(VMContext)};
918 return DIExpression(MDNode::get(VMContext, Elts));
921 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
922 unsigned SizeInBytes) {
923 int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
924 return createExpression(Addr);
927 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
928 StringRef LinkageName, DIFile File,
929 unsigned LineNo, DICompositeType Ty,
930 bool isLocalToUnit, bool isDefinition,
931 unsigned ScopeLine, unsigned Flags,
932 bool isOptimized, Function *Fn,
933 MDNode *TParams, MDNode *Decl) {
934 // dragonegg does not generate identifier for types, so using an empty map
935 // to resolve the context should be fine.
936 DITypeIdentifierMap EmptyMap;
937 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
938 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
939 Flags, isOptimized, Fn, TParams, Decl);
943 createFunctionHelper(LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
944 StringRef LinkageName, DIFile File, unsigned LineNo,
945 DICompositeType Ty, bool isLocalToUnit, bool isDefinition,
946 unsigned ScopeLine, unsigned Flags, bool isOptimized,
947 Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
948 std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
949 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
950 "function types should be subroutines");
952 HeaderBuilder::get(dwarf::DW_TAG_subprogram)
957 .concat(isLocalToUnit)
958 .concat(isDefinition)
965 File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
966 nullptr, Fn, TParams, Decl, Vars};
968 DISubprogram S(CreateFunc(Elts));
969 assert(S.isSubprogram() &&
970 "createFunction should return a valid DISubprogram");
975 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
976 StringRef LinkageName, DIFile File,
977 unsigned LineNo, DICompositeType Ty,
978 bool isLocalToUnit, bool isDefinition,
979 unsigned ScopeLine, unsigned Flags,
980 bool isOptimized, Function *Fn,
981 MDNode *TParams, MDNode *Decl) {
982 return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
983 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
984 Flags, isOptimized, Fn, TParams, Decl,
985 MDNode::getTemporary(VMContext, None),
986 [&] (ArrayRef<Value *> Elts) -> MDNode *{
987 MDNode *Node = MDNode::get(VMContext, Elts);
988 // Create a named metadata so that we
989 // do not lose this mdnode.
991 AllSubprograms.push_back(Node);
997 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
998 StringRef LinkageName, DIFile File,
999 unsigned LineNo, DICompositeType Ty,
1000 bool isLocalToUnit, bool isDefinition,
1001 unsigned ScopeLine, unsigned Flags,
1002 bool isOptimized, Function *Fn,
1003 MDNode *TParams, MDNode *Decl) {
1004 return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1005 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1006 Flags, isOptimized, Fn, TParams, Decl, nullptr,
1007 [&] (ArrayRef<Value *> Elts) {
1008 return MDNode::getTemporary(VMContext, Elts);
1012 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1013 StringRef LinkageName, DIFile F,
1014 unsigned LineNo, DICompositeType Ty,
1015 bool isLocalToUnit, bool isDefinition,
1016 unsigned VK, unsigned VIndex,
1017 DIType VTableHolder, unsigned Flags,
1018 bool isOptimized, Function *Fn,
1020 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1021 "function types should be subroutines");
1022 assert(getNonCompileUnitScope(Context) &&
1023 "Methods should have both a Context and a context that isn't "
1024 "the compile unit.");
1025 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1028 .concat(LinkageName)
1030 .concat(isLocalToUnit)
1031 .concat(isDefinition)
1035 .concat(isOptimized)
1037 // FIXME: Do we want to use different scope/lines?
1039 F.getFileNode(), DIScope(Context).getRef(), Ty,
1040 VTableHolder.getRef(), Fn, TParam, nullptr, nullptr};
1041 MDNode *Node = MDNode::get(VMContext, Elts);
1043 AllSubprograms.push_back(Node);
1044 DISubprogram S(Node);
1045 assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1049 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1050 DIFile File, unsigned LineNo) {
1051 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1055 File.getFileNode(), getNonCompileUnitScope(Scope)};
1056 DINameSpace R(MDNode::get(VMContext, Elts));
1057 assert(R.Verify() &&
1058 "createNameSpace should return a verifiable DINameSpace");
1062 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1064 unsigned Discriminator) {
1065 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1066 .concat(Discriminator)
1068 File.getFileNode(), Scope};
1069 DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1072 "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1076 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1077 unsigned Line, unsigned Col) {
1078 // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1079 // I believe the right way is to have a self-referential element in the node.
1080 // Also: why do we bother with line/column - they're not used and the
1081 // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1082 // for uniquing, yet then we have this other solution (because line/col were
1083 // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1085 // Defeat MDNode uniquing for lexical blocks by using unique id.
1086 static unsigned int unique_id = 0;
1087 Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1090 .concat(unique_id++)
1092 File.getFileNode(), getNonCompileUnitScope(Scope)};
1093 DILexicalBlock R(MDNode::get(VMContext, Elts));
1094 assert(R.Verify() &&
1095 "createLexicalBlock should return a verifiable DILexicalBlock");
1099 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1101 Instruction *InsertBefore) {
1102 assert(Storage && "no storage passed to dbg.declare");
1103 assert(VarInfo.isVariable() &&
1104 "empty or invalid DIVariable passed to dbg.declare");
1106 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1108 Value *Args[] = {MDNode::get(Storage->getContext(), Storage), VarInfo, Expr};
1109 return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1112 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1114 BasicBlock *InsertAtEnd) {
1115 assert(Storage && "no storage passed to dbg.declare");
1116 assert(VarInfo.isVariable() &&
1117 "empty or invalid DIVariable passed to dbg.declare");
1119 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1121 Value *Args[] = {MDNode::get(Storage->getContext(), Storage), VarInfo, Expr};
1123 // If this block already has a terminator then insert this intrinsic
1124 // before the terminator.
1125 if (TerminatorInst *T = InsertAtEnd->getTerminator())
1126 return CallInst::Create(DeclareFn, Args, "", T);
1128 return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1131 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1134 Instruction *InsertBefore) {
1135 assert(V && "no value passed to dbg.value");
1136 assert(VarInfo.isVariable() &&
1137 "empty or invalid DIVariable passed to dbg.value");
1139 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1141 Value *Args[] = {MDNode::get(V->getContext(), V),
1142 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1144 return CallInst::Create(ValueFn, Args, "", InsertBefore);
1147 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1150 BasicBlock *InsertAtEnd) {
1151 assert(V && "no value passed to dbg.value");
1152 assert(VarInfo.isVariable() &&
1153 "empty or invalid DIVariable passed to dbg.value");
1155 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1157 Value *Args[] = {MDNode::get(V->getContext(), V),
1158 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1160 return CallInst::Create(ValueFn, Args, "", InsertAtEnd);