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 /// \brief Whether there are any fields yet.
30 /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
31 /// may have been called already with an empty string.
33 SmallVector<char, 256> Chars;
36 HeaderBuilder() : IsEmpty(true) {}
37 HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
38 HeaderBuilder(HeaderBuilder &&X)
39 : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
41 template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
46 Twine(X).toVector(Chars);
50 MDString *get(LLVMContext &Context) const {
51 return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
54 static HeaderBuilder get(unsigned Tag) {
55 return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
60 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
61 : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
62 TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
63 DeclareFn(nullptr), ValueFn(nullptr),
64 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
66 void DIBuilder::trackIfUnresolved(MDNode *N) {
72 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
73 UnresolvedNodes.emplace_back(N);
76 void DIBuilder::finalize() {
77 DIArray Enums = getOrCreateArray(AllEnumTypes);
78 DIType(TempEnumTypes).replaceAllUsesWith(Enums);
80 SmallVector<Metadata *, 16> RetainValues;
81 // Declarations and definitions of the same type may be retained. Some
82 // clients RAUW these pairs, leaving duplicates in the retained types
83 // list. Use a set to remove the duplicates while we transform the
84 // TrackingVHs back into Values.
85 SmallPtrSet<Metadata *, 16> RetainSet;
86 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
87 if (RetainSet.insert(AllRetainTypes[I]).second)
88 RetainValues.push_back(AllRetainTypes[I]);
89 DIArray RetainTypes = getOrCreateArray(RetainValues);
90 DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
92 DIArray SPs = getOrCreateArray(AllSubprograms);
93 DIType(TempSubprograms).replaceAllUsesWith(SPs);
94 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
95 DISubprogram SP(SPs.getElement(i));
96 if (MDNode *Temp = SP.getVariablesNodes()) {
97 const auto &PV = PreservedVariables.lookup(SP);
98 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
99 DIArray AV = getOrCreateArray(Variables);
100 DIType(Temp).replaceAllUsesWith(AV);
104 DIArray GVs = getOrCreateArray(AllGVs);
105 DIType(TempGVs).replaceAllUsesWith(GVs);
107 SmallVector<Metadata *, 16> RetainValuesI(AllImportedModules.begin(),
108 AllImportedModules.end());
109 DIArray IMs = getOrCreateArray(RetainValuesI);
110 DIType(TempImportedModules).replaceAllUsesWith(IMs);
112 // Now that all temp nodes have been replaced or deleted, resolve remaining
114 for (const auto &N : UnresolvedNodes)
115 if (N && !N->isResolved())
117 UnresolvedNodes.clear();
119 // Can't handle unresolved nodes anymore.
120 AllowUnresolvedNodes = false;
123 /// If N is compile unit return NULL otherwise return N.
124 static MDScope *getNonCompileUnitScope(MDNode *N) {
125 if (!N || isa<MDCompileUnit>(N))
127 return cast<MDScope>(N);
130 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
132 StringRef Producer, bool isOptimized,
133 StringRef Flags, unsigned RunTimeVer,
135 DebugEmissionKind Kind,
136 bool EmitDebugInfo) {
138 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
139 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
140 "Invalid Language tag");
141 assert(!Filename.empty() &&
142 "Unable to create compile unit without filename");
144 // TODO: Once we make MDCompileUnit distinct, stop using temporaries here
145 // (just start with operands assigned to nullptr).
146 TempEnumTypes = MDTuple::getTemporary(VMContext, None).release();
147 TempRetainTypes = MDTuple::getTemporary(VMContext, None).release();
148 TempSubprograms = MDTuple::getTemporary(VMContext, None).release();
149 TempGVs = MDTuple::getTemporary(VMContext, None).release();
150 TempImportedModules = MDTuple::getTemporary(VMContext, None).release();
152 // TODO: Switch to getDistinct(). We never want to merge compile units based
154 MDNode *CUNode = MDCompileUnit::get(
155 VMContext, Lang, MDFile::get(VMContext, Filename, Directory), Producer,
156 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes,
157 TempRetainTypes, TempSubprograms, TempGVs, TempImportedModules);
159 // Create a named metadata so that it is easier to find cu in a module.
160 // Note that we only generate this when the caller wants to actually
161 // emit debug information. When we are only interested in tracking
162 // source line locations throughout the backend, we prevent codegen from
163 // emitting debug info in the final output by not generating llvm.dbg.cu.
165 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
166 NMD->addOperand(CUNode);
169 trackIfUnresolved(CUNode);
170 return DICompileUnit(CUNode);
173 static DIImportedEntity
174 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
175 Metadata *NS, unsigned Line, StringRef Name,
176 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
177 DIImportedEntity M = MDImportedEntity::get(C, Tag, Context, NS, Line, Name);
178 assert(M.Verify() && "Imported module should be valid");
179 AllImportedModules.emplace_back(M.get());
183 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
186 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187 Context, NS, Line, StringRef(), AllImportedModules);
190 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
193 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
194 Context, NS, Line, StringRef(), AllImportedModules);
197 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
199 unsigned Line, StringRef Name) {
200 // Make sure to use the unique identifier based metadata reference for
201 // types that have one.
203 Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
204 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
205 Context, V, Line, Name,
209 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
210 DIImportedEntity Imp,
211 unsigned Line, StringRef Name) {
212 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
213 Context, Imp, Line, Name, AllImportedModules);
216 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
217 return MDFile::get(VMContext, Filename, Directory);
220 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
221 assert(!Name.empty() && "Unable to create enumerator without name");
222 return MDEnumerator::get(VMContext, Val, Name);
225 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
226 assert(!Name.empty() && "Unable to create type without name");
227 return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
230 DIBasicType DIBuilder::createNullPtrType() {
231 return createUnspecifiedType("decltype(nullptr)");
235 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
236 uint64_t AlignInBits, unsigned Encoding) {
237 assert(!Name.empty() && "Unable to create type without name");
238 return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
239 AlignInBits, Encoding);
242 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
243 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
244 FromTy.getRef(), 0, 0, 0, 0);
248 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
249 uint64_t AlignInBits, StringRef Name) {
250 // FIXME: Why is there a name here?
251 return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
252 nullptr, 0, nullptr, PointeeTy.getRef(), SizeInBits,
257 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
258 uint64_t SizeInBits, uint64_t AlignInBits) {
259 return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
260 nullptr, 0, nullptr, PointeeTy.getRef(), SizeInBits,
261 AlignInBits, 0, 0, Base.getRef());
264 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
265 assert(RTy.isType() && "Unable to create reference type");
266 return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
267 RTy.getRef(), 0, 0, 0, 0);
270 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
271 unsigned LineNo, DIDescriptor Context) {
272 return MDDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name,
273 File.getFileNode(), LineNo,
274 DIScope(getNonCompileUnitScope(Context)).getRef(),
275 Ty.getRef(), 0, 0, 0, 0);
278 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
279 // typedefs are encoded in DIDerivedType format.
280 assert(Ty.isType() && "Invalid type!");
281 assert(FriendTy.isType() && "Invalid friend type!");
282 return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
283 Ty.getRef(), FriendTy.getRef(), 0, 0, 0, 0);
286 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
289 assert(Ty.isType() && "Unable to create inheritance");
290 return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
291 0, Ty.getRef(), BaseTy.getRef(), 0, 0, BaseOffset,
295 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
296 DIFile File, unsigned LineNumber,
298 uint64_t AlignInBits,
299 uint64_t OffsetInBits, unsigned Flags,
301 return MDDerivedType::get(
302 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
303 DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(), SizeInBits,
304 AlignInBits, OffsetInBits, Flags);
307 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
309 return ConstantAsMetadata::get(C);
313 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
314 StringRef Name, DIFile File,
315 unsigned LineNumber, DIType Ty,
317 llvm::Constant *Val) {
318 // TAG_member is encoded in DIDerivedType format.
319 Flags |= DIDescriptor::FlagStaticMember;
320 return MDDerivedType::get(
321 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
322 DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(), 0, 0, 0,
323 Flags, getConstantOrNull(Val));
326 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
329 uint64_t AlignInBits,
330 uint64_t OffsetInBits, unsigned Flags,
331 DIType Ty, MDNode *PropertyNode) {
332 return MDDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
333 LineNumber, getNonCompileUnitScope(File),
334 Ty.getRef(), SizeInBits, AlignInBits, OffsetInBits,
335 Flags, PropertyNode);
339 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
340 StringRef GetterName, StringRef SetterName,
341 unsigned PropertyAttributes, DIType Ty) {
342 return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
343 SetterName, PropertyAttributes, Ty);
346 DITemplateTypeParameter
347 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
349 assert(!DIScope(getNonCompileUnitScope(Context)).getRef() &&
350 "Expected compile unit");
351 return MDTemplateTypeParameter::get(VMContext, Name, Ty.getRef());
354 static DITemplateValueParameter
355 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
356 DIDescriptor Context, StringRef Name,
357 DIType Ty, Metadata *MD) {
358 assert(!DIScope(getNonCompileUnitScope(Context)).getRef() &&
359 "Expected compile unit");
360 return MDTemplateValueParameter::get(VMContext, Tag, Name, Ty.getRef(), MD);
363 DITemplateValueParameter
364 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
365 DIType Ty, Constant *Val) {
366 return createTemplateValueParameterHelper(
367 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
368 getConstantOrNull(Val));
371 DITemplateValueParameter
372 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
373 DIType Ty, StringRef Val) {
374 return createTemplateValueParameterHelper(
375 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
376 MDString::get(VMContext, Val));
379 DITemplateValueParameter
380 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
381 DIType Ty, DIArray Val) {
382 return createTemplateValueParameterHelper(
383 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
387 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
388 DIFile File, unsigned LineNumber,
390 uint64_t AlignInBits,
391 uint64_t OffsetInBits,
392 unsigned Flags, DIType DerivedFrom,
395 MDNode *TemplateParams,
396 StringRef UniqueIdentifier) {
397 assert((!Context || Context.isScope() || Context.isType()) &&
398 "createClassType should be called with a valid Context");
399 // TAG_class_type is encoded in DICompositeType format.
400 DICompositeType R = MDCompositeType::get(
401 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
402 DIScope(getNonCompileUnitScope(Context)).getRef(), DerivedFrom.getRef(),
403 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, 0,
404 VTableHolder.getRef(), TemplateParams, UniqueIdentifier);
405 if (!UniqueIdentifier.empty())
407 trackIfUnresolved(R);
411 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
412 StringRef Name, DIFile File,
415 uint64_t AlignInBits,
416 unsigned Flags, DIType DerivedFrom,
418 unsigned RunTimeLang,
420 StringRef UniqueIdentifier) {
421 DICompositeType R = MDCompositeType::get(
422 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
423 DIScope(getNonCompileUnitScope(Context)).getRef(), DerivedFrom.getRef(),
424 SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang,
425 VTableHolder.getRef(), nullptr, UniqueIdentifier);
426 if (!UniqueIdentifier.empty())
428 trackIfUnresolved(R);
432 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
433 DIFile File, unsigned LineNumber,
435 uint64_t AlignInBits, unsigned Flags,
437 unsigned RunTimeLang,
438 StringRef UniqueIdentifier) {
439 DICompositeType R = MDCompositeType::get(
440 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
441 DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
442 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
444 if (!UniqueIdentifier.empty())
446 trackIfUnresolved(R);
450 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
451 DITypeArray ParameterTypes,
453 return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
456 DICompositeType DIBuilder::createEnumerationType(
457 DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
458 uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
459 DIType UnderlyingType, StringRef UniqueIdentifier) {
460 DICompositeType CTy = MDCompositeType::get(
461 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
462 DIScope(getNonCompileUnitScope(Scope)).getRef(), UnderlyingType.getRef(),
463 SizeInBits, AlignInBits, 0, 0, Elements, 0, nullptr, nullptr,
465 AllEnumTypes.push_back(CTy);
466 if (!UniqueIdentifier.empty())
468 trackIfUnresolved(CTy);
472 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
473 DIType Ty, DIArray Subscripts) {
474 auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
475 nullptr, 0, nullptr, Ty.getRef(), Size,
476 AlignInBits, 0, 0, Subscripts, 0, nullptr);
477 trackIfUnresolved(R);
481 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
482 DIType Ty, DIArray Subscripts) {
483 auto *R = MDCompositeType::get(
484 VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty.getRef(),
485 Size, AlignInBits, 0, DIType::FlagVector, Subscripts, 0, nullptr);
486 trackIfUnresolved(R);
490 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
491 unsigned FlagsToSet) {
492 TempMDType NewTy = cast<MDType>(static_cast<MDNode *>(Ty))->clone();
493 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
494 return MDNode::replaceWithUniqued(std::move(NewTy));
497 DIType DIBuilder::createArtificialType(DIType Ty) {
498 // FIXME: Restrict this to the nodes where it's valid.
499 if (Ty.isArtificial())
501 return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
504 DIType DIBuilder::createObjectPointerType(DIType Ty) {
505 // FIXME: Restrict this to the nodes where it's valid.
506 if (Ty.isObjectPointer())
508 unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
509 return createTypeWithFlags(VMContext, Ty, Flags);
512 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
514 DIBasicType DIBuilder::createUnspecifiedParameter() {
515 return DIBasicType();
519 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
520 DIFile F, unsigned Line, unsigned RuntimeLang,
521 uint64_t SizeInBits, uint64_t AlignInBits,
522 StringRef UniqueIdentifier) {
523 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
524 // replaceWithUniqued().
525 DICompositeType RetTy = MDCompositeType::get(
526 VMContext, Tag, Name, F.getFileNode(), Line,
527 DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
528 AlignInBits, 0, DIDescriptor::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
529 nullptr, UniqueIdentifier);
530 if (!UniqueIdentifier.empty())
532 trackIfUnresolved(RetTy);
536 DICompositeType DIBuilder::createReplaceableCompositeType(
537 unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
538 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
539 unsigned Flags, StringRef UniqueIdentifier) {
540 DICompositeType RetTy =
541 MDCompositeType::getTemporary(
542 VMContext, Tag, Name, F.getFileNode(), Line,
543 DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
544 AlignInBits, 0, Flags, nullptr, RuntimeLang,
545 nullptr, nullptr, UniqueIdentifier).release();
546 if (!UniqueIdentifier.empty())
548 trackIfUnresolved(RetTy);
552 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
553 return DIArray(MDNode::get(VMContext, Elements));
556 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
557 SmallVector<llvm::Metadata *, 16> Elts;
558 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
559 if (Elements[i] && isa<MDNode>(Elements[i]))
560 Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
562 Elts.push_back(Elements[i]);
564 return DITypeArray(MDNode::get(VMContext, Elts));
567 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
568 return MDSubrange::get(VMContext, Count, Lo);
571 static void checkGlobalVariableScope(DIDescriptor Context) {
572 MDNode *TheCtx = getNonCompileUnitScope(Context);
573 if (DIScope(TheCtx).isCompositeType()) {
574 assert(!DICompositeType(TheCtx).getIdentifier() &&
575 "Context of a global variable should not be a type with identifier");
579 DIGlobalVariable DIBuilder::createGlobalVariable(
580 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
581 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
583 checkGlobalVariableScope(Context);
585 auto *N = MDGlobalVariable::get(
586 VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName, F,
587 LineNumber, Ty, isLocalToUnit, true, getConstantOrNull(Val),
588 cast_or_null<MDDerivedType>(Decl));
593 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
594 DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
595 unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
597 checkGlobalVariableScope(Context);
599 return MDGlobalVariable::getTemporary(
600 VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName,
601 F, LineNumber, Ty, isLocalToUnit, false, getConstantOrNull(Val),
602 cast_or_null<MDDerivedType>(Decl)).release();
605 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
606 StringRef Name, DIFile File,
607 unsigned LineNo, DITypeRef Ty,
608 bool AlwaysPreserve, unsigned Flags,
610 // FIXME: Why getNonCompileUnitScope()?
611 // FIXME: Why is "!Context" okay here?
612 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
613 // the only valid scopes)?
614 DIDescriptor Context(getNonCompileUnitScope(Scope));
615 assert((!Context || Context.isScope()) &&
616 "createLocalVariable should be called with a valid Context");
618 auto *Node = MDLocalVariable::get(VMContext, Tag,
619 cast_or_null<MDLocalScope>(Context.get()),
620 Name, File, LineNo, Ty, ArgNo, Flags);
621 if (AlwaysPreserve) {
622 // The optimizer may remove local variable. If there is an interest
623 // to preserve variable info in such situation then stash it in a
625 DISubprogram Fn(getDISubprogram(Scope));
626 assert(Fn && "Missing subprogram for local variable");
627 PreservedVariables[Fn].emplace_back(Node);
632 DIExpression DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
633 return MDExpression::get(VMContext, Addr);
636 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
637 // TODO: Remove the callers of this signed version and delete.
638 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
639 return createExpression(Addr);
642 DIExpression DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
643 unsigned SizeInBytes) {
644 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
645 return MDExpression::get(VMContext, Addr);
648 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
649 StringRef LinkageName, DIFile File,
650 unsigned LineNo, DICompositeType Ty,
651 bool isLocalToUnit, bool isDefinition,
652 unsigned ScopeLine, unsigned Flags,
653 bool isOptimized, Function *Fn,
654 MDNode *TParams, MDNode *Decl) {
655 // dragonegg does not generate identifier for types, so using an empty map
656 // to resolve the context should be fine.
657 DITypeIdentifierMap EmptyMap;
658 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
659 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
660 Flags, isOptimized, Fn, TParams, Decl);
663 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
664 StringRef LinkageName, DIFile File,
665 unsigned LineNo, DICompositeType Ty,
666 bool isLocalToUnit, bool isDefinition,
667 unsigned ScopeLine, unsigned Flags,
668 bool isOptimized, Function *Fn,
669 MDNode *TParams, MDNode *Decl) {
670 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
671 "function types should be subroutines");
672 auto *Node = MDSubprogram::get(
673 VMContext, DIScope(getNonCompileUnitScope(Context)).getRef(), Name,
674 LinkageName, File.getFileNode(), LineNo, Ty, isLocalToUnit, isDefinition,
675 ScopeLine, nullptr, 0, 0, Flags, isOptimized, getConstantOrNull(Fn),
676 TParams, Decl, MDNode::getTemporary(VMContext, None).release());
679 AllSubprograms.push_back(Node);
680 trackIfUnresolved(Node);
685 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
686 StringRef LinkageName, DIFile File,
687 unsigned LineNo, DICompositeType Ty,
688 bool isLocalToUnit, bool isDefinition,
689 unsigned ScopeLine, unsigned Flags,
690 bool isOptimized, Function *Fn,
691 MDNode *TParams, MDNode *Decl) {
692 return MDSubprogram::getTemporary(
693 VMContext, DIScope(getNonCompileUnitScope(Context)).getRef(), Name,
694 LinkageName, File.getFileNode(), LineNo, Ty, isLocalToUnit,
695 isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
696 getConstantOrNull(Fn), TParams, Decl, nullptr).release();
699 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
700 StringRef LinkageName, DIFile F,
701 unsigned LineNo, DICompositeType Ty,
702 bool isLocalToUnit, bool isDefinition,
703 unsigned VK, unsigned VIndex,
704 DIType VTableHolder, unsigned Flags,
705 bool isOptimized, Function *Fn,
707 assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
708 "function types should be subroutines");
709 assert(getNonCompileUnitScope(Context) &&
710 "Methods should have both a Context and a context that isn't "
711 "the compile unit.");
712 // FIXME: Do we want to use different scope/lines?
713 auto *Node = MDSubprogram::get(
714 VMContext, DIScope(Context).getRef(), Name, LinkageName, F.getFileNode(),
715 LineNo, Ty, isLocalToUnit, isDefinition, LineNo, VTableHolder.getRef(),
716 VK, VIndex, Flags, isOptimized, getConstantOrNull(Fn), TParam, nullptr,
720 AllSubprograms.push_back(Node);
721 DISubprogram S(Node);
722 assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
723 trackIfUnresolved(S);
727 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
728 DIFile File, unsigned LineNo) {
729 DINameSpace R = MDNamespace::get(VMContext, getNonCompileUnitScope(Scope),
730 File.getFileNode(), Name, LineNo);
732 "createNameSpace should return a verifiable DINameSpace");
736 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
738 unsigned Discriminator) {
739 DILexicalBlockFile R = MDLexicalBlockFile::get(
740 VMContext, Scope, File.getFileNode(), Discriminator);
743 "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
747 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
748 unsigned Line, unsigned Col) {
749 // Make these distinct, to avoid merging two lexical blocks on the same
751 DILexicalBlock R = MDLexicalBlock::getDistinct(
752 VMContext, getNonCompileUnitScope(Scope), File.getFileNode(), Line, Col);
754 "createLexicalBlock should return a verifiable DILexicalBlock");
758 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
759 assert(V && "no value passed to dbg intrinsic");
760 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
763 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
765 Instruction *InsertBefore) {
766 assert(VarInfo.isVariable() &&
767 "empty or invalid DIVariable passed to dbg.declare");
769 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
771 trackIfUnresolved(VarInfo);
772 trackIfUnresolved(Expr);
773 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
774 MetadataAsValue::get(VMContext, VarInfo),
775 MetadataAsValue::get(VMContext, Expr)};
776 return CallInst::Create(DeclareFn, Args, "", InsertBefore);
779 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
781 BasicBlock *InsertAtEnd) {
782 assert(VarInfo.isVariable() &&
783 "empty or invalid DIVariable passed to dbg.declare");
785 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
787 trackIfUnresolved(VarInfo);
788 trackIfUnresolved(Expr);
789 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
790 MetadataAsValue::get(VMContext, VarInfo),
791 MetadataAsValue::get(VMContext, Expr)};
793 // If this block already has a terminator then insert this intrinsic
794 // before the terminator.
795 if (TerminatorInst *T = InsertAtEnd->getTerminator())
796 return CallInst::Create(DeclareFn, Args, "", T);
798 return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
801 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
804 Instruction *InsertBefore) {
805 assert(V && "no value passed to dbg.value");
806 assert(VarInfo.isVariable() &&
807 "empty or invalid DIVariable passed to dbg.value");
809 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
811 trackIfUnresolved(VarInfo);
812 trackIfUnresolved(Expr);
813 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
814 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
815 MetadataAsValue::get(VMContext, VarInfo),
816 MetadataAsValue::get(VMContext, Expr)};
817 return CallInst::Create(ValueFn, Args, "", InsertBefore);
820 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
823 BasicBlock *InsertAtEnd) {
824 assert(V && "no value passed to dbg.value");
825 assert(VarInfo.isVariable() &&
826 "empty or invalid DIVariable passed to dbg.value");
828 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
830 trackIfUnresolved(VarInfo);
831 trackIfUnresolved(Expr);
832 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
833 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
834 MetadataAsValue::get(VMContext, VarInfo),
835 MetadataAsValue::get(VMContext, Expr)};
836 return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
839 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
840 T.setContainingType(VTableHolder);
842 // If this didn't create a self-reference, just return.
843 if (T != VTableHolder)
846 // Look for unresolved operands. T will drop RAUW support, orphaning any
847 // cycles underneath it.
849 for (const MDOperand &O : T->operands())
850 if (auto *N = dyn_cast_or_null<MDNode>(O))
851 trackIfUnresolved(N);
854 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
856 T.setArrays(Elements, TParams);
858 // If T isn't resolved, there's no problem.
859 if (!T->isResolved())
862 // If "T" is resolved, it may be due to a self-reference cycle. Track the
863 // arrays explicitly if they're unresolved, or else the cycles will be
866 trackIfUnresolved(Elements);
868 trackIfUnresolved(TParams);